muttakin2301/ccr2000 huggingface dataset:
Code review comment: Not this particular one, that was just an example of one having a comma (taken from a non-hosted app). Maybe we should disallow `-Xrunjdwp:transport` completely in hosted?  Right now we warn or fail deployment for hosted (depending on feature flag value) and warn for non-hosted for JVM options like these. A JVM option like the above is perfectly valid in non-hosted. If we only validate JVM options for hosted this PR is not necessary

Code under review:
public void requireThatJvmOptionsAreLogged()  throws IOException, SAXException {
        verifyLoggingOfJvmOptions(true,
                                  "options",
                                  "-Xms2G foo     bar",
                                  "foo", "bar");
        verifyLoggingOfJvmOptions(true,
                                  "options",
                                  "$(touch /tmp/hello-from-gc-options)",
                                  "$(touch", "/tmp/hello-from-gc-options)");

        verifyLoggingOfJvmOptions(false,
                                  "options",
                                  "$(touch /tmp/hello-from-gc-options)",
                                  "$(touch", "/tmp/hello-from-gc-options)");

        
        verifyLoggingOfJvmOptions(true, "options", "-Xms2G");
        verifyLoggingOfJvmOptions(true, "options", "-verbose:gc");
        verifyLoggingOfJvmOptions(true, "options", "-Djava.library.path=/opt/vespa/lib64:/home/y/lib64 -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005");
        verifyLoggingOfJvmOptions(false, "options", "-Xms2G");
    }

Line commented on: verifyLoggingOfJvmOptions(true, "options", "-Djava.library.path=/opt/vespa/lib64:/home/y/lib64 -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005");

Revised code:
public void requireThatJvmOptionsAreLogged()  throws IOException, SAXException {
        verifyLoggingOfJvmOptions(true,
                                  "options",
                                  "-Xms2G foo     bar",
                                  "foo", "bar");
        verifyLoggingOfJvmOptions(true,
                                  "options",
                                  "$(touch /tmp/hello-from-gc-options)",
                                  "$(touch", "/tmp/hello-from-gc-options)");

        verifyLoggingOfJvmOptions(true,
                                  "options",
                                  "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005",
                                  "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005");

        verifyLoggingOfJvmOptions(false,
                                  "options",
                                  "$(touch /tmp/hello-from-gc-options)",
                                  "$(touch", "/tmp/hello-from-gc-options)");

        
        verifyLoggingOfJvmOptions(true, "options", "-Xms2G");
        verifyLoggingOfJvmOptions(true, "options", "-verbose:gc");
        verifyLoggingOfJvmOptions(true, "options", "-Djava.library.path=/opt/vespa/lib64:/home/y/lib64");
        verifyLoggingOfJvmOptions(false, "options", "-Xms2G");
    }
Code review comment: Instead of doing multiple String::format calls across if statements, why not use a string builder?

Code under review:
public URL getDirectoryUrl() {
        String directoryURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(),
            shareName, directoryPath);
        if (snapshot != null) {
            directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot);
        }
        try {
            return new URL(directoryURLString);
        } catch (MalformedURLException e) {
            throw logger.logExceptionAsError(new RuntimeException(
                String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
        }
    }

Line commented on: directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot);

Revised code:
public URL getDirectoryUrl() {
        StringBuilder directoryURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
            .append(shareName).append("/").append(directoryPath);
        if (snapshot != null) {
            directoryURLString.append("?snapshot=").append(snapshot);
        }
        try {
            return new URL(directoryURLString.toString());
        } catch (MalformedURLException e) {
            throw logger.logExceptionAsError(new RuntimeException(
                String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), directoryURLString), e));
        }
    }
Code review comment: We need to handle other places where we call the semantic analyzer from the type checker too. Please check and create an issue.

Code under review:
private void analyzeObjectConstructor(BLangNode node, SymbolEnv env) {
        if (!nonErrorLoggingCheck) {
            semanticAnalyzer.analyzeNode(node, env);
        }
    }

Line commented on: semanticAnalyzer.analyzeNode(node, env);

Revised code:
private void analyzeObjectConstructor(BLangNode node, SymbolEnv env) {
        if (!nonErrorLoggingCheck) {
            semanticAnalyzer.analyzeNode(node, env);
        }
    }
Code review comment: No, I'm not sure if it's the case.

Code under review:
public void setNodeName(final TransactionManagerConfiguration transactions) {

        try {
            arjPropertyManager.getCoreEnvironmentBean().setNodeIdentifier(transactions.nodeName);
            jtaPropertyManager.getJTAEnvironmentBean().setXaRecoveryNodes(Collections.singletonList(transactions.nodeName));
            TxControl.setXANodeName(transactions.nodeName);
        } catch (CoreEnvironmentBeanException e) {
            e.printStackTrace();
        }
    }

Line commented on: TxControl.setXANodeName(transactions.nodeName);

Revised code:
public void setNodeName(final TransactionManagerConfiguration transactions) {

        try {
            arjPropertyManager.getCoreEnvironmentBean().setNodeIdentifier(transactions.nodeName);
            jtaPropertyManager.getJTAEnvironmentBean().setXaRecoveryNodes(Collections.singletonList(transactions.nodeName));
            TxControl.setXANodeName(transactions.nodeName);
        } catch (CoreEnvironmentBeanException e) {
            e.printStackTrace();
        }
    }
Code review comment: Thanks for the suggestion! I was unhappy about the various wait times and time-dependent checks, but didn't know a proper way to handle it.

Code under review:
public void testCachedStatsCleanedAfterCleanupInterval() throws Exception {
        final Duration cleanUpInterval2 = Duration.ofMillis(1);
        final long waitingTime = cleanUpInterval2.toMillis() + 10;

        
        Cache<JobVertexThreadInfoTracker.Key, JobVertexThreadInfoStats> vertexStatsCache =
                CacheBuilder.newBuilder()
                        .concurrencyLevel(1)
                        .expireAfterAccess(cleanUpInterval2.toMillis(), TimeUnit.MILLISECONDS)
                        .recordStats()
                        .build();
        final JobVertexThreadInfoTracker<JobVertexThreadInfoStats> tracker =
                createThreadInfoTracker(
                        cleanUpInterval2,
                        STATS_REFRESH_INTERVAL,
                        vertexStatsCache,
                        threadInfoStatsDefaultSample);

        
        assertFalse(tracker.getVertexStats(JOB_ID, EXECUTION_JOB_VERTEX).isPresent());
        
        tracker.getResultAvailableFuture().get();
        
        Thread.sleep(waitingTime);

        assertFalse(tracker.getVertexStats(JOB_ID, EXECUTION_JOB_VERTEX).isPresent());
        assertEquals(1, vertexStatsCache.stats().evictionCount());
    }

Line commented on: Thread.sleep(waitingTime);

Revised code:
public void testCachedStatsCleanedAfterCleanupInterval() throws Exception {
        final Duration shortCleanUpInterval = Duration.ofMillis(1);

        
        CountDownLatch cacheExpired = new CountDownLatch(1);
        Cache<JobVertexThreadInfoTracker.Key, JobVertexThreadInfoStats> vertexStatsCache =
                createCache(shortCleanUpInterval, new LatchRemovalListener<>(cacheExpired));
        final JobVertexThreadInfoTracker<JobVertexThreadInfoStats> tracker =
                createThreadInfoTracker(
                        shortCleanUpInterval,
                        STATS_REFRESH_INTERVAL,
                        vertexStatsCache,
                        threadInfoStatsDefaultSample);

        
        assertFalse(tracker.getVertexStats(JOB_ID, EXECUTION_JOB_VERTEX).isPresent());
        
        cacheExpired.await();

        assertFalse(tracker.getVertexStats(JOB_ID, EXECUTION_JOB_VERTEX).isPresent());
    }
Code review comment: You should be able to remove a key that isn't there so you won't need to filter for keys that exist since that is expected to be slow if we need to read them all from the runner.  If we knew that we had them all in memory already then it would be worthwhile to filter upfront.

Code under review:
public void asyncClose() throws Exception {
    checkState(
        !isClosed,
        "Multimap user state is no longer usable because it is closed for %s",
        keysStateRequest.getStateKey());

    
    if (!isCleared && pendingRemoves.isEmpty() && pendingAdds.isEmpty()) {
      isClosed = true;
      return;
    }

    
    if (isCleared) {
      beamFnStateClient.handle(
          keysStateRequest.toBuilder().setClear(StateClearRequest.getDefaultInstance()),
          new CompletableFuture<>());
    } else if (!pendingRemoves.isEmpty()) {
      Iterable<K> removeKeys = Iterables.filter(getPersistedKeys(), pendingRemoves::contains);
      for (K key : removeKeys) {
        beamFnStateClient.handle(
            createUserStateRequest(key)
                .toBuilder()
                .setClear(StateClearRequest.getDefaultInstance()),
            new CompletableFuture<>());
      }
    }

    
    if (!pendingAdds.isEmpty()) {
      for (K key : pendingAdds.keySet()) {
        beamFnStateClient.handle(
            createUserStateRequest(key)
                .toBuilder()
                .setAppend(
                    StateAppendRequest.newBuilder().setData(encodeValues(pendingAdds.get(key)))),
            new CompletableFuture<>());
      }
    }
    isClosed = true;
  }

Line commented on: Iterable<K> removeKeys = Iterables.filter(getPersistedKeys(), pendingRemoves::contains);

Revised code:
public void asyncClose() throws Exception {
    checkState(
        !isClosed,
        "Multimap user state is no longer usable because it is closed for %s",
        keysStateRequest.getStateKey());
    isClosed = true;
    
    if (!isCleared && pendingRemoves.isEmpty() && pendingAdds.isEmpty()) {
      return;
    }

    
    if (isCleared) {
      beamFnStateClient.handle(
          keysStateRequest.toBuilder().setClear(StateClearRequest.getDefaultInstance()),
          new CompletableFuture<>());
    } else if (!pendingRemoves.isEmpty()) {
      for (K key : pendingRemoves) {
        beamFnStateClient.handle(
            createUserStateRequest(key)
                .toBuilder()
                .setClear(StateClearRequest.getDefaultInstance()),
            new CompletableFuture<>());
      }
    }

    
    if (!pendingAdds.isEmpty()) {
      for (Map.Entry<K, List<V>> entry : pendingAdds.entrySet()) {
        beamFnStateClient.handle(
            createUserStateRequest(entry.getKey())
                .toBuilder()
                .setAppend(StateAppendRequest.newBuilder().setData(encodeValues(entry.getValue()))),
            new CompletableFuture<>());
      }
    }
  }
Code review comment: Required, protobuf Message not allow to use `null`

Code under review:
private void startCDCClient() {
        ImportDataSourceParameter importDataSourceParam = new ImportDataSourceParameter(appendExtraParam(getActualJdbcUrlTemplate(DS_4, false, 0)), getUsername(), getPassword());
        StartCDCClientParameter parameter = new StartCDCClientParameter(importDataSourceParam);
        parameter.setAddress("localhost");
        parameter.setPort(getContainerComposer().getProxyCDCPort());
        parameter.setUsername(ProxyContainerConstants.USERNAME);
        parameter.setPassword(ProxyContainerConstants.PASSWORD);
        parameter.setDatabase("sharding_db");
        
        parameter.setFull(true);
        String schema = "";
        if (getDatabaseType().isSchemaAvailable()) {
            schema = "test";
        }
        parameter.setSchemaTables(Collections.singletonList(SchemaTable.newBuilder().setTable(getSourceTableOrderName()).setSchema(schema).build()));
        parameter.setDatabaseType(getDatabaseType().getType());
        CompletableFuture.runAsync(() -> new CDCClient(parameter).start(), executor).whenComplete((unused, throwable) -> {
            if (null != throwable) {
                log.error("cdc client sync failed, ", throwable);
            }
            throw new RuntimeException(throwable);
        });
    }

Line commented on: String schema = "";

Revised code:
private void startCDCClient() {
        ImportDataSourceParameter importDataSourceParam = new ImportDataSourceParameter(appendExtraParam(getActualJdbcUrlTemplate(DS_4, false, 0)), getUsername(), getPassword());
        StartCDCClientParameter parameter = new StartCDCClientParameter(importDataSourceParam);
        parameter.setAddress("localhost");
        parameter.setPort(getContainerComposer().getProxyCDCPort());
        parameter.setUsername(ProxyContainerConstants.USERNAME);
        parameter.setPassword(ProxyContainerConstants.PASSWORD);
        parameter.setDatabase("sharding_db");
        
        parameter.setFull(true);
        String schema = getDatabaseType().isSchemaAvailable() ? "test" : "";
        parameter.setSchemaTables(Collections.singletonList(SchemaTable.newBuilder().setTable(getSourceTableOrderName()).setSchema(schema).build()));
        parameter.setDatabaseType(getDatabaseType().getType());
        CompletableFuture.runAsync(() -> new CDCClient(parameter).start(), executor).whenComplete((unused, throwable) -> {
            if (null != throwable) {
                log.error("cdc client sync failed, ", throwable);
            }
        });
    }
Code review comment: Here, we use the binding pattern as it is with the `toSourceCode` API. Shall we check whether the user experience with the various binding pattern options? Specially the list and map binding pattern https://ballerina.io/spec/lang/master/#binding-pattern

Code under review:
public Optional<DocumentSymbol> transform(ModuleVariableDeclarationNode moduleVariableDeclarationNode) {
        String name = moduleVariableDeclarationNode.typedBindingPattern().bindingPattern().toSourceCode();
        SymbolKind symbolKind = SymbolKind.Variable;
        Range range = DocumentSymbolUtil.generateNodeRange(moduleVariableDeclarationNode);
        Optional<MetadataNode> metadata = moduleVariableDeclarationNode.metadata();
        boolean isDeprecated = metadata.isPresent() &&
                DocumentSymbolUtil.isDeprecated(metadata.get());
        return Optional.ofNullable(createDocumentSymbol(name, symbolKind, null,
                range, range, isDeprecated, Collections.emptyList(), this.context));
    }

Line commented on: String name = moduleVariableDeclarationNode.typedBindingPattern().bindingPattern().toSourceCode();

Revised code:
public Optional<DocumentSymbol> transform(ModuleVariableDeclarationNode moduleVariableDeclarationNode) {
        BindingPatternNode bindingPatternNode = moduleVariableDeclarationNode.typedBindingPattern().bindingPattern();
        
        if (bindingPatternNode.kind() != SyntaxKind.CAPTURE_BINDING_PATTERN) {
            return Optional.empty();
        }
        String name = bindingPatternNode.toSourceCode();
        SymbolKind symbolKind = SymbolKind.Variable;
        Range range = DocumentSymbolUtil.generateNodeRange(moduleVariableDeclarationNode);
        Optional<MetadataNode> metadata = moduleVariableDeclarationNode.metadata();
        boolean isDeprecated = metadata.isPresent() &&
                DocumentSymbolUtil.isDeprecated(metadata.get());
        return Optional.of(createDocumentSymbol(name, symbolKind, range, range, isDeprecated,
                Collections.emptyList()));
    }
Code review comment: Can you modify the kernel logic instead of sql parse logic?

Code under review:
private BinaryOperationExpression createPatternMatchingOperationSegment(final AExprContext ctx) {
        String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();
        ExpressionSegment left = (ExpressionSegment) visit(ctx.aExpr(0));
        ListExpression right = new ListExpression(ctx.aExpr(1).start.getStartIndex(), ctx.aExpr().get(ctx.aExpr().size() - 1).stop.getStopIndex());
        for (int i = 1; i < ctx.aExpr().size(); i++) {
            right.getItems().add((ExpressionSegment) visit(ctx.aExpr().get(i)));
        }
        String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
        return new BinaryOperationExpression(ctx.start.getStartIndex(), ctx.stop.getStopIndex(), left, right, operator, text);
    }

Line commented on: String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();

Revised code:
private BinaryOperationExpression createPatternMatchingOperationSegment(final AExprContext ctx) {
        String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();
        ExpressionSegment left = (ExpressionSegment) visit(ctx.aExpr(0));
        ListExpression right = new ListExpression(ctx.aExpr(1).start.getStartIndex(), ctx.aExpr().get(ctx.aExpr().size() - 1).stop.getStopIndex());
        for (int i = 1; i < ctx.aExpr().size(); i++) {
            right.getItems().add((ExpressionSegment) visit(ctx.aExpr().get(i)));
        }
        String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
        return new BinaryOperationExpression(ctx.start.getStartIndex(), ctx.stop.getStopIndex(), left, right, operator, text);
    }
Code review comment: Shouldn't this be `max.nodes() / min.groups()` ?

Code under review:
public Capacity applyOn(Capacity capacity, ApplicationId application, boolean exclusive) {
        var min = applyOn(capacity.minResources(), capacity, application, exclusive);
        var max = applyOn(capacity.maxResources(), capacity, application, exclusive);
        var groupSize = capacity.groupSize().fromAtMost(max.nodes() / max.groups())
                                            .toAtLeast(min.nodes() / min.groups());
        return capacity.withLimits(min, max, groupSize);
    }

Line commented on: var groupSize = capacity.groupSize().fromAtMost(max.nodes() / max.groups())

Revised code:
public Capacity applyOn(Capacity capacity, ApplicationId application, boolean exclusive) {
        var min = applyOn(capacity.minResources(), capacity, application, exclusive);
        var max = applyOn(capacity.maxResources(), capacity, application, exclusive);
        var groupSize = capacity.groupSize().fromAtMost(max.nodes() / min.groups())
                                            .toAtLeast(min.nodes() / max.groups());
        return capacity.withLimits(min, max, groupSize);
    }
Code review comment: Just move the toByteArray call to the test and out of the implementation to prevent its use

Code under review:
public static byte[] getPosition(@Nullable ShufflePosition shufflePosition) {
    if (shufflePosition == null) {
      return null;
    }
    Preconditions.checkArgument(shufflePosition instanceof ByteArrayShufflePosition);
    ByteArrayShufflePosition adapter = (ByteArrayShufflePosition) shufflePosition;
    return adapter.getPosition().toByteArray();
  }

Line commented on: return adapter.getPosition().toByteArray();

Revised code:
public static byte[] getPosition(@Nullable ShufflePosition shufflePosition) {
    if (shufflePosition == null) {
      return null;
    }
    Preconditions.checkArgument(shufflePosition instanceof ByteArrayShufflePosition);
    ByteArrayShufflePosition adapter = (ByteArrayShufflePosition) shufflePosition;
    return adapter.getPosition().toByteArray();
  }
Code review comment: Log the exception as the last parameter in this.

Code under review:
public String serializeRaw(Object object) {
        final ClientLogger logger = new ClientLogger(JacksonAdapter.class);
        if (object == null) {
            return null;
        }
        try {
            return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", "");
        } catch (IOException ex) {
            logger.warning("Failed to serialize {} to JSON.", object.getClass());
            return null;
        }
    }

Line commented on: logger.warning("Failed to serialize {} to JSON.", object.getClass());

Revised code:
public String serializeRaw(Object object) {
        if (object == null) {
            return null;
        }
        try {
            return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", "");
        } catch (IOException ex) {
            logger.warning("Failed to serialize {} to JSON.", object.getClass(), ex);
            return null;
        }
    }
Code review comment: I think you should set this to null.

Code under review:
public PubsubMessage(byte[] payload, Map<String, String> attributes) {
    this.message = payload;
    this.attributes = attributes;
    this.messageId = "";
  }

Line commented on: this.messageId = "";

Revised code:
public PubsubMessage(byte[] payload, Map<String, String> attributes) {
    this.message = payload;
    this.attributes = attributes;
    this.messageId = null;
  }
Code review comment: Negative is an interesting situation, but you are right makes sense, removed the reduandant check

Code under review:
private Duration calculateRenewalDelay(OffsetDateTime initialLockedUntil) {
        final OffsetDateTime now = OffsetDateTime.now();
        final Duration remainingTime = Duration.between(now, initialLockedUntil);

        
        
        

        if (remainingTime.isNegative() || remainingTime.toMillis() < 400) {
            logger.info("Duration was negative or less than 400ms. now[{}] lockedUntil[{}]", now, initialLockedUntil);
            return Duration.ZERO;
        } else {
            
            final long bufferInMilliSec = Math.min(remainingTime.toMillis() / 2,
                MAX_RENEWAL_BUFFER_DURATION.toMillis());
            final Duration renewAfter = Duration.ofMillis(remainingTime.toMillis() - bufferInMilliSec);
            if (renewAfter.isNegative()) {
                logger.info("Adjusted duration is negative. renewAfter: {}ms. Buffer: {}ms.",
                    remainingTime.toMillis(), bufferInMilliSec);
            }
            return renewAfter;
        }
    }

Line commented on: if (remainingTime.isNegative() || remainingTime.toMillis() < 400) {

Revised code:
private Duration calculateRenewalDelay(OffsetDateTime initialLockedUntil) {
        final OffsetDateTime now = OffsetDateTime.now();
        final Duration remainingTime = Duration.between(now, initialLockedUntil);

        
        
        

        if (remainingTime.toMillis() < 400) {
            logger.info("Duration was less than 400ms. now[{}] lockedUntil[{}]", now, initialLockedUntil);
            return Duration.ZERO;
        } else {
            
            final long bufferInMilliSec = Math.min(remainingTime.toMillis() / 2,
                MAX_RENEWAL_BUFFER_DURATION.toMillis());
            final Duration renewAfter = Duration.ofMillis(remainingTime.toMillis() - bufferInMilliSec);
            if (renewAfter.isNegative()) {
                logger.info("Adjusted duration is negative. renewAfter: {}ms. Buffer: {}ms.",
                    remainingTime.toMillis(), bufferInMilliSec);
            }
            return renewAfter;
        }
    }
Code review comment: ```suggestion             sqlStr = op.toString() + " " + getChild(0).toSql(); ```

Code under review:
public ArithmeticExpr(Operator op, Expr e1, Expr e2) {
        super();
        this.op = op;
        Preconditions.checkNotNull(e1);
        children.add(e1);
        Preconditions.checkArgument(
                op == Operator.BITNOT && e2 == null || op != Operator.BITNOT && e2 != null);
        if (e2 != null) {
            children.add(e2);
        }
        if (children.size() == 1) {
            sqlStr=op.toString() + " " + getChild(0).toSql();
        } else {
            sqlStr = getChild(0).toSql() + " " + op.toString() + " " + getChild(1).toSql();
        }
    }

Line commented on: sqlStr=op.toString() + " " + getChild(0).toSql();

Revised code:
public ArithmeticExpr(Operator op, Expr e1, Expr e2) {
        super();
        this.op = op;
        Preconditions.checkNotNull(e1);
        children.add(e1);
        Preconditions.checkArgument(
                op == Operator.BITNOT && e2 == null || op != Operator.BITNOT && e2 != null);
        if (e2 != null) {
            children.add(e2);
        }
        sqlStr = null;
    }
Code review comment: I don't know much about the use of `jboss.xnio` library, just read its documentation.  I have a question here: will this run in `WORKER THREAD pool`, which was configured to 16 in `NMysqlServer`(use `Options.WORKER_TASK_MAX_THREADS`)?  If it is, there may be a problem. For example: if we have 16 slow queries, such as running for 5 minutes, which makes these 16 threads are filled. And because there are no threads available for subsequent query requests, the server will hang for 5 minutes.

Code under review:
public void handleEvent(ConduitStreamSourceChannel channel) {
        
        
        XnioIoThread.requireCurrentThread();
        ctx.suspendAcceptQuery();
        
        channel.getWorker().execute(() -> {
            ctx.setThreadLocalInfo();
            try {
                connectProcessor.processOnce();
                if (!ctx.isKilled()) {
                    ctx.resumeAcceptQuery();
                } else {
                    ctx.stopAcceptQuery();
                    ctx.cleanup();
                }
            } catch (Exception e) {
                LOG.warn("Exception happened in one session(" + ctx + ").", e);
                ctx.setKilled();
                ctx.cleanup();
            } finally {
                ConnectContext.remove();
            }
        });
    }

Line commented on: channel.getWorker().execute(() -> {

Revised code:
public void handleEvent(ConduitStreamSourceChannel channel) {
        
        
        XnioIoThread.requireCurrentThread();
        ctx.suspendAcceptQuery();
        
        channel.getWorker().execute(() -> {
            ctx.setThreadLocalInfo();
            try {
                connectProcessor.processOnce();
                if (!ctx.isKilled()) {
                    ctx.resumeAcceptQuery();
                } else {
                    ctx.stopAcceptQuery();
                    ctx.cleanup();
                }
            } catch (Exception e) {
                LOG.warn("Exception happened in one session(" + ctx + ").", e);
                ctx.setKilled();
                ctx.cleanup();
            } finally {
                ConnectContext.remove();
            }
        });
    }
Code review comment: @sd-f This null is taken care of a bit later [here](https://github.com/quarkusio/quarkus/blob/351778d3ce0aa8a44cc45328ebdc44c293d2f1bb/extensions/oidc-client/runtime/src/main/java/io/quarkus/oidc/client/runtime/OidcClientRecorder.java#L119). We can throw the exception now but then we'd have to refactor the uni code catching it, so if you don't mind then lets keep retuning null here :-)

Code under review:
private static Uni<String> discoverTokenEndpoint(WebClient client, String authServerUrl) {
        String discoveryUrl = authServerUrl + "/.well-known/openid-configuration";
        return client.getAbs(discoveryUrl).send().onItem().transform(resp -> {
            if (resp.statusCode() == 200) {
                JsonObject json = resp.bodyAsJsonObject();
                return json.getString("token_endpoint");
            } else {
                LOG.tracef("Discovery has failed, status code: %d", resp.statusCode());
                throw new OidcClientException("Token endpoint discovery has failed");
            }
        });
    }

Line commented on: throw new OidcClientException("Token endpoint discovery has failed");

Revised code:
private static Uni<String> discoverTokenEndpoint(WebClient client, String authServerUrl) {
        String discoveryUrl = authServerUrl + "/.well-known/openid-configuration";
        return client.getAbs(discoveryUrl).send().onItem().transform(resp -> {
            if (resp.statusCode() == 200) {
                JsonObject json = resp.bodyAsJsonObject();
                return json.getString("token_endpoint");
            } else {
                LOG.tracef("Discovery has failed, status code: %d", resp.statusCode());
                return null;
            }
        });
    }
Code review comment: Here will be a problem. For now, `DataProperty.DEFAULT_DATA_PROPERTY` is configuration, so here, it is all possible to write `true` or `false`. And when reading, `true` may point to HDD, may point to SSD, depends on the config.

Code under review:
public void write(DataOutput out) throws IOException {
        Text.writeString(out, type.name());

        Preconditions.checkState(idToDataProperty.size() == idToReplicationNum.size());
        Preconditions.checkState(idToInMemory.keySet().equals(idToReplicationNum.keySet()));
        out.writeInt(idToDataProperty.size());
        for (Map.Entry<Long, DataProperty> entry : idToDataProperty.entrySet()) {
            out.writeLong(entry.getKey());
            if (entry.getValue() == DataProperty.DEFAULT_DATA_PROPERTY) {
                out.writeBoolean(true);
            } else {
                out.writeBoolean(false);
                entry.getValue().write(out);
            }

            out.writeShort(idToReplicationNum.get(entry.getKey()));
            out.writeBoolean(idToInMemory.get(entry.getKey()));
        }
    }

Line commented on: if (entry.getValue() == DataProperty.DEFAULT_DATA_PROPERTY) {

Revised code:
public void write(DataOutput out) throws IOException {
        Text.writeString(out, type.name());

        Preconditions.checkState(idToDataProperty.size() == idToReplicationNum.size());
        Preconditions.checkState(idToInMemory.keySet().equals(idToReplicationNum.keySet()));
        out.writeInt(idToDataProperty.size());
        for (Map.Entry<Long, DataProperty> entry : idToDataProperty.entrySet()) {
            out.writeLong(entry.getKey());
            if (entry.getValue().equals(new DataProperty(TStorageMedium.HDD))) {
                out.writeBoolean(true);
            } else {
                out.writeBoolean(false);
                entry.getValue().write(out);
            }

            out.writeShort(idToReplicationNum.get(entry.getKey()));
            out.writeBoolean(idToInMemory.get(entry.getKey()));
        }
    }
Code review comment: Yes I agree `UnresolvedFieldReference` cannot be translated into RexNode and also that it should never end up in the Planner. This is also the main purpose of the `UnresolvedFieldReference` to make this distinction clear.  `ExpressionVisitor` is just a way to traverse the operation tree. I am currently working on moving all the resolution of expressions into a single place in the API module, as part of FLINK-11884. I agree we should move this resolution here up to the API module as well once it's in place.

Code under review:
public RexNode visit(Expression other) {
		if (other instanceof UnresolvedFieldReferenceExpression) {
			return visitUnresolvedFieldReferenceExpression((UnresolvedFieldReferenceExpression) other);
		} else if (other instanceof ResolvedAggInputReference) {
			return visitResolvedAggInputReference((ResolvedAggInputReference) other);
		} else if (other instanceof ResolvedAggLocalReference) {
			return visitResolvedAggLocalReference((ResolvedAggLocalReference) other);
		} else if (other instanceof ResolvedDistinctKeyReference) {
			return visitResolvedDistinctKeyReference((ResolvedDistinctKeyReference) other);
		} else {
			throw new UnsupportedOperationException(other.getClass().getSimpleName() + ":" + other.toString());
		}
	}

Line commented on: if (other instanceof UnresolvedFieldReferenceExpression) {

Revised code:
public RexNode visit(Expression other) {
		if (other instanceof UnresolvedFieldReferenceExpression) {
			return visitUnresolvedFieldReferenceExpression((UnresolvedFieldReferenceExpression) other);
		} else if (other instanceof ResolvedAggInputReference) {
			return visitResolvedAggInputReference((ResolvedAggInputReference) other);
		} else if (other instanceof ResolvedAggLocalReference) {
			return visitResolvedAggLocalReference((ResolvedAggLocalReference) other);
		} else if (other instanceof ResolvedDistinctKeyReference) {
			return visitResolvedDistinctKeyReference((ResolvedDistinctKeyReference) other);
		} else {
			throw new UnsupportedOperationException(other.getClass().getSimpleName() + ":" + other.toString());
		}
	}
Code review comment: I think you can extends DefaultExpressionRewriter, and replace this line to `return super.visit(expr, substitutionMap)`

Code under review:
public Expression visit(Expression expr, Map<Expression, Expression> substitutionMap) {
            
            
            
            
            if (substitutionMap.containsKey(expr)) {
                return substitutionMap.get(expr);
            } else {
                List<Expression> newChildren = new ArrayList<>();
                boolean hasNewChildren = false;
                for (Expression child : expr.children()) {
                    Expression newChild = visit(child, substitutionMap);
                    if (newChild != child) {
                        hasNewChildren = true;
                    }
                    newChildren.add(newChild);
                }
                return hasNewChildren ? expr.withChildren(newChildren) : expr;
            }
        }

Line commented on: List<Expression> newChildren = new ArrayList<>();

Revised code:
public Expression visit(Expression expr, Map<Expression, Expression> substitutionMap) {
            
            
            
            
            if (substitutionMap.containsKey(expr)) {
                return substitutionMap.get(expr);
            } else {
                List<Expression> newChildren = new ArrayList<>();
                boolean hasNewChildren = false;
                for (Expression child : expr.children()) {
                    Expression newChild = visit(child, substitutionMap);
                    if (newChild != child) {
                        hasNewChildren = true;
                    }
                    newChildren.add(newChild);
                }
                return hasNewChildren ? expr.withChildren(newChildren) : expr;
            }
        }
Code review comment: @cescoffier maybe it's not mandatory in this case but we usually restore previous contexts in a finally block. It's not needed here?

Code under review:
public void handle(Promise<Object> f) {
                        final Context previous = Context.current();
                        grpcContext.attach();

                        consumer.accept(delegate);
                        f.complete();

                        grpcContext.detach(previous);
                    }

Line commented on: grpcContext.detach(previous);

Revised code:
public void handle(Promise<Object> f) {
                    ServerCall.Listener<ReqT> listener = next.startCall(call, headers);
                    replay.setDelegate(listener);
                    f.complete(null);
                }
Code review comment: There are multiple strategies to solve this specific problem, but I don't think creating a mapping will be significantly better.

Code under review:
private void removeDuplicateBindingsFromAccessControlChain(Http http) {
        Set<FilterBinding> duplicateBindings = new HashSet<>();
        for (FilterBinding binding : http.getBindings()) {
            if (binding.filterId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
                for (FilterBinding otherBinding : http.getBindings()) {
                    if (!binding.filterId().equals(otherBinding.filterId())
                            && binding.binding().equals(otherBinding.binding())) {
                        duplicateBindings.add(binding);
                    }
                }
            }
        }
        duplicateBindings.forEach(http.getBindings()::remove);
    }

Line commented on: for (FilterBinding binding : http.getBindings()) {

Revised code:
private void removeDuplicateBindingsFromAccessControlChain(Http http) {
        Set<FilterBinding> duplicateBindings = new HashSet<>();
        for (FilterBinding binding : http.getBindings()) {
            if (binding.chainId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
                for (FilterBinding otherBinding : http.getBindings()) {
                    if (!binding.chainId().equals(otherBinding.chainId())
                            && binding.binding().equals(otherBinding.binding())) {
                        duplicateBindings.add(binding);
                    }
                }
            }
        }
        duplicateBindings.forEach(http.getBindings()::remove);
    }
Code review comment: It was more so that people know what they are using.  People are used to hamcrest assertions being static but I didn't want a magic `get(...)` that people don't know where it's coming from.

Code under review:
public void testHealth() {
        
        try {
            RestAssured.defaultParser = Parser.JSON;
            RestAssured.when().get("/health").then()
                    .body("outcome", is("UP"),
                            "checks.state", contains("UP"),
                            "checks.name", contains("basic"));
        } finally {
            RestAssured.reset();
        }
    }

Line commented on: RestAssured.when().get("/health").then()

Revised code:
public void testHealth() {
        
        try {
            RestAssured.defaultParser = Parser.JSON;
            RestAssured.when().get("/health").then()
                    .body("outcome", is("UP"),
                            "checks.state", contains("UP"),
                            "checks.name", contains("basic"));
        } finally {
            RestAssured.reset();
        }
    }
Code review comment: I got your point, but it would require to annotate the `inputStream` [here](https://github.com/julianhyde/sqlline/blob/sqlline-1.4.0/src/main/java/sqlline/SqlLine.java#L615) in `begin` method with `@Nullable`, which is outside the project. What could be possible workaround here ?

Code under review:
private Future<List<List<String>>> runQueryInBackground(String[] args) {
    return pool.submit(
        (Callable)
            () -> {
              ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
              InputStream inputStream = new ByteArrayInputStream(new byte[0]);
              BeamSqlLine.runSqlLine(args, inputStream, outputStream, null);
              return toLines(outputStream);
            });
  }

Line commented on: BeamSqlLine.runSqlLine(args, inputStream, outputStream, null);

Revised code:
new ByteArrayOutputStream();
              BeamSqlLine.runSqlLine(args, null, outputStream, null);
              return toLines(outputStream);
            });
  }

  private long convertTimestampToMillis(String timestamp) throws ParseException {
    return dateFormat.parse(timestamp).getTime();
  }
Code review comment: ```suggestion        addShutdownHookAndCleanup(); // Register a shutdown hook to handle graceful shutdown of the application ```

Code under review:
public static void main(String[] args) throws CustomException {
        profilerStartTime = TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
        tempFileCleanupShutdownHook(); 
        printHeader(); 
        handleProfilerArguments(args); 
        extractTheProfiler(); 
        createTempJar(balJarName); 
        initialize(balJarName); 
    }

Line commented on: tempFileCleanupShutdownHook();

Revised code:
public static void main(String[] args) throws CustomException {
        profilerStartTime = TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
        addShutdownHookAndCleanup(); 
        printHeader(); 
        handleProfilerArguments(args); 
        extractProfiler(); 
        createTempJar(balJarName); 
        initializeProfiling(balJarName); 
    }
Code review comment: The strange issue was related to HTTP/2 and solved by `executeBlocking` https://github.com/quarkusio/quarkus/issues/34912

Code under review:
public static Uni<HttpResponse<Buffer>> sendRequest(Vertx vertx, HttpRequest<Buffer> request, boolean blockingDnsLookup) {
        if (blockingDnsLookup) {
            return vertx.executeBlocking(new Callable<Void>() {
                @Override
                public Void call() {
                    try {
                        
                        InetAddress.getByName(request.host());
                    } catch (UnknownHostException e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }
            }).flatMap(new Function<Void, Uni<? extends HttpResponse<Buffer>>>() {
                @Override
                public Uni<? extends HttpResponse<Buffer>> apply(Void unused) {
                    return request.send();
                }
            });
        } else {
            return request.send();
        }
    }

Line commented on: return vertx.executeBlocking(new Callable<Void>() {

Revised code:
Override
                public Void call() {
                    try {
                        
                        InetAddress.getByName(request.host());
                    } catch (UnknownHostException e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }
Code review comment: Let's also log other shutdown attempts as DEBUG.

Code under review:
private CompletableFuture<Void> close(Throwable cause) {
			final CompletableFuture<Void> shutdownFuture = new CompletableFuture<>();

			if (connectionShutdownFuture.compareAndSet(null, shutdownFuture) &&
					failureCause.compareAndSet(null, cause)) {

				channel.close().addListener(finished -> {
					stats.reportInactiveConnection();
					for (long requestId : pendingRequests.keySet()) {
						TimestampedCompletableFuture pending = pendingRequests.remove(requestId);
						if (pending != null && pending.completeExceptionally(cause)) {
							stats.reportFailedRequest();
						}
					}

					if (finished.isSuccess()) {
						shutdownFuture.complete(null);
					} else {
						shutdownFuture.completeExceptionally(finished.cause());
					}
				});
			}

			
			return connectionShutdownFuture.get();
		}

Line commented on: if (connectionShutdownFuture.compareAndSet(null, shutdownFuture) &&

Revised code:
private CompletableFuture<Void> close(Throwable cause) {
			CompletableFuture<Void> future = new CompletableFuture<>();
			if (connectionShutdownFuture.compareAndSet(null, future)) {
				synchronized (connectLock) {
					if (failureCause == null) {
						failureCause = cause;
					}

					if (established != null) {
						established.close().whenComplete((result, throwable) -> {
							if (throwable != null) {
								future.completeExceptionally(throwable);
							} else {
								future.complete(null);
							}
						});
					} else {
						PendingRequest pending;
						while ((pending = queuedRequests.poll()) != null) {
							pending.completeExceptionally(cause);
						}
						future.complete(null);
					}
				}
			}
			return connectionShutdownFuture.get();
		}
Code review comment: A question here: why have to change from `BufferOrEvent` to `Optional<BufferOrEvent>`, to avoid null check?

Code under review:
public Optional<BufferOrEvent> pollNext() throws Exception {
		while (true) {
			
			Optional<BufferOrEvent> next;
			if (currentBuffered == null) {
				next = inputGate.pollNext();
			}
			else {
				
				next = Optional.ofNullable(currentBuffered.getNext());
				if (!next.isPresent()) {
					completeBufferedSequence();
					return pollNext();
				}
			}

			if (!next.isPresent()) {
				return handleEmptyBuffer();
			}

			BufferOrEvent bufferOrEvent = next.get();
			if (isBlocked(bufferOrEvent.getChannelIndex())) {
				
				bufferBlocker.add(bufferOrEvent);
				checkSizeLimit();
			}
			else if (bufferOrEvent.isBuffer()) {
				return next;
			}
			else if (bufferOrEvent.getEvent().getClass() == CheckpointBarrier.class) {
				if (!endOfStream) {
					
					processBarrier((CheckpointBarrier) bufferOrEvent.getEvent(), bufferOrEvent.getChannelIndex());
				}
			}
			else if (bufferOrEvent.getEvent().getClass() == CancelCheckpointMarker.class) {
				processCancellationBarrier((CancelCheckpointMarker) bufferOrEvent.getEvent());
			}
			else {
				if (bufferOrEvent.getEvent().getClass() == EndOfPartitionEvent.class) {
					processEndOfPartition();
				}
				return next;
			}
		}
	}

Line commented on: if (currentBuffered == null) {

Revised code:
public Optional<BufferOrEvent> pollNext() throws Exception {
		while (true) {
			
			Optional<BufferOrEvent> next;
			if (currentBuffered == null) {
				next = inputGate.pollNext();
			}
			else {
				
				next = Optional.ofNullable(currentBuffered.getNext());
				if (!next.isPresent()) {
					completeBufferedSequence();
					return pollNext();
				}
			}

			if (!next.isPresent()) {
				return handleEmptyBuffer();
			}

			BufferOrEvent bufferOrEvent = next.get();
			if (isBlocked(bufferOrEvent.getChannelIndex())) {
				
				bufferBlocker.add(bufferOrEvent);
				checkSizeLimit();
			}
			else if (bufferOrEvent.isBuffer()) {
				return next;
			}
			else if (bufferOrEvent.getEvent().getClass() == CheckpointBarrier.class) {
				if (!endOfStream) {
					
					processBarrier((CheckpointBarrier) bufferOrEvent.getEvent(), bufferOrEvent.getChannelIndex());
				}
			}
			else if (bufferOrEvent.getEvent().getClass() == CancelCheckpointMarker.class) {
				processCancellationBarrier((CancelCheckpointMarker) bufferOrEvent.getEvent());
			}
			else {
				if (bufferOrEvent.getEvent().getClass() == EndOfPartitionEvent.class) {
					processEndOfPartition();
				}
				return next;
			}
		}
	}
Code review comment: fileSystem.listLocatedStatus is an api to list all statuses and block locations of the files in the given path in one operation. The performance is better than getting status and block location one by one.

Code under review:
private List<HdfsFileDesc> getHdfsFileDescs(String dirPath) throws Exception {
        URI uri = new URI(dirPath);
        FileSystem fileSystem = getFileSystem(uri);
        
        
        
        RemoteIterator<LocatedFileStatus> blockIterator = fileSystem.listLocatedStatus(new Path(uri.getPath()));
        List<HdfsFileDesc> fileDescs = Lists.newArrayList();

        while (blockIterator.hasNext()) {
            LocatedFileStatus locatedFileStatus = blockIterator.next();
            if (!isValidDataFile(locatedFileStatus)) {
                continue;
            }
            String fileName = Utils.getSuffixName(dirPath, locatedFileStatus.getPath().toString());
            BlockLocation[] blockLocations = locatedFileStatus.getBlockLocations();
            List<HdfsFileBlockDesc> fileBlockDescs = getHdfsFileBlockDescs(blockLocations);
            fileDescs.add(new HdfsFileDesc(fileName, "", locatedFileStatus.getLen(), ImmutableList.copyOf(fileBlockDescs)));
        }
        return fileDescs;
    }


Revised code:
private List<HdfsFileDesc> getHdfsFileDescs(String dirPath) throws Exception {
        URI uri = new URI(dirPath);
        FileSystem fileSystem = getFileSystem(uri);
        
        
        
        RemoteIterator<LocatedFileStatus> blockIterator = fileSystem.listLocatedStatus(new Path(uri.getPath()));
        List<HdfsFileDesc> fileDescs = Lists.newArrayList();

        while (blockIterator.hasNext()) {
            LocatedFileStatus locatedFileStatus = blockIterator.next();
            if (!isValidDataFile(locatedFileStatus)) {
                continue;
            }
            String fileName = Utils.getSuffixName(dirPath, locatedFileStatus.getPath().toString());
            BlockLocation[] blockLocations = locatedFileStatus.getBlockLocations();
            List<HdfsFileBlockDesc> fileBlockDescs = getHdfsFileBlockDescs(blockLocations);
            fileDescs.add(new HdfsFileDesc(fileName, "", locatedFileStatus.getLen(), ImmutableList.copyOf(fileBlockDescs)));
        }
        return fileDescs;
    }