muttakin2301/ccr2000 huggingface dataset:
Code review comment: We have a ton of functions in the OIDC code the only difference is that they are all unique in their structure, but here they are the same hence I suggested it :-)

Code under review:
public Object handle(InvocationContext ic) throws Exception {
        if (alreadyHandled(ic)) {
            return ic.proceed();
        }
        Class<?> returnType = ic.getMethod().getReturnType();
        if (Uni.class.isAssignableFrom(returnType)) {
            return constrainer.nonBlockingCheck(ic.getMethod(), ic.getParameters())
                    .onItem().transformToUni(new Function<Object, Uni<?>>() {
                        @Override
                        public Uni<?> apply(Object o) {
                            try {
                                return (Uni<?>) ic.proceed();
                            } catch (Exception e) {
                                return Uni.createFrom().failure(e);
                            }
                        }
                    });
        } else if (CompletionStage.class.isAssignableFrom(returnType)) {
            return constrainer.nonBlockingCheck(ic.getMethod(), ic.getParameters())
                    .subscribeAsCompletionStage()
                    .thenApply(whatever -> {
                        try {
                            return (CompletionStage) ic.proceed();
                        } catch (Exception e) {
                            return CompletableFuture.failedFuture(e);
                        }
                    });
        } else if (returnType == Multi.class) {
            return constrainer.nonBlockingCheck(ic.getMethod(), ic.getParameters())
                    .onItem().transformToMulti(whatever -> {
                        try {
                            return (Multi) ic.proceed();
                        } catch (Exception e) {
                            return Multi.createFrom().failure(e);
                        }
                    });
        } else {
            constrainer.check(ic.getMethod(), ic.getParameters());
            return ic.proceed();
        }
    }

Line commented on: @Override

Revised code:
public Object handle(InvocationContext ic) throws Exception {
        if (alreadyHandled(ic)) {
            return ic.proceed();
        }
        Class<?> returnType = ic.getMethod().getReturnType();
        if (Uni.class.isAssignableFrom(returnType)) {
            return constrainer.nonBlockingCheck(ic.getMethod(), ic.getParameters())
                    .onItem().transformToUni(new UniContinuation(ic));
        } else if (CompletionStage.class.isAssignableFrom(returnType)) {
            return constrainer.nonBlockingCheck(ic.getMethod(), ic.getParameters())
                    .subscribeAsCompletionStage()
                    .thenApply(new CompletionStageContinuation(ic));
        } else if (Multi.class.isAssignableFrom(returnType)) {
            return constrainer.nonBlockingCheck(ic.getMethod(), ic.getParameters())
                    .onItem().transformToMulti(new MultiContinuation(ic));
        } else {
            constrainer.check(ic.getMethod(), ic.getParameters());
            return ic.proceed();
        }
    }
Code review comment: ```suggestion             sb.append(", enforceSort=").append(node.getEnforceSortColumns()); ```

Code under review:
public String visitLogicalAnalytic(LogicalWindowOperator node, Void context) {
            StringBuilder sb = new StringBuilder("LogicalWindowOperator");
            sb.append(" {window=").append(node.getWindowCall());
            sb.append(", partitions=").append(node.getPartitionExpressions());
            sb.append(", orderBy=").append(node.getOrderByElements());
            sb.append(", enforceSort").append(node.getEnforceSortColumns());
            sb.append("}");
            return sb.toString();
        }

Line commented on: sb.append(", enforceSort").append(node.getEnforceSortColumns());

Revised code:
public String visitLogicalAnalytic(LogicalWindowOperator node, Void context) {
            StringBuilder sb = new StringBuilder("LogicalWindowOperator");
            sb.append(" {window=").append(node.getWindowCall());
            sb.append(", partitions=").append(node.getPartitionExpressions());
            sb.append(", orderBy=").append(node.getOrderByElements());
            sb.append(", enforceSort").append(node.getEnforceSortColumns());
            sb.append("}");
            return sb.toString();
        }
Code review comment: Should this be `code >= TRANSIENT_ERROR && code < FATAL_ERROR`?

Code under review:
public static boolean isTransient(int code) {
        return code >= TRANSIENT_ERROR;
    }

Line commented on: return code >= TRANSIENT_ERROR;

Revised code:
public static boolean isTransient(int code) {
        return (code >= TRANSIENT_ERROR) && (code < FATAL_ERROR);
    }
Code review comment: +1. I'll update the code

Code under review:
public void assertRenewWorkerIdChange() {
        WorkerIdEvent mockWorkerIdEvent = mock(WorkerIdEvent.class);
        when(mockWorkerIdEvent.getWorkerId()).thenReturn(12223L);
        when(mockWorkerIdEvent.getInstanceId()).thenReturn(contextManager.getInstanceContext().getInstance().getInstanceDefinition().getInstanceId().getId());
        coordinator.renew(mockWorkerIdEvent);
        assertNotNull(contextManager.getInstanceContext());
        assertNotNull(contextManager.getInstanceContext().getInstance());
        assertThat(contextManager.getInstanceContext().getWorkerId(), is(12223L));
    }

Line commented on: WorkerIdEvent mockWorkerIdEvent = mock(WorkerIdEvent.class);

Revised code:
public void assertRenewWorkerIdChange() {
        WorkerIdEvent mockWorkerIdEvent = new WorkerIdEvent(contextManager.getInstanceContext().getInstance().getInstanceDefinition().getInstanceId().getId(), 12223L);
        coordinator.renew(mockWorkerIdEvent);
        assertThat(contextManager.getInstanceContext().getWorkerId(), is(12223L));
    }
Code review comment: you should use `org.assertj.core.api.Assumptions.assumeThat`

Code under review:
public static void checkEnv() {
        final String kubeConfigEnv = System.getenv("ITCASE_KUBECONFIG");
        assertThat(StringUtils.isNullOrWhitespaceOnly(kubeConfigEnv))
                .withFailMessage("ITCASE_KUBECONFIG environment is not set.")
                .isFalse();
        kubeConfigFile = kubeConfigEnv;
    }

Line commented on: assertThat(StringUtils.isNullOrWhitespaceOnly(kubeConfigEnv))

Revised code:
public static void checkEnv() {
        final String kubeConfigEnv = System.getenv("ITCASE_KUBECONFIG");
        assumeThat(kubeConfigEnv)
                .withFailMessage("ITCASE_KUBECONFIG environment is not set.")
                .isNotBlank();
        kubeConfigFile = kubeConfigEnv;
    }
Code review comment: Agree with formatting, extraction into a named method is probably not a good idea because the lambda is capturing `partitionId` from the enclosing scope.

Code under review:
void triggerPartitionStateCheck(ResultPartitionID partitionId) {
		partitionProducerStateProvider.requestPartitionProducerState(
			consumedResultId,
			partitionId, (responseHandle -> {
				boolean isProducingState = new RemoteChannelStateChecker(partitionId, owningTaskName)
					.isProducerReadyOrAbortConsumption(responseHandle);
				if (isProducingState) {
					try {
						retriggerPartitionRequest(partitionId.getPartitionId());
					} catch (IOException t) {
						responseHandle.failConsumption(t);
					}
				}
			}));
	}

Line commented on: partitionId, (responseHandle -> {

Revised code:
void triggerPartitionStateCheck(ResultPartitionID partitionId) {
		partitionProducerStateProvider.requestPartitionProducerState(
			consumedResultId,
			partitionId,
			((PartitionProducerStateProvider.ResponseHandle responseHandle) -> {
				boolean isProducingState = new RemoteChannelStateChecker(partitionId, owningTaskName)
					.isProducerReadyOrAbortConsumption(responseHandle);
				if (isProducingState) {
					try {
						retriggerPartitionRequest(partitionId.getPartitionId());
					} catch (IOException t) {
						responseHandle.failConsumption(t);
					}
				}
			}));
	}
Code review comment: Should not call `onClose()`, it will remove the accessController

Code under review:
public void onRefresh(boolean invalidCache) {
        super.onRefresh(invalidCache);
        onClose();
    }

Line commented on: onClose();

Revised code:
public void onRefresh(boolean invalidCache) {
        super.onRefresh(invalidCache);
        if (jdbcClient != null) {
            jdbcClient.closeClient();
        }
    }
Code review comment: @lirui-apache It's indeed unnecessary.

Code under review:
public void testHiveCommands() throws Exception {
		SqlParserHelper helper = new SqlParserHelper(SqlDialect.HIVE);
		parser = helper.getSqlParser();
		List<TestItem> testItems = Collections.singletonList(
			
			TestItem.validSql(SqlDialect.HIVE, "SHOW PARTITIONS t1", SqlCommand.SHOW_PARTITIONS, "SHOW PARTITIONS t1")
		);
		for (TestItem item : testItems) {
			tableEnv.getConfig().setSqlDialect(item.sqlDialect);
			runTestItem(item);
		}
	}

Line commented on: parser = helper.getSqlParser();

Revised code:
public void testHiveCommands() throws Exception {
		List<TestItem> testItems = Collections.singletonList(
			
			TestItem.validSql(SqlDialect.HIVE, "SHOW PARTITIONS t1", SqlCommand.SHOW_PARTITIONS, "SHOW PARTITIONS t1")
		);
		for (TestItem item : testItems) {
			tableEnv.getConfig().setSqlDialect(item.sqlDialect);
			runTestItem(item);
		}
	}
Code review comment: `parseCompoundAssignmentStmt()` is only called within `resumeParsing()` No other usage. Do we need that method?

Code under review:
public STNode resumeStatementNodeParsing(ParserRuleContext context, Object... args) {
        switch (context) {
            case STATEMENT:
                return parseStatement();
            case STATEMENT_WITHOUT_ANNOTS:
                return parseStatement((STNode) args[0]);
            case STMT_START_WITH_EXPR_RHS:
                return parseStatementStartWithExprRhs((STNode) args[0]);
            case STMT_START_BRACKETED_LIST_MEMBER:
                return parseStatementStartBracketedListMember();
            case VAR_DECL_STMT_RHS:
                return parseVarDeclRhs((STNode) args[0], (STNode) args[1], (STNode) args[2], (boolean) args[3]);
            case COMPOUND_ASSIGNMENT_STMT:
                return parseCompoundAssignmentStmt();
            default:
                return resumeActionOrExpressionNodesParsing(context, args);
        }
    }

Line commented on: return parseCompoundAssignmentStmt();

Revised code:
public STNode resumeStatementNodeParsing(ParserRuleContext context, Object... args) {
        switch (context) {
            case STATEMENT:
                return parseStatement();
            case STATEMENT_WITHOUT_ANNOTS:
                return parseStatement((STNode) args[0]);
            case STMT_START_WITH_EXPR_RHS:
                return parseStatementStartWithExprRhs((STNode) args[0]);
            case STMT_START_BRACKETED_LIST_MEMBER:
                return parseStatementStartBracketedListMember();
            case VAR_DECL_STMT_RHS:
                return parseVarDeclRhs((STNode) args[0], (STNode) args[1], (STNode) args[2], (boolean) args[3]);
            case LIST_MATCH_PATTERN_MEMBER_RHS:
                return parseListMatchPatternMemberRhs();
            case FIELD_MATCH_PATTERN_MEMBER:
                return parseFieldMatchPatternMember();
            case FIELD_MATCH_PATTERN_MEMBER_RHS:
                return parseFieldMatchPatternRhs();
            case FUNC_MATCH_PATTERN_OR_CONST_PATTERN:
                return parseFunctionalMatchPatternOrConsPattern((STNode) args[0]);
            case ARG_MATCH_PATTERN:
                return parseArgMatchPattern();
            case ARG_MATCH_PATTERN_RHS:
                return parseArgMatchPatternRhs();
            case OPTIONAL_MATCH_GUARD:
                return parseMatchGuard();
            case MATCH_PATTERN_START:
                return parseMatchPattern();
            case MATCH_PATTERN_RHS:
                return parseMatchPatternEnd();
            case RETRY_TYPE_PARAM_RHS:
                return parseRetryTypeParamRhs((STNode) args[0], (STNode) args[1]);
            case NAMESPACE_PREFIX:
                return parseNamespacePrefix();
            default:
                return resumeActionOrExpressionNodesParsing(context, args);
        }
    }
Code review comment: ```suggestion 		// let the first vertex acknowledge the checkpoint, and fail it afterwards 		// the failover strategy should then cancel all pending checkpoints on restart ```

Code under review:
public void abortPendingCheckpointsWhenRestartingTasks() throws Exception {
		final JobGraph jobGraph = createStreamingJobGraph();
		final ExecutionGraph executionGraph = createExecutionGraph(jobGraph);

		final Iterator<ExecutionVertex> vertexIterator = executionGraph.getAllExecutionVertices().iterator();
		final ExecutionVertex firstExecutionVertex = vertexIterator.next();

		setTaskRunning(executionGraph, firstExecutionVertex, vertexIterator.next());

		final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
		checkState(checkpointCoordinator != null);

		checkpointCoordinator.triggerCheckpoint(System.currentTimeMillis(),  false);
		final int pendingCheckpointsBeforeFailure = checkpointCoordinator.getNumberOfPendingCheckpoints();
		long checkpointId = checkpointCoordinator.getPendingCheckpoints().keySet().iterator().next();

		AcknowledgeCheckpoint acknowledgeCheckpoint = new AcknowledgeCheckpoint(
			firstExecutionVertex.getJobId(),
			firstExecutionVertex.getCurrentExecutionAttempt().getAttemptId(),
			checkpointId,
			mock(CheckpointMetrics.class),
			mock(TaskStateSnapshot.class));

		
		checkpointCoordinator.receiveAcknowledgeMessage(acknowledgeCheckpoint, "Unknown location");
		failVertex(firstExecutionVertex);

		assertThat(pendingCheckpointsBeforeFailure, is(equalTo(1)));
		assertNoPendingCheckpoints(checkpointCoordinator);
	}


Revised code:
public void abortPendingCheckpointsWhenRestartingTasks() throws Exception {
		final JobGraph jobGraph = createStreamingJobGraph();
		final ExecutionGraph executionGraph = createExecutionGraph(jobGraph);

		final Iterator<ExecutionVertex> vertexIterator = executionGraph.getAllExecutionVertices().iterator();
		final ExecutionVertex firstExecutionVertex = vertexIterator.next();

		setTasksRunning(executionGraph, firstExecutionVertex, vertexIterator.next());

		final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
		checkState(checkpointCoordinator != null);

		checkpointCoordinator.triggerCheckpoint(System.currentTimeMillis(),  false);
		assertEquals(1, checkpointCoordinator.getNumberOfPendingCheckpoints());
		long checkpointId = checkpointCoordinator.getPendingCheckpoints().keySet().iterator().next();

		AcknowledgeCheckpoint acknowledgeCheckpoint = new AcknowledgeCheckpoint(
			jobGraph.getJobID(),
			firstExecutionVertex.getCurrentExecutionAttempt().getAttemptId(),
			checkpointId);

		
		
		checkpointCoordinator.receiveAcknowledgeMessage(acknowledgeCheckpoint, "Unknown location");
		assertEquals(1, checkpointCoordinator.getNumberOfPendingCheckpoints());

		failVertex(firstExecutionVertex);
		assertEquals(1, checkpointCoordinator.getNumberOfPendingCheckpoints());
		manualMainThreadExecutor.triggerScheduledTasks();

		assertNoPendingCheckpoints(checkpointCoordinator);
	}
Code review comment: Removed the regex and refactor the previous logic

Code under review:
boolean validateFloatLiteral(Location pos, String numericLiteral) {
        double value = Double.parseDouble(numericLiteral);
        if (Double.isInfinite(value)) {
            dlog.error(pos, DiagnosticErrorCode.FLOAT_TOO_LARGE, numericLiteral);
            return false;
        }

        Pattern floatLiteral = Pattern.compile("[1-9]");
        Pattern floatLiteralWithExpIndicator = Pattern.compile("([1-9])(.*)([eEpP])");
        if (value == 0.0 && floatLiteral.matcher(numericLiteral).find() &&
                floatLiteralWithExpIndicator.matcher(numericLiteral).find()) {
            dlog.error(pos, DiagnosticErrorCode.FLOAT_TOO_SMALL, numericLiteral);
            return false;
        }
        return true;
    }

Line commented on: Pattern floatLiteralWithExpIndicator = Pattern.compile("([1-9])(.*)([eEpP])");

Revised code:
boolean validateFloatLiteral(Location pos, String numericLiteral) {
        double value = Double.parseDouble(numericLiteral);
        if (Double.isInfinite(value)) {
            dlog.error(pos, DiagnosticErrorCode.FLOAT_TOO_LARGE, numericLiteral);
            return false;
        }
        if (value != 0.0) {
            return true;
        }

        List<Character> exponentIndicator = List.of('e', 'E', 'p', 'P');
        for (int i = 0; i < numericLiteral.length(); i++) {
            char character = numericLiteral.charAt(i);
            if (exponentIndicator.contains(character)) {
                break;
            }
            if (numericLiteral.charAt(i) >= '1' && numericLiteral.charAt(i) <= '9') {
                dlog.error(pos, DiagnosticErrorCode.FLOAT_TOO_SMALL, numericLiteral);
                return false;
            }

        }
        return true;
    }
Code review comment: For performance, I want to exit this method early. And currently all PTFs have this catagory.

Code under review:
private static List<SqlIdentifier> getExplicitTableOperands(SqlNode node) {
        if (!(node instanceof SqlBasicCall)) {
            return null;
        }
        final SqlBasicCall call = (SqlBasicCall) node;

        if (!(call.getOperator() instanceof SqlFunction)) {
            return null;
        }
        final SqlFunction function = (SqlFunction) call.getOperator();

        if (function.getFunctionType() != SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION) {
            return null;
        }

        return call.getOperandList().stream()
                .map(
                        op -> {
                            if (op.getKind() == SqlKind.EXPLICIT_TABLE) {
                                final SqlBasicCall opCall = (SqlBasicCall) op;
                                if (opCall.operandCount() == 1
                                        && opCall.operand(0) instanceof SqlIdentifier) {
                                    return (SqlIdentifier) opCall.operand(0);
                                }
                            }
                            return null;
                        })
                .collect(Collectors.toList());
    }

Line commented on: if (function.getFunctionType() != SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION) {

Revised code:
private static List<SqlIdentifier> getExplicitTableOperands(SqlNode node) {
        if (!(node instanceof SqlBasicCall)) {
            return null;
        }
        final SqlBasicCall call = (SqlBasicCall) node;

        if (!(call.getOperator() instanceof SqlFunction)) {
            return null;
        }
        final SqlFunction function = (SqlFunction) call.getOperator();

        if (function.getFunctionType() != SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION) {
            return null;
        }

        return call.getOperandList().stream()
                .map(
                        op -> {
                            if (op.getKind() == SqlKind.EXPLICIT_TABLE) {
                                final SqlBasicCall opCall = (SqlBasicCall) op;
                                if (opCall.operandCount() == 1
                                        && opCall.operand(0) instanceof SqlIdentifier) {
                                    return (SqlIdentifier) opCall.operand(0);
                                }
                            }
                            return null;
                        })
                .collect(Collectors.toList());
    }
Code review comment: Should we use `nextCheckpointTriggeringRelativeTime += checkpointInterval` for consistency with the semantics of `scheduleAtFixedRate`()?  Then we can schedule runnable with delay = `nextCheckpointTriggeringRelativeTime - clock.relativeTimeMillis()`.

Code under review:
public void run() {
            synchronized (lock) {
                if (currentPeriodicTrigger != this) {
                    
                    
                    return;
                }

                long checkpointInterval = getCurrentCheckpointInterval();
                if (checkpointInterval != Long.MAX_VALUE) {
                    nextCheckpointTriggeringRelativeTime =
                            clock.relativeTimeMillis() + checkpointInterval;
                    currentPeriodicTriggerFuture =
                            timer.schedule(this, checkpointInterval, TimeUnit.MILLISECONDS);
                } else {
                    nextCheckpointTriggeringRelativeTime = Long.MAX_VALUE;
                    currentPeriodicTrigger = null;
                    currentPeriodicTriggerFuture = null;
                }
            }

            try {
                triggerCheckpoint(checkpointProperties, null, true);
            } catch (Exception e) {
                LOG.error("Exception while triggering checkpoint for job {}.", job, e);
            }
        }

Line commented on: clock.relativeTimeMillis() + checkpointInterval;

Revised code:
public void run() {
            synchronized (lock) {
                if (currentPeriodicTrigger != this) {
                    
                    
                    return;
                }

                long checkpointInterval = getCurrentCheckpointInterval();
                if (checkpointInterval
                        != CheckpointCoordinatorConfiguration.DISABLED_CHECKPOINT_INTERVAL) {
                    nextCheckpointTriggeringRelativeTime += checkpointInterval;
                    currentPeriodicTriggerFuture =
                            timer.schedule(
                                    this,
                                    Math.max(
                                            0,
                                            nextCheckpointTriggeringRelativeTime
                                                    - clock.relativeTimeMillis()),
                                    TimeUnit.MILLISECONDS);
                } else {
                    nextCheckpointTriggeringRelativeTime = Long.MAX_VALUE;
                    currentPeriodicTrigger = null;
                    currentPeriodicTriggerFuture = null;
                }
            }

            try {
                triggerCheckpoint(checkpointProperties, null, true);
            } catch (Exception e) {
                LOG.error("Exception while triggering checkpoint for job {}.", job, e);
            }
        }
Code review comment: Can't the logic of choosing `ChangelogStreamHandleReader` be moved to the creator of this object?  So that: - `FsStateChangelogStorage` passes no-caching version to `FsStateChangelogStorageForRecovery` constructor - `FsStateChangelogStorageFactory` passes configuration, from which a caching version is built  (so there is no `null` and no `if` here)

Code under review:
public StateChangelogHandleReader<ChangelogStateHandleStreamImpl> createReader() {
        return new StateChangelogHandleStreamHandleReader(
                changelogHandleReaderWithCache != null
                        ? new StateChangeIteratorImpl(changelogHandleReaderWithCache)
                        : new StateChangeIteratorImpl());
    }

Line commented on: : new StateChangeIteratorImpl());

Revised code:
public StateChangelogHandleReader<ChangelogStateHandleStreamImpl> createReader() {
        return new StateChangelogHandleStreamHandleReader(
                new StateChangeIteratorImpl(changelogStreamHandleReader));
    }
Code review comment: If the class is available on the classpath, use `com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl.class.getName()` instead

Code under review:
public Identity(String domain, String service) {
        super("com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl");
        this.domain = domain;
        this.service = service;
    }

Line commented on: super("com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl");

Revised code:
public Identity(String domain, String service) {
        super("com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl");
        this.domain = domain;
        this.service = service;
    }
Code review comment: My intention was to add service keyword to service objects and listener keyword to listener objects. The type descriptors are not necessary as you suggested. Let's get rid of them. WDYT about the service declaration? should we keep the service keyword there?

Code under review:
public Optional<DocumentSymbol> transform(ListenerDeclarationNode listenerDeclarationNode) {
        StringBuilder name = new StringBuilder(SyntaxKind.LISTENER_KEYWORD.stringValue());
        Optional<TypeDescriptorNode> typeDescriptorNode = listenerDeclarationNode.typeDescriptor();
        if (typeDescriptorNode.isPresent()) {
            name.append(" " + typeDescriptorNode.get().toSourceCode());
        }
        name.append(" " + listenerDeclarationNode.variableName().text());
        SymbolKind symbolKind = SymbolKind.Object;
        Range range = DocumentSymbolUtil.generateNodeRange(listenerDeclarationNode);
        Optional<MetadataNode> metadata = listenerDeclarationNode.metadata();
        boolean isDeprecated = metadata.isPresent() &&
                DocumentSymbolUtil.isDeprecated(metadata.get());
        return Optional.ofNullable(createDocumentSymbol(name.toString(), symbolKind, null,
                range, range, isDeprecated, Collections.emptyList(), this.context));
    }

Line commented on: name.append(" " + typeDescriptorNode.get().toSourceCode());

Revised code:
public Optional<DocumentSymbol> transform(ListenerDeclarationNode listenerDeclarationNode) {
        String name = listenerDeclarationNode.variableName().text();
        SymbolKind symbolKind = SymbolKind.Object;
        Range range = DocumentSymbolUtil.generateNodeRange(listenerDeclarationNode);
        Optional<MetadataNode> metadata = listenerDeclarationNode.metadata();
        boolean isDeprecated = metadata.isPresent() &&
                DocumentSymbolUtil.isDeprecated(metadata.get());
        return Optional.of(createDocumentSymbol(name, symbolKind, range, range, isDeprecated,
                Collections.emptyList()));
    }
Code review comment: This check will always succeed as you are checking "a = a". Let's change the second param to the "Age" variable.

Code under review:
public void testPatchPreConditionSuccess() {
        options.setFilterPredicate("FROM person p WHERE p.lastName = '"+LAST_NAME+"'");
        Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations, options);
        assertEquals(patchedPerson.getAge(), patchedPerson.getAge());
    }

Line commented on: assertEquals(patchedPerson.getAge(), patchedPerson.getAge());

Revised code:
public void testPatchPreConditionSuccess() {
        options.setFilterPredicate("FROM person p WHERE p.lastName = '"+LAST_NAME+"'");
        Person patchedPerson = cosmosTemplate.patch(insertedPerson.getId(), new PartitionKey(insertedPerson.getLastName()), Person.class, operations, options);
        assertEquals(patchedPerson.getAge(), PATCH_AGE_1);
    }
Code review comment: The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method.

Code under review:
public void populatePropertyBag() {
        super.populatePropertyBag();

        synchronized(this) {
            setProperty(
                this,
                Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
                ChangeFeedStartFromTypes.LEASE);

            setProperty(
                this,
                Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
                this.eTag);

            this.feedRange.setProperties(
                this,
                true);
        }
    }

Line commented on: synchronized(this) {

Revised code:
public void populatePropertyBag() {
        super.populatePropertyBag();

        synchronized(this) {
            setProperty(
                this,
                Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
                ChangeFeedStartFromTypes.LEASE);

            setProperty(
                this,
                Constants.Properties.CHANGE_FEED_START_FROM_ETAG,
                this.eTag);

            this.feedRange.setProperties(
                this,
                true);
        }
    }
Code review comment: Remove trailing space in case the prefix already had one. ```suggestion         headers.set(name, (prefix == null) ? credential : prefix.trim() + " " + credential); ```

Code under review:
void setCredential(HttpHeaders headers) {
        String credential = this.credential.getKey();
        headers.set(name, (prefix == null) ? credential : prefix + " " + credential);
    }

Line commented on: headers.set(name, (prefix == null) ? credential : prefix + " " + credential);

Revised code:
void setCredential(HttpHeaders headers) {
        String credential = this.credential.getKey();
        headers.set(name, (prefix == null) ? credential : prefix + " " + credential);
    }
Code review comment: All `application/*` types require a charset? That doesn't seem right.

Code under review:
private boolean isStringMediaType(MediaType mediaType) {
        return mediaType.getType().equals("application")
                || (mediaType.getType().equals("text") && mediaType.getSubtype().equals("plain"));
    }

Line commented on: return mediaType.getType().equals("application")

Revised code:
private boolean isStringMediaType(MediaType mediaType) {
        String type = mediaType.getType();
        String subtype = mediaType.getSubtype();
        return (type.equals("application") && (subtype.contains("json") || subtype.contains("xml") || subtype.contains("yaml")))
                || type.equals("text");
    }
Code review comment: use request.isSetExtra() to check if the member is set.

Code under review:
private boolean loadTxnCommitImpl(TLoadTxnCommitRequest request) throws UserException {
        String cluster = request.getCluster();
        if (Strings.isNullOrEmpty(cluster)) {
            cluster = SystemInfoService.DEFAULT_CLUSTER;
        }

        checkPasswordAndPrivs(cluster, request.getUser(), request.getPasswd(), request.getDb(),
                request.getTbl(), request.getUser_ip(), PrivPredicate.LOAD);

        
        Catalog catalog = Catalog.getInstance();
        String fullDbName = ClusterNamespace.getFullName(cluster, request.getDb());
        Database db = catalog.getDb(fullDbName);
        if (db == null) {
            String dbName = fullDbName;
            if (Strings.isNullOrEmpty(request.getCluster())) {
                dbName = request.getDb();
            }
            throw new UserException("unknown database, database=" + dbName);
        }

        
        if (!Strings.isNullOrEmpty(request.getExtra())) {
            Catalog.getCurrentGlobalTransactionMgr()
                    .updateExtraInTransactionState(request.getTxnId(), request.getExtra());
        }

        return Catalog.getCurrentGlobalTransactionMgr().commitAndPublishTransaction(
                db, request.getTxnId(),
                TabletCommitInfo.fromThrift(request.getCommitInfos()),
                5000);
    }

Line commented on: if (!Strings.isNullOrEmpty(request.getExtra())) {

Revised code:
private boolean loadTxnCommitImpl(TLoadTxnCommitRequest request) throws UserException {
        String cluster = request.getCluster();
        if (Strings.isNullOrEmpty(cluster)) {
            cluster = SystemInfoService.DEFAULT_CLUSTER;
        }

        checkPasswordAndPrivs(cluster, request.getUser(), request.getPasswd(), request.getDb(),
                              request.getTbl(), request.getUser_ip(), PrivPredicate.LOAD);

        
        Catalog catalog = Catalog.getInstance();
        String fullDbName = ClusterNamespace.getFullName(cluster, request.getDb());
        Database db = catalog.getDb(fullDbName);
        if (db == null) {
            String dbName = fullDbName;
            if (Strings.isNullOrEmpty(request.getCluster())) {
                dbName = request.getDb();
            }
            throw new UserException("unknown database, database=" + dbName);
        }

        return Catalog.getCurrentGlobalTransactionMgr().commitAndPublishTransaction(
                db, request.getTxnId(),
                TabletCommitInfo.fromThrift(request.getCommitInfos()),
                5000, TxnCommitAttachment.fromThrift(request.txnCommitAttachment));
    }
Code review comment: This still appears to actually be a "FixedWindowsTableFunctionRel".

Code under review:
public PCollection<Row> expand(PCollectionList<Row> input) {
      checkArgument(
          input.size() == 1,
          "Wrong number of inputs for %s, expected 1 input but received: %s",
          BeamTableFunctionScanRel.class.getSimpleName(),
          input);
      String operatorName = ((RexCall) getCall()).getOperator().getName();
      checkArgument(
          operatorName.equals("TUMBLE"),
          "Only support TUMBLE table-valued function. Current operator: %s",
          operatorName);
      RexCall call = ((RexCall) getCall());
      RexInputRef wmCol = (RexInputRef) call.getOperands().get(1);
      PCollection<Row> upstream = input.get(0);
      Schema outputSchema = CalciteUtils.toSchema(getRowType());
      return upstream
          .apply(
              ParDo.of(
                  new FixedWindowDoFn(
                      FixedWindows.of(durationParameter(call.getOperands().get(2))),
                      wmCol.getIndex(),
                      outputSchema)))
          .setRowSchema(outputSchema);
    }

Line commented on: new FixedWindowDoFn(

Revised code:
public PCollection<Row> expand(PCollectionList<Row> input) {
      checkArgument(
          input.size() == 1,
          "Wrong number of inputs for %s, expected 1 input but received: %s",
          BeamTableFunctionScanRel.class.getSimpleName(),
          input);
      String operatorName = ((RexCall) getCall()).getOperator().getName();
      checkArgument(
          operatorName.equals("TUMBLE"),
          "Only support TUMBLE table-valued function. Current operator: %s",
          operatorName);
      RexCall call = ((RexCall) getCall());
      RexInputRef wmCol = (RexInputRef) call.getOperands().get(1);
      PCollection<Row> upstream = input.get(0);
      Schema outputSchema = CalciteUtils.toSchema(getRowType());
      return upstream
          .apply(
              ParDo.of(
                  new FixedWindowDoFn(
                      FixedWindows.of(durationParameter(call.getOperands().get(2))),
                      wmCol.getIndex(),
                      outputSchema)))
          .setRowSchema(outputSchema);
    }
Code review comment: @RocMarshal The archive types have not changed for over 2 years, maybe it is a good time to do this when there is a new archive type need to add  here.

Code under review:
private static boolean isArchiveOnlyIncludedInShipArchiveFiles(List<File> shipFiles) {
        long archivedFileCount =
                shipFiles.stream()
                        .filter(File::isFile)
                        .map(File::getName)
                        .map(String::toLowerCase)
                        .filter(
                                name ->
                                        name.endsWith(".tar.gz")
                                                || name.endsWith(".tar")
                                                || name.endsWith(".tgz")
                                                || name.endsWith(".dst")
                                                || name.endsWith(".jar")
                                                || name.endsWith(".zip"))
                        .count();
        return archivedFileCount == shipFiles.size();
    }

Line commented on: || name.endsWith(".zip"))

Revised code:
private static boolean isArchiveOnlyIncludedInShipArchiveFiles(List<File> shipFiles) {
        long archivedFileCount =
                shipFiles.stream()
                        .filter(File::isFile)
                        .map(File::getName)
                        .map(String::toLowerCase)
                        .filter(
                                name ->
                                        name.endsWith(".tar.gz")
                                                || name.endsWith(".tar")
                                                || name.endsWith(".tgz")
                                                || name.endsWith(".dst")
                                                || name.endsWith(".jar")
                                                || name.endsWith(".zip"))
                        .count();
        return archivedFileCount == shipFiles.size();
    }
Code review comment: that's a fair point - I know what you mean. :-D You could use JavaDoc to underline that. But using the compiler as a safeguard is a better option, I guess.

Code under review:
public void testCloseClientBeforeRequest() throws Exception {
        
        
        try (final RestClient restClient =
                new RestClient(new Configuration(), Executors.directExecutor())) {
            
            restClient.close();

            CompletableFuture<?> future =
                    restClient.sendRequest(
                            unroutableIp,
                            80,
                            new TestMessageHeaders(),
                            EmptyMessageParameters.getInstance(),
                            EmptyRequestBody.getInstance());

            
            
            
            final ThrowingRunnable getFuture = () -> future.get(0, TimeUnit.SECONDS);

            final Throwable cause = assertThrows(ExecutionException.class, getFuture).getCause();
            assertThat(cause, instanceOf(IOException.class));
            assertThat(cause.getMessage(), containsString("RestClient is closed"));
        }
    }

Line commented on: restClient.close();

Revised code:
public void testCloseClientBeforeRequest() throws Exception {
        try (final RestClient restClient =
                new RestClient(new Configuration(), Executors.directExecutor())) {
            restClient.close(); 

            CompletableFuture<?> future =
                    restClient.sendRequest(
                            unroutableIp,
                            80,
                            new TestMessageHeaders(),
                            EmptyMessageParameters.getInstance(),
                            EmptyRequestBody.getInstance());

            
            
            
            final ThrowingRunnable getFuture = () -> future.get(0, TimeUnit.SECONDS);

            final Throwable cause = assertThrows(ExecutionException.class, getFuture).getCause();
            assertThat(cause, instanceOf(IllegalStateException.class));
            assertThat(cause.getMessage(), equalTo("RestClient is already closed"));
        }
    }
Code review comment: @pahans this is the formatter to format the json values to show in the webview of tracelog yeah?

Code under review:
public String format(LogRecord record) {
        return new Gson().toJson(record) + "\n";
    }

Line commented on: return new Gson().toJson(record) + "\n";

Revised code:
public String format(LogRecord record) {
        return new Gson().toJson(record) + System.getProperty("line.separator");
    }
Code review comment: Another option would be to pass `false` to the existing method from `StreamTask`, as it's done for iterative jobs: ``` private void readRecoveredChannelState() throws IOException, InterruptedException {     reader.readOutputData(getEnvironment().getAllWriters(), !configuration.isGraphContainingLoops()); ```  In the end, I think we'll need a check that we are either not using approximate recovery or not rescaling with UC. It would probably be more consistent and easier to implement with the 2nd approach. WDYT?   The check itself can be added to JM after we compute virtual mappings (cc: @AHeise).

Code under review:
public void finishReadRecoveredState(boolean notifyAndBlockOnCompletion) throws IOException {
		
	}


Revised code:
public void finishReadRecoveredState(boolean notifyAndBlockOnCompletion) throws IOException {
		
	}
Code review comment: Either use Duration or include the time unit in the name.

Code under review:
public void handleReply(Reply reply) {
        Object o = reply.getContext();
        if (!(o instanceof ReplyContext)) {
            return;
        }
        ReplyContext context = (ReplyContext) o;
        final double latency = (System.currentTimeMillis() - context.creationTime) / 1000.0d;
        metric.set(MetricNames.LATENCY, latency, null);

        if (reply.hasErrors()) {
            Set<Integer> errorCodes = MessageBusAsyncSession.getErrorCodes(reply);
            metricsHelper.reportFailure(DocumentOperationType.fromMessage(reply.getMessage()),
                    DocumentOperationStatus.fromMessageBusErrorCodes(errorCodes));
            metric.add(MetricNames.FAILED, 1, null);
            enqueue(context, reply.getError(0).getMessage(), ErrorCode.ERROR,
                    reply.getError(0).getCode() == DocumentProtocol.ERROR_TEST_AND_SET_CONDITION_FAILED, reply.getTrace());
        } else {
            metricsHelper.reportSuccessful(DocumentOperationType.fromMessage(reply.getMessage()), latency);
            metric.add(MetricNames.SUCCEEDED, 1, null);
            enqueue(context, "Document processed.", ErrorCode.OK, false, reply.getTrace());
        }
    }

Line commented on: final double latency = (System.currentTimeMillis() - context.creationTime) / 1000.0d;

Revised code:
public void handleReply(Reply reply) {
        Object o = reply.getContext();
        if (!(o instanceof ReplyContext)) {
            return;
        }
        ReplyContext context = (ReplyContext) o;
        final double latencyInSeconds = (System.currentTimeMillis() - context.creationTime) / 1000.0d;
        metric.set(MetricNames.LATENCY, latencyInSeconds, null);

        if (reply.hasErrors()) {
            Set<Integer> errorCodes = reply.getErrorCodes();
            metricsHelper.reportFailure(DocumentOperationType.fromMessage(reply.getMessage()),
                    DocumentOperationStatus.fromMessageBusErrorCodes(errorCodes));
            metric.add(MetricNames.FAILED, 1, null);
            enqueue(context, reply.getError(0).getMessage(), ErrorCode.ERROR,
                    reply.getError(0).getCode() == DocumentProtocol.ERROR_TEST_AND_SET_CONDITION_FAILED, reply.getTrace());
        } else {
            metricsHelper.reportSuccessful(DocumentOperationType.fromMessage(reply.getMessage()), latencyInSeconds);
            metric.add(MetricNames.SUCCEEDED, 1, null);
            enqueue(context, "Document processed.", ErrorCode.OK, false, reply.getTrace());
        }
    }
Code review comment: What's the need for taking these values from the module descriptor? Wouldn't just sending them as params do? Plus then you know what you are testing for. In this case, if these values change for some reason, the test changes too.

Code under review:
public void testTypeByName(String moduleName, String typeDefName, SymbolKind symKind, TypeDescKind typeDescKind) {
        Module module = getModule(project, moduleName);
        model = project.currentPackage().getCompilation().getSemanticModel(module.moduleId());
        types = model.types();
        String org = module.descriptor().org().value();
        String pkgName = module.descriptor().name().toString();
        String version = module.descriptor().version().toString();

        Optional<Symbol> symbol = types.getTypeByName(org, pkgName, version, typeDefName);
        assertTrue(symbol.isPresent());
        assertSymbolTypeDesc(symbol.get(), symKind, typeDescKind);

        Optional<String> symbolName = symbol.get().getName();
        assertTrue(symbolName.isPresent());
        assertEquals(symbolName.get(), typeDefName);
    }

Line commented on: String version = module.descriptor().version().toString();

Revised code:
public void testTypeByName(String moduleName, String typeDefName, SymbolKind symKind, TypeDescKind typeDescKind) {
        Module module = getModule(project, moduleName);
        SemanticModel model = project.currentPackage().getCompilation().getSemanticModel(module.moduleId());
        Types types = model.types();
        Optional<Symbol> symbol = types.getTypeByName("testorg", "typesapi." + moduleName, "1.0.0", typeDefName);
        assertTrue(symbol.isPresent());
        assertSymbolTypeDesc(symbol.get(), symKind, typeDescKind);
        Optional<String> symbolName = symbol.get().getName();
        assertTrue(symbolName.isPresent());
        assertEquals(symbolName.get(), typeDefName);
    }
Code review comment: Will be incorporate with next iteration.

Code under review:
private boolean isStampSupportedForSourceType(BType sourceType) {

        if (types.isAnydata(sourceType)) {
            switch (sourceType.tag) {
                case TypeTags.ARRAY:
                    
                    int arrayConstraintTypeTag = ((BArrayType) sourceType).eType.tag;
                    return !(arrayConstraintTypeTag == TypeTags.INT || arrayConstraintTypeTag == TypeTags.BOOLEAN ||
                            arrayConstraintTypeTag == TypeTags.FLOAT || arrayConstraintTypeTag == TypeTags.BYTE ||
                            arrayConstraintTypeTag == TypeTags.STRING || arrayConstraintTypeTag == TypeTags.DECIMAL);
                case TypeTags.INT:
                case TypeTags.BOOLEAN:
                case TypeTags.STRING:
                case TypeTags.FLOAT:
                case TypeTags.DECIMAL:
                case TypeTags.BYTE:
                case TypeTags.TABLE:
                    return false;
                default:
                    return true;
            }

        }
        return false;
    }

Line commented on: return !(arrayConstraintTypeTag == TypeTags.INT || arrayConstraintTypeTag == TypeTags.BOOLEAN ||

Revised code:
private boolean isStampSupportedForSourceType(BType sourceType) {

        if (!types.isAnydata(sourceType)) {
            return false;
        }

        switch (sourceType.tag) {
            case TypeTags.ARRAY:
                
                int arrayConstraintTypeTag = ((BArrayType) sourceType).eType.tag;
                return !(arrayConstraintTypeTag == TypeTags.INT || arrayConstraintTypeTag == TypeTags.BOOLEAN ||
                        arrayConstraintTypeTag == TypeTags.FLOAT || arrayConstraintTypeTag == TypeTags.BYTE ||
                        arrayConstraintTypeTag == TypeTags.STRING || arrayConstraintTypeTag == TypeTags.DECIMAL);
            case TypeTags.INT:
            case TypeTags.BOOLEAN:
            case TypeTags.STRING:
            case TypeTags.FLOAT:
            case TypeTags.DECIMAL:
            case TypeTags.BYTE:
            case TypeTags.TABLE:
                return false;
            default:
                return true;
        }

    }
Code review comment: nit: 2 spaces rather than 1. And same with lines 38, 44, and 45.

Code under review:
private IterableResponse<Integer> getIntegerIterableResponse(int startNumber, int noOfValues) {
        Flux<Integer>  integerFlux = Flux.range(startNumber, noOfValues);
        return new IterableResponse<>(integerFlux);
    }

Line commented on: Flux<Integer>  integerFlux = Flux.range(startNumber, noOfValues);

Revised code:
private IterableResponse<Integer> getIntegerIterableResponse(int startNumber, int noOfValues) {
        Flux<Integer> integerFlux = Flux.range(startNumber, noOfValues);
        return new IterableResponse<>(integerFlux);
    }