muttakin2301/ccr2000 huggingface dataset:
Code review comment: And I check the source code. if the data can pass to this function, they are all binaryData, so we can use java's equal.

Code under review:
public MapDataForMapUnion(MapData map1, MapData map2) {

            this.map = new HashMap<>();
            for (int i = 0; i < map1.size(); i++) {
                final Object key = keyElementGetter.getElementOrNull(map1.keyArray(), i);
                final Object value = valueElementGetter.getElementOrNull(map1.valueArray(), i);
                this.map.put(key, value);
            }
            for (int i = 0; i < map2.size(); i++) {
                final Object key = keyElementGetter.getElementOrNull(map2.keyArray(), i);
                final Object value = valueElementGetter.getElementOrNull(map2.valueArray(), i);
                this.map.put(key, value);
            }
            this.updateArrays();
        }

Line commented on: this.map = new HashMap<>();

Revised code:
public MapDataForMapUnion(MapData map1, MapData map2) throws Throwable {
            List<Object> keysList = new ArrayList<>();
            List<Object> valuesList = new ArrayList<>();
            boolean isKeyNullExist = false;
            ArrayData keyArray2 = map2.keyArray();
            ArrayData valueArray2 = map2.valueArray();
            for (int i = 0; i < map2.size(); i++) {
                Object key = keyElementGetter.getElementOrNull(keyArray2, i);
                if (key == null) {
                    isKeyNullExist = true;
                }
                keysList.add(key);
                valuesList.add(valueElementGetter.getElementOrNull(valueArray2, i));
            }
            ArrayData keyArray1 = map1.keyArray();
            ArrayData valueArray1 = map1.valueArray();
            for (int i = 0; i < map1.size(); i++) {
                final Object key1 = keyElementGetter.getElementOrNull(keyArray1, i);

                boolean keyExists = false;
                if (key1 != null) {
                    for (int j = 0; j < keysList.size(); j++) {
                        final Object key2 = keysList.get(j);
                        if (key2 != null && (boolean) keyEqualityHandle.invoke(key1, key2)) {
                            
                            keyExists = true;
                            break;
                        }
                    }
                }

                if (isKeyNullExist && key1 == null) {
                    continue;
                }

                
                if (!keyExists) {
                    final Object value1 = valueElementGetter.getElementOrNull(valueArray1, i);
                    keysList.add(key1);
                    valuesList.add(value1);
                }
            }
            this.keysArray = new GenericArrayData(keysList.toArray());
            this.valuesArray = new GenericArrayData(valuesList.toArray());
        }
Code review comment: It should be. Do you have `<extensions>true</extensions>` in the `quarkus-maven-plugin` config?

Code under review:
public void close() {
            
            curatedApp.close();
            curatedApp = null;
            quarkusBootstrap = null;
        }


Revised code:
public void close() throws IOException {
        if (appBootstrapProviders.size() == 0) {
            return;
        }
        for (QuarkusAppBootstrapProvider p : appBootstrapProviders.asMap().values()) {
            try {
                p.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
Code review comment: why we use http protocal as result sink?

Code under review:
public void executeDML(String sql) {
        try {
            ConnectContext context = StatisticUtils.buildConnectContext();
            context.setThreadLocalInfo();
            StatementBase parsedStmt = SqlParser.parseOneWithStarRocksDialect(sql, context.getSessionVariable());
            Preconditions.checkState(parsedStmt instanceof DmlStmt, "the statement should be dml");
            DmlStmt dmlStmt = (DmlStmt) parsedStmt;
            ExecPlan execPlan = StatementPlanner.plan(parsedStmt, context, TResultSinkType.HTTP_PROTOCAL);
            StmtExecutor executor = new StmtExecutor(context, parsedStmt);
            context.setExecutor(executor);
            context.setQueryId(UUIDUtil.genUUID());
            executor.handleDMLStmt(execPlan, dmlStmt);
        } catch (Exception e) {
            LOG.error("Repo execute SQL failed {}", sql, e);
            throw new SemanticException("execute sql failed with exception", e);
        } finally {
            ConnectContext.remove();
        }
    }

Line commented on: ExecPlan execPlan = StatementPlanner.plan(parsedStmt, context, TResultSinkType.HTTP_PROTOCAL);

Revised code:
public void executeDML(String sql) {
        try {
            ConnectContext context = StatisticUtils.buildConnectContext();
            context.setThreadLocalInfo();
            StatementBase parsedStmt = SqlParser.parseOneWithStarRocksDialect(sql, context.getSessionVariable());
            Preconditions.checkState(parsedStmt instanceof DmlStmt, "the statement should be dml");
            DmlStmt dmlStmt = (DmlStmt) parsedStmt;
            ExecPlan execPlan = StatementPlanner.plan(parsedStmt, context, TResultSinkType.HTTP_PROTOCAL);
            StmtExecutor executor = new StmtExecutor(context, parsedStmt);
            context.setExecutor(executor);
            context.setQueryId(UUIDUtil.genUUID());
            executor.handleDMLStmt(execPlan, dmlStmt);
        } catch (Exception e) {
            LOG.error("Repo execute SQL failed {}", sql, e);
            throw new SemanticException("execute sql failed with exception", e);
        } finally {
            ConnectContext.remove();
        }
    }
Code review comment: ```suggestion                         "' defined twice with identical expression (illegal and will be enforced soon) '" + expression.getFileName() + "'."); ```

Code under review:
public void add(RankExpressionFile expression, DeployLogger deployLogger) {
        expression.validate();
        String name = expression.getName();
        if (expressions.containsKey(name)) {
            if ( expressions.get(name).getFileName().equals(expression.getFileName()) ) {
                
                deployLogger.logApplicationPackage(Level.WARNING, "Rank expression file '" + name +
                        "' defined twice with identical expression (illegal and will be enfoced soon) '" + expression.getFileName() + "'.");
            } else {
                throw new IllegalArgumentException("Rank expression file '" + name +
                        "' defined twice (illegal but not enforced), but redefinition is not matching (illegal and enforced), " +
                        "previous = '" + expressions.get(name).getFileName() + "', new = '" + expression.getFileName() + "'.");
            }
        }
        expressions.put(name, expression);
    }

Line commented on: "' defined twice with identical expression (illegal and will be enfoced soon) '" + expression.getFileName() + "'.");

Revised code:
public void add(RankExpressionFile expression, DeployLogger deployLogger) {
        expression.validate();
        String name = expression.getName();
        if (expressions.containsKey(name)) {
            if ( expressions.get(name).getFileName().equals(expression.getFileName()) ) {
                
                deployLogger.logApplicationPackage(Level.WARNING, "Rank expression file '" + name +
                        "' defined twice with identical expression (illegal and will be enforced soon) '" + expression.getFileName() + "'.");
            } else {
                throw new IllegalArgumentException("Rank expression file '" + name +
                        "' defined twice (illegal but not enforced), but redefinition is not matching (illegal and enforced), " +
                        "previous = '" + expressions.get(name).getFileName() + "', new = '" + expression.getFileName() + "'.");
            }
        }
        expressions.put(name, expression);
    }
Code review comment: Should we save some resources by guarding this with isDebugEnabled?

Code under review:
private void logCheckpointStatistics(AbstractCheckpointStats checkpointStats) {
        try {
            StringWriter sw = new StringWriter();
            MAPPER.writeValue(sw, CheckpointStatistics.generateCheckpointStatistics(checkpointStats, true));
            String jsonDump = sw.toString();
            LOG.debug("CheckpointStatistics (for jobID={}, jobName={}) dump = {} ", jobID, jobName, jsonDump);
        } catch (Exception ex) {
            LOG.error("Fail to log CheckpointStatistics", ex);
        }
    }

Line commented on: String jsonDump = sw.toString();

Revised code:
private void logCheckpointStatistics(AbstractCheckpointStats checkpointStats) {
        try {
            if (LOG.isDebugEnabled()) {
                StringWriter sw = new StringWriter();
                MAPPER.writeValue(
                        sw,
                        CheckpointStatistics.generateCheckpointStatistics(checkpointStats, true));
                String jsonDump = sw.toString();
                LOG.debug(
                        "CheckpointStatistics (for jobID={}, checkpointId={}) dump = {} ",
                        jobID,
                        checkpointStats.checkpointId,
                        jsonDump);
            }
        } catch (Exception ex) {
            LOG.warn("Fail to log CheckpointStatistics", ex);
        }
    }
Code review comment: Are you sure you want to do this? It could introduce a race condition, because multiple parallel requests will use the same object. I think this is not thread safe.

Code under review:
protected ConnectionProvider selectConnectionProvider(final String tenantIdentifier) {
        LOG.debugv("selectConnectionProvider({0})", tenantIdentifier);

        ConnectionProvider provider = providerMap.get(tenantIdentifier);
        if (provider == null) {
            final ConnectionProvider connectionProvider = resolveConnectionProvider(tenantIdentifier);
            providerMap.put(tenantIdentifier, connectionProvider);
            return connectionProvider;
        }
        return provider;

    }

Line commented on: final ConnectionProvider connectionProvider = resolveConnectionProvider(tenantIdentifier);

Revised code:
protected ConnectionProvider selectConnectionProvider(final String tenantIdentifier) {
        LOG.debugv("selectConnectionProvider({0})", tenantIdentifier);

        ConnectionProvider provider = providerMap.get(tenantIdentifier);
        if (provider == null) {
            final ConnectionProvider connectionProvider = resolveConnectionProvider(tenantIdentifier);
            providerMap.put(tenantIdentifier, connectionProvider);
            return connectionProvider;
        }
        return provider;

    }
Code review comment: How many logs will this print? Why not `debug`?

Code under review:
public Progress getProgress() {
        if (this.lastAttemptedOffset == null) {
          return Progress.from(0.0D, BigDecimal.valueOf(this.totalWork).doubleValue());
        } else {
          BigDecimal workRemaining =
              BigDecimal.valueOf(this.totalWork)
                  .subtract(BigDecimal.valueOf(this.progress), MathContext.DECIMAL128)
                  .max(BigDecimal.ZERO);
          BigDecimal work = BigDecimal.valueOf(this.totalWork);
          LOG.info("total work: " + work + " work remaining: " + workRemaining);
          return Progress.from(
              work.subtract(workRemaining, MathContext.DECIMAL128).doubleValue(),
              workRemaining.doubleValue());
        }
      }

Line commented on: LOG.info("total work: " + work + " work remaining: " + workRemaining);

Revised code:
public Progress getProgress() {
        return super.getProgress();
      }
Code review comment: ditto - this should be timestamp() not fireTimestamp()

Code under review:
public TimerMap timerFamily(String timerFamilyId) {
      try {
        TimerSpec spec =
            (TimerSpec) signature.timerFamilyDeclarations().get(timerFamilyId).field().get(fn);
        return new TimerInternalsTimerMap(
            timerFamilyId,
            window(),
            getNamespace(),
            spec,
            fireTimestamp(),
            stepContext.timerInternals());
      } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    }

Line commented on: fireTimestamp(),

Revised code:
public TimerMap timerFamily(String timerFamilyId) {
      try {
        TimerSpec spec =
            (TimerSpec) signature.timerFamilyDeclarations().get(timerFamilyId).field().get(fn);
        return new TimerInternalsTimerMap(
            timerFamilyId,
            window(),
            getNamespace(),
            spec,
            timestamp(),
            stepContext.timerInternals());
      } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    }
Code review comment: variant.toThrift(desc) will add TTypeNode to the empty list

Code under review:
protected void toThrift(TExprNode msg) {
        TSchemaChangeInfo schemaInfo = new TSchemaChangeInfo();
        schemaInfo.setTableId(tableId);
        msg.setSchemaChangeInfo(schemaInfo);
        
        variantSlot.toThrift(msg);
        msg.node_type = TExprNodeType.SCHEMA_CHANGE_EXPR;
        
        TTypeDesc desc = new TTypeDesc();
        desc.setTypes(new ArrayList<TTypeNode>());
        VariantType variant = new VariantType();
        variant.toThrift(desc);
        msg.setType(desc);
    }

Line commented on: VariantType variant = new VariantType();

Revised code:
protected void toThrift(TExprNode msg) {
        TSchemaChangeExpr schemaInfo = new TSchemaChangeExpr();
        schemaInfo.setTableId(tableId);
        msg.setSchemaChangeExpr(schemaInfo);
        
        variantSlot.toThrift(msg);
        msg.node_type = TExprNodeType.SCHEMA_CHANGE_EXPR;
        
        TTypeDesc desc = new TTypeDesc();
        desc.setTypes(new ArrayList<TTypeNode>());
        VariantType variant = new VariantType();
        variant.toThrift(desc);
        msg.setType(desc);
    }
Code review comment: if (true), it is better to overwrite `visitOnObjectClause_()` and move the content of `if condition` to the new function. Don't you think so?

Code under review:
public ASTNode visitGrant(final GrantContext ctx) {
        GrantStatement result = new GrantStatement();
        PrivilegeClause_Context privilegeClause = ctx.privilegeClause_();
        if (null != privilegeClause && null != privilegeClause.onObjectClause_()) {
            PrivilegeLevel_Context privilegeLevel = privilegeClause.onObjectClause_().privilegeLevel_();
            TableNameContext tableNameContext = privilegeLevel.tableName();
            if (null != tableNameContext) {
                TableSegment tableSegment = (TableSegment) visitTableName(tableNameContext);
                result.getAllSQLSegments().add(tableSegment);
                result.getTables().add(tableSegment);
                return result;
            }
        }
        return result;
    }

Line commented on: if (null != privilegeClause && null != privilegeClause.onObjectClause_()) {

Revised code:
public ASTNode visitGrant(final GrantContext ctx) {
        GrantStatement result = new GrantStatement();
        PrivilegeClause_Context privilegeClause = ctx.privilegeClause_();
        if (null != privilegeClause && null != privilegeClause.onObjectClause_()) {
            PrivilegeLevel_Context privilegeLevel = privilegeClause.onObjectClause_().privilegeLevel_();
            TableNameContext tableNameContext = privilegeLevel.tableName();
            if (null != tableNameContext) {
                TableSegment tableSegment = (TableSegment) visitTableName(tableNameContext);
                result.getAllSQLSegments().add(tableSegment);
                result.getTables().add(tableSegment);
                return result;
            }
        }
        return result;
    }
Code review comment: I think a better strategy would be to ask for fields named `id` and for annotations of the `jakarta.persistence.Id` type, rather than building a list of all fields and annotations. You can do this for each class in the hierarchy until you find one or you reach `Object`.

Code under review:
private void validateClassHasFieldId(IndexView index, String entityType) {
        
        DotName className = DotName.createSimple(entityType);
        List<FieldInfo> classFields = index.getClassByName(className).fields();
        List<AnnotationInstance> classAnnotations = index.getClassByName(className).annotations();

        LinkedList<FieldInfo> allFields = new LinkedList<>(classFields);
        LinkedList<AnnotationInstance> allAnnotations = new LinkedList<>(classAnnotations);

        
        DotName superClassName = index.getClassByName(className).superName();
        while (superClassName != null) {
            List<FieldInfo> allSuperFields = index.getClassByName(superClassName).fields();
            List<AnnotationInstance> allSuperAnnotations = index.getClassByName(superClassName).annotations();
            allFields.addAll(allSuperFields);
            allAnnotations.addAll(allSuperAnnotations);

            className = superClassName;
            superClassName = index.getClassByName(className).superName();
        }

        List<FieldInfo> fieldsNamedId = allFields.stream().filter(f -> f.name().equals("id")).collect(Collectors.toList());
        List<AnnotationInstance> fieldsAnnotatedWithId = allAnnotations.stream()
                .filter(a -> a.name().toString().endsWith("persistence.Id"))
                .collect(Collectors.toList());

        if (fieldsNamedId.isEmpty() && fieldsAnnotatedWithId.isEmpty()) {
            throw new IllegalStateException("Cannot generate web links for the class " + entityType +
                    " because is either missing an `id` field or a field with an `@Id` annotation");
        }
    }

Line commented on: List<FieldInfo> classFields = index.getClassByName(className).fields();

Revised code:
private void validateClassHasFieldId(IndexView index, String entityType) {
        
        DotName className = DotName.createSimple(entityType);
        ClassInfo classInfo = index.getClassByName(className);

        if (classInfo == null) {
            throw new RuntimeException(String.format("Class '%s' was not found", classInfo));
        }
        validateRec(index, entityType, classInfo);
    }
Code review comment: @geoand @ge0ffrey Fixed by modifying the `config` using `withAdapters()`, the integration test works with expected output, for both non native and native mode. Latest changes have been pushed and squashed.

Code under review:
public void customize(JsonbConfig config) {
        config = OptaPlannerJsonbConfig.createConfig();
    }

Line commented on: config = OptaPlannerJsonbConfig.createConfig();

Revised code:
public void customize(JsonbConfig config) {
        
        config.withAdapters(new BendableScoreJsonbAdapter(),
                new BendableBigDecimalScoreJsonbAdapter(),
                new BendableLongScoreJsonbAdapter(),
                new HardMediumSoftScoreJsonbAdapter(),
                new HardMediumSoftBigDecimalScoreJsonbAdapter(),
                new HardMediumSoftLongScoreJsonbAdapter(),
                new HardSoftScoreJsonbAdapter(),
                new HardSoftBigDecimalScoreJsonbAdapter(),
                new HardSoftDoubleScoreJsonbAdapter(),
                new HardSoftLongScoreJsonbAdapter(),
                new SimpleScoreJsonbAdapter(),
                new SimpleBigDecimalScoreJsonbAdapter(),
                new SimpleDoubleScoreJsonbAdapter(),
                new SimpleLongScoreJsonbAdapter());
    }
Code review comment: Do we need the check for the found symbol? `hasSameOwner` being false would imply it's not from the same (testable) package?

Code under review:
private boolean isSymbolRedeclaredInTestPackage(BSymbol symbol, BSymbol foundSym) {
        if (Symbols.isFlagOn(symbol.owner.flags, Flags.TESTABLE) &&
                !Symbols.isFlagOn(foundSym.owner.flags, Flags.TESTABLE)) {
            return true;
        }
        return false;
    }

Line commented on: !Symbols.isFlagOn(foundSym.owner.flags, Flags.TESTABLE)) {

Revised code:
private boolean isSymbolRedeclaredInTestPackage(BSymbol symbol, BSymbol foundSym) {
        if (Symbols.isFlagOn(symbol.owner.flags, Flags.TESTABLE) &&
                !Symbols.isFlagOn(foundSym.owner.flags, Flags.TESTABLE)) {
            return true;
        }
        return false;
    }
Code review comment: nit; If we already have the value of `certificateBundle.getCer()` in `certificateString` we can use the variable here. ```suggestion                         new ByteArrayInputStream(Base64.getDecoder().decode(certificateString)) ```

Code under review:
public Certificate getCertificate(String alias) {
        LOGGER.entering("KeyVaultClient", "getCertificate", alias);
        LOGGER.log(INFO, "Getting certificate for alias: {0}", alias);
        X509Certificate certificate = null;
        CertificateBundle certificateBundle = getCertificateBundle(alias);
        if (certificateBundle != null) {
            String certificateString = certificateBundle.getCer();
            if (certificateString != null) {
                try {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    certificate = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer()))
                    );
                } catch (CertificateException ce) {
                    LOGGER.log(WARNING, "Certificate error", ce);
                }
            }
        }
        LOGGER.exiting("KeyVaultClient", "getCertificate", certificate);
        return certificate;
    }

Line commented on: new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer()))

Revised code:
public Certificate getCertificate(String alias) {
        LOGGER.entering("KeyVaultClient", "getCertificate", alias);
        LOGGER.log(INFO, "Getting certificate for alias: {0}", alias);
        X509Certificate certificate = null;
        CertificateBundle certificateBundle = getCertificateBundle(alias);
        if (certificateBundle != null) {
            String certificateString = certificateBundle.getCer();
            if (certificateString != null) {
                try {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    certificate = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer()))
                    );
                } catch (CertificateException ce) {
                    LOGGER.log(WARNING, "Certificate error", ce);
                }
            }
        }
        LOGGER.exiting("KeyVaultClient", "getCertificate", certificate);
        return certificate;
    }
Code review comment: I just tested that. Seems like returning `in` while the user has types `o` doesn't show `in` as a suggestion in VSCode.

Code under review:
private boolean onSuggestInKeyword(BallerinaCompletionContext context, JoinClauseNode node) {
        int cursor = context.getCursorPositionInTree();
        TypedBindingPatternNode typedBindingPattern = node.typedBindingPattern();

        if (!node.inKeyword().isMissing() || typedBindingPattern.isMissing()) {
            return false;
        } else if (cursor > typedBindingPattern.textRange().endOffset() &&
                cursor <= node.expression().textRange().startOffset()) {
            /*
             * Captures:
             * (1) join var varName <cursor>
             */
            return true;
        } else {
            Node nodeAtCursor = context.getNodeAtCursor();

            /*
             * Captures:
             * (1) join var varName i<cursor>
             * (2) join var varName i<cursor> expression
             */
            if (nodeAtCursor.kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) {
                SimpleNameReferenceNode nameReferenceNode = (SimpleNameReferenceNode) nodeAtCursor;
                return node.expression().textRange().startOffset() + 1 == cursor &&
                        nameReferenceNode.textRange().startOffset() + 1 == cursor &&
                        ItemResolverConstants.IN_KEYWORD.startsWith(nameReferenceNode.name().text());
            }
        }

        return false;
    }

Line commented on: * (2) join var varName i<cursor> expression

Revised code:
private boolean onSuggestInKeyword(BallerinaCompletionContext context, JoinClauseNode node) {
        int cursor = context.getCursorPositionInTree();
        TypedBindingPatternNode typedBindingPattern = node.typedBindingPattern();

        if (!node.inKeyword().isMissing() || typedBindingPattern.isMissing()) {
            return false;
        } else if (cursor > typedBindingPattern.textRange().endOffset() &&
                cursor <= node.expression().textRange().startOffset()) {
            /*
             * Captures:
             * (1) join var varName <cursor>
             */
            return true;
        } else {
            Node nodeAtCursor = context.getNodeAtCursor();

            /*
             * Captures:
             * (1) join var varName i<cursor>
             * (2) join var varName i<cursor> expression
             */
            if (nodeAtCursor.kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) {
                SimpleNameReferenceNode nameReferenceNode = (SimpleNameReferenceNode) nodeAtCursor;
                return node.expression().textRange().startOffset() + 1 == cursor &&
                        nameReferenceNode.textRange().startOffset() + 1 == cursor;
            }
        }

        return false;
    }
Code review comment: its error trace and I am not seeing them at-least in my runs.  --- In reply to: [487800413](https://github.com/Azure/azure-sdk-for-java/pull/15157#discussion_r487800413) [](ancestors = 487800413)

Code under review:
private void runTasksInPendingAcquisitionQueue() {
        ensureInEventLoop();

        this.ensureInEventLoop();
        int channelsAvailable = this.availableChannels.size();

        
        
        
        do {

            
            final AcquireTask task = this.pendingAcquisitions.poll();


            if (task == null) {
                break;
            }

            final ScheduledFuture<?> timeoutFuture = task.timeoutFuture;

            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }

            task.acquired(true);
            this.acquire(task.promise);
        } while (--channelsAvailable> 0);
    }

Line commented on: this.ensureInEventLoop();

Revised code:
private void runTasksInPendingAcquisitionQueue() {
        this.ensureInEventLoop();
        int channelsAvailable = this.availableChannels.size();

        
        
        
        do {

            
            final AcquireTask task = this.pendingAcquisitions.poll();

            if (task == null) {
                break;
            }

            task.acquired(true);
            this.acquire(task.promise);
        } while (--channelsAvailable > 0);
    }
Code review comment: Shall we log exception instance as well?

Code under review:
public BValue[] execute(Context context) {
        BStruct channel;
        BStruct errorStruct = null;
        try {
            channel = (BStruct) getRefArgument(context, BYTE_CHANNEL_INDEX);
            Channel byteChannel = (Channel) channel.getNativeData(IOConstants.BYTE_CHANNEL_NAME);
            EventContext eventContext = new EventContext(context);
            CloseByteChannelEvent closeEvent = new CloseByteChannelEvent(byteChannel, eventContext);
            CompletableFuture<EventResult> future = EventManager.getInstance().publish(closeEvent);
            EventResult eventResult = future.get();
            Throwable error = ((EventContext) eventResult.getContext()).getError();
            if (null != error) {
                errorStruct = IOUtils.createError(context, error.getMessage());
            }
        } catch (Throwable e) {
            String message = "Failed to close the channel:" + e.getMessage();
            log.error(message);
            errorStruct = IOUtils.createError(context, message);
        }
        return getBValues(errorStruct);
    }

Line commented on: log.error(message);

Revised code:
public BValue[] execute(Context context) {
        BStruct errorStruct = null;
        try {
            BStruct channel = (BStruct) getRefArgument(context, BYTE_CHANNEL_INDEX);
            Channel byteChannel = (Channel) channel.getNativeData(IOConstants.BYTE_CHANNEL_NAME);
            EventContext eventContext = new EventContext(context);
            CloseByteChannelEvent closeEvent = new CloseByteChannelEvent(byteChannel, eventContext);
            CompletableFuture<EventResult> future = EventManager.getInstance().publish(closeEvent);
            EventResult eventResult = future.get();
            Throwable error = ((EventContext) eventResult.getContext()).getError();
            if (null != error) {
                errorStruct = IOUtils.createError(context, error.getMessage());
            }
        } catch (Throwable e) {
            String message = "Failed to close the channel:" + e.getMessage();
            log.error(message, e);
            errorStruct = IOUtils.createError(context, message);
        }
        return getBValues(errorStruct);
    }
Code review comment: This looks like a design flaw that if `getConfiguration` and `getOptions` are equivalent, then why do we need to provide both of them?   In DynamicTableFactory, the configuration represents the configs of the session, and options represent the table WITH options. I think we can change the methods to `getFlinkConfiguration()` and `getEndpointOptions()` to make it clear.

Code under review:
private static void validateSpecifiedEndpointsAreUnique(List<String> identifiers) {
        Set<String> uniqueIdentifiers = new HashSet<>();

        for (String identifier : identifiers) {
            if (uniqueIdentifiers.contains(identifier)) {
                throw new ValidationException(
                        String.format(
                                "Get the duplicate endpoint identifier: %s. Please keep the specified endpoint identifier unique.",
                                identifier));
            }
            uniqueIdentifiers.add(identifier);
        }
    }

Line commented on: throw new ValidationException(

Revised code:
private static void validateSpecifiedEndpointsAreUnique(List<String> identifiers) {
        Set<String> uniqueIdentifiers = new HashSet<>();

        for (String identifier : identifiers) {
            if (uniqueIdentifiers.contains(identifier)) {
                throw new ValidationException(
                        String.format(
                                "Get the duplicate endpoint identifier '%s' for the option '%s'. "
                                        + "Please keep the specified endpoint identifier unique.",
                                identifier, SQL_GATEWAY_ENDPOINT_TYPE.key()));
            }
            uniqueIdentifiers.add(identifier);
        }
    }
Code review comment: This is not enough to clean the timer. The method call will only evict the timer meta information used to delete timers by id (Flink does not allow to delete timers by id, you always need to supply the original timestamp of the the timer). See the deleteTimer method below for the additional delete step on Flink's timer service.

Code under review:
public void deleteTimer(StateNamespace namespace, String timerId, TimeDomain timeDomain) {
      try {
        cancelPendingTimerById(getContextTimerId(timerId, namespace));
      } catch (Exception e) {
        throw new RuntimeException("Failed to cancel timer", e);
      }
    }

Line commented on: cancelPendingTimerById(getContextTimerId(timerId, namespace));

Revised code:
public void deleteTimer(StateNamespace namespace, String timerId, TimeDomain timeDomain) {
      try {
        cancelPendingTimerById(getContextTimerId(timerId, namespace));
      } catch (Exception e) {
        throw new RuntimeException("Failed to cancel timer", e);
      }
    }
Code review comment: If we use `UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup().getIOMetricGroup()` here, maybe we can get rid of your new `mock`? Then we could just use `metricGroup#getIOMetricGroup` for assertions.

Code under review:
public static InternalSinkWriterMetricGroup mock(MetricGroup metricGroup) {
        return new InternalSinkWriterMetricGroup(
                metricGroup, UnregisteredMetricsGroup.createOperatorIOMetricGroup());
    }

Line commented on: metricGroup, UnregisteredMetricsGroup.createOperatorIOMetricGroup());

Revised code:
public static InternalSinkWriterMetricGroup mock(MetricGroup metricGroup) {
        return new InternalSinkWriterMetricGroup(
                metricGroup, UnregisteredMetricsGroup.createOperatorIOMetricGroup());
    }
Code review comment: properties.put(MEMORY_LIMIT, "100"); this.memoryLimitPercent = 100;

Code under review:
public void gsonPostProcess() throws IOException {
        if (properties.containsKey(MEMORY_LIMIT)) {
            String memoryLimitString = properties.get(MEMORY_LIMIT);
            this.memoryLimitPercent = Double.parseDouble(memoryLimitString.substring(0,
                    memoryLimitString.length() - 1));
        } else {
            this.memoryLimitPercent = 100;
        }
        this.initQueryQueue();
    }

Line commented on: this.memoryLimitPercent = 100;

Revised code:
public void gsonPostProcess() throws IOException {
        if (properties.containsKey(MEMORY_LIMIT)) {
            String memoryLimitString = properties.get(MEMORY_LIMIT);
            this.memoryLimitPercent = Double.parseDouble(memoryLimitString.substring(0,
                    memoryLimitString.length() - 1));
        } else {
            this.memoryLimitPercent = 100;
            this.properties.put(MEMORY_LIMIT, "100%");
        }
        this.initQueryQueue();
    }
Code review comment: Well, I used the `ConcurrentMap` here to ensure visibility and not to eliminate race conditions. But you're right that it wouldn not hurt to `computeIfAbsent()` ;-)

Code under review:
private Object resolveInject(EvalContext ctx) {
        InjectableBean<?> bean = container.namedBean(ctx.getName());
        if (bean != null) {
            if (bean.getScope().equals(Dependent.class)) {
                
                Object dependentInstances = ctx.getAttribute(EngineProducer.DEPENDENT_INSTANCES);
                if (dependentInstances != null) {
                    @SuppressWarnings("unchecked")
                    ConcurrentMap<String, InstanceHandle<?>> existing = (ConcurrentMap<String, InstanceHandle<?>>) dependentInstances;
                    InstanceHandle<?> handle = existing.get(ctx.getName());
                    if (handle == null) {
                        handle = container.instance(bean);
                        existing.put(ctx.getName(), handle);
                    }
                    return handle.get();
                }
            }
            return container.instance(bean).get();
        }
        return Results.NotFound.from(ctx);
    }

Line commented on: InstanceHandle<?> handle = existing.get(ctx.getName());

Revised code:
private Object resolveInject(EvalContext ctx) {
        InjectableBean<?> bean = container.namedBean(ctx.getName());
        if (bean != null) {
            if (bean.getScope().equals(Dependent.class)) {
                
                Object dependentInstances = ctx.getAttribute(EngineProducer.DEPENDENT_INSTANCES);
                if (dependentInstances != null) {
                    @SuppressWarnings("unchecked")
                    ConcurrentMap<String, InstanceHandle<?>> existing = (ConcurrentMap<String, InstanceHandle<?>>) dependentInstances;
                    return existing.computeIfAbsent(ctx.getName(), name -> container.instance(bean)).get();
                }
            }
            return container.instance(bean).get();
        }
        return Results.NotFound.from(ctx);
    }
Code review comment: Any particular reason to swap the order of the two checks?

Code under review:
private static String getPackageAlias(SymbolEnv env, String compUnitName, PackageID typePkgId) {
        for (BLangImportPackage importStmt : env.enclPkg.imports) {
            if (!importStmt.compUnit.value.equals(compUnitName)) {
                continue;
            }

            if (importStmt.symbol != null && typePkgId.equals(importStmt.symbol.pkgID)) {
                return importStmt.alias.value;
            }
        }

        return ""; 
    }

Line commented on: if (importStmt.symbol != null && typePkgId.equals(importStmt.symbol.pkgID)) {

Revised code:
private static String getPackageAlias(SymbolEnv env, String compUnitName, PackageID typePkgId) {
        for (BLangImportPackage importStmt : env.enclPkg.imports) {
            if (!importStmt.compUnit.value.equals(compUnitName)) {
                continue;
            }

            if (importStmt.symbol != null && typePkgId.equals(importStmt.symbol.pkgID)) {
                return importStmt.alias.value;
            }
        }

        return ""; 
    }
Code review comment: I added the assertion. It can't hurt because we may have upstream operators that misbehave (custom operators).

Code under review:
private void emitCommittables(long checkpointId) throws IOException, InterruptedException {
        if (!emitDownstream) {
            
            
            if (sinkWriter instanceof CommittingSinkWriter) {
                ((CommittingSinkWriter<?, ?>) sinkWriter).prepareCommit();
            }
            return;
        }
        Collection<CommT> committables =
                ((CommittingSinkWriter<?, CommT>) sinkWriter).prepareCommit();
        StreamingRuntimeContext runtimeContext = getRuntimeContext();
        final int indexOfThisSubtask = runtimeContext.getTaskInfo().getIndexOfThisSubtask();
        final int numberOfParallelSubtasks =
                runtimeContext.getTaskInfo().getNumberOfParallelSubtasks();

        
        if (!legacyCommittables.isEmpty()) {
            checkState(checkpointId > InitContext.INITIAL_CHECKPOINT_ID);
            emit(
                    indexOfThisSubtask,
                    numberOfParallelSubtasks,
                    InitContext.INITIAL_CHECKPOINT_ID,
                    legacyCommittables);
            legacyCommittables.clear();
        }
        emit(indexOfThisSubtask, numberOfParallelSubtasks, checkpointId, committables);
    }


Revised code:
private void emitCommittables(long checkpointId) throws IOException, InterruptedException {
        if (!emitDownstream) {
            
            
            if (sinkWriter instanceof CommittingSinkWriter) {
                ((CommittingSinkWriter<?, ?>) sinkWriter).prepareCommit();
            }
            return;
        }
        Collection<CommT> committables =
                ((CommittingSinkWriter<?, CommT>) sinkWriter).prepareCommit();
        StreamingRuntimeContext runtimeContext = getRuntimeContext();
        final int indexOfThisSubtask = runtimeContext.getTaskInfo().getIndexOfThisSubtask();
        final int numberOfParallelSubtasks =
                runtimeContext.getTaskInfo().getNumberOfParallelSubtasks();

        
        if (!legacyCommittables.isEmpty()) {
            checkState(checkpointId > InitContext.INITIAL_CHECKPOINT_ID);
            emit(
                    indexOfThisSubtask,
                    numberOfParallelSubtasks,
                    InitContext.INITIAL_CHECKPOINT_ID,
                    legacyCommittables);
            legacyCommittables.clear();
        }
        emit(indexOfThisSubtask, numberOfParallelSubtasks, checkpointId, committables);
    }
Code review comment: This wouldn't be necessary at all if the upstream project just built an MR-jar.

Code under review:
public GeneratedClassBuildItem replaceJava9Code() {
        
        byte[][] holder = new byte[1][];
        ClassOutput classOutput = new ClassOutput() {
            public void write(final String name, final byte[] data) {
                holder[0] = data;
            }
        };
        try (ClassCreator cc = ClassCreator.builder().className(TARGET_JAVA_9_CHECKSUM_FACTORY)
                .classOutput(classOutput).setFinal(true).superClass(Object.class).build()) {

            cc.addAnnotation("com/oracle/svm/core/annotate/TargetClass").addValue("className",
                    "org.apache.kafka.common.utils.Crc32C$Java9ChecksumFactory");
            cc.addAnnotation("com/oracle/svm/core/annotate/Substitute");

            try (MethodCreator mc = cc.getMethodCreator("create", Checksum.class)) {
                mc.addAnnotation("com/oracle/svm/core/annotate/Substitute");
                mc.returnValue(mc.newInstance(MethodDescriptor.ofConstructor("java.util.zip.CRC32C")));
            }
        }
        return new GeneratedClassBuildItem(false, TARGET_JAVA_9_CHECKSUM_FACTORY, holder[0]);
    }

Line commented on: return new GeneratedClassBuildItem(false, TARGET_JAVA_9_CHECKSUM_FACTORY, holder[0]);

Revised code:
public GeneratedClassBuildItem replaceJava9Code() {
        
        byte[][] holder = new byte[1][];
        ClassOutput classOutput = new ClassOutput() {
            public void write(final String name, final byte[] data) {
                holder[0] = data;
            }
        };
        try (ClassCreator cc = ClassCreator.builder().className(TARGET_JAVA_9_CHECKSUM_FACTORY)
                .classOutput(classOutput).setFinal(true).superClass(Object.class).build()) {

            cc.addAnnotation("com/oracle/svm/core/annotate/TargetClass").addValue("className",
                    "org.apache.kafka.common.utils.Crc32C$Java9ChecksumFactory");
            cc.addAnnotation("com/oracle/svm/core/annotate/Substitute");

            try (MethodCreator mc = cc.getMethodCreator("create", Checksum.class)) {
                mc.addAnnotation("com/oracle/svm/core/annotate/Substitute");
                mc.returnValue(mc.newInstance(MethodDescriptor.ofConstructor("java.util.zip.CRC32C")));
            }
        }
        return new GeneratedClassBuildItem(false, TARGET_JAVA_9_CHECKSUM_FACTORY, holder[0]);
    }
Code review comment: for checkstyle: `preTransactionType != null` => `null != preTransactionType`

Code under review:
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
        ShardingTransactionType shardingTransactionType = getAnnotation(methodInvocation);
        Objects.requireNonNull(shardingTransactionType, "could not found sharding transaction type annotation");
        TransactionType preTransactionType = TransactionTypeHolder.get();
        TransactionTypeHolder.set(shardingTransactionType.value());
        try {
            return methodInvocation.proceed();
        } finally {
            TransactionTypeHolder.clear();
            if (preTransactionType != null) {
                TransactionTypeHolder.set(preTransactionType);
            }
        }
    }

Line commented on: if (preTransactionType != null) {

Revised code:
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
        ShardingTransactionType shardingTransactionType = getAnnotation(methodInvocation);
        Objects.requireNonNull(shardingTransactionType, "could not found sharding transaction type annotation");
        TransactionType preTransactionType = TransactionTypeHolder.get();
        TransactionTypeHolder.set(shardingTransactionType.value());
        try {
            return methodInvocation.proceed();
        } finally {
            TransactionTypeHolder.clear();
            if (null != preTransactionType) {
                TransactionTypeHolder.set(preTransactionType);
            }
        }
    }
Code review comment: the majority of these tests could be moved into a shared method to reduce code duplication.

Code under review:
public void testReleaseOnFailure() throws Exception {
		final CassandraSinkBaseConfig config = CassandraSinkBaseConfig.newBuilder()
			.setMaxConcurrentRequests(1)
			.setMaxConcurrentRequestsTimeout(5, TimeUnit.MILLISECONDS)
			.build();
		TestCassandraSink casSinkFunc = new TestCassandraSink(config);

		casSinkFunc.open(new Configuration());

		CompletableFuture<ResultSet> completableFuture = new CompletableFuture<>();

		casSinkFunc.enqueueResultSetFuture(ResultSetFutures.fromCompletableFuture(completableFuture));

		Assert.assertEquals(1, casSinkFunc.getAvailablePermits());
		Assert.assertEquals(0, casSinkFunc.getAcquiredPermits());

		casSinkFunc.invoke("hello");

		Assert.assertEquals(0, casSinkFunc.getAvailablePermits());
		Assert.assertEquals(1, casSinkFunc.getAcquiredPermits());

		completableFuture.completeExceptionally(new RuntimeException());

		Assert.assertEquals(1, casSinkFunc.getAvailablePermits());
		Assert.assertEquals(0, casSinkFunc.getAcquiredPermits());

		try {
			casSinkFunc.close();
		} catch (Exception e) {
			Assert.assertTrue(e.getMessage().contains("Error while sending value"));
		}
	}

Line commented on: Assert.assertEquals(1, casSinkFunc.getAvailablePermits());

Revised code:
public void testReleaseOnFailure() throws Exception {
		final CassandraSinkBaseConfig config = CassandraSinkBaseConfig.newBuilder()
			.setMaxConcurrentRequests(1)
			.build();
		final CassandraFailureHandler failureHandler = ignored -> {};

		try (TestCassandraSink testCassandraSink = createOpenedTestCassandraSink(config, failureHandler)) {
			Assert.assertEquals(1, testCassandraSink.getAvailablePermits());
			Assert.assertEquals(0, testCassandraSink.getAcquiredPermits());

			CompletableFuture<ResultSet> completableFuture = new CompletableFuture<>();
			testCassandraSink.enqueueCompletableFuture(completableFuture);
			testCassandraSink.invoke("N/A");

			Assert.assertEquals(0, testCassandraSink.getAvailablePermits());
			Assert.assertEquals(1, testCassandraSink.getAcquiredPermits());

			completableFuture.completeExceptionally(new RuntimeException());

			Assert.assertEquals(1, testCassandraSink.getAvailablePermits());
			Assert.assertEquals(0, testCassandraSink.getAcquiredPermits());
		}
	}
Code review comment: When does this happen？ the cache file has  deleted Manually？

Code under review:
private SeekableInputStream cachedStream() throws IOException {
            try {
                CacheEntry entry = contentCache.get(location(), k -> newCacheEntry());
                Preconditions.checkNotNull(entry, "CacheEntry should not be null when there is no RuntimeException occurs");
                
                if (!entry.isExistOnDisk()) {
                    LOG.info("local file {} has been deleted, but still in cache, reload it", location());
                    contentCache.invalidate(location());
                    entry = contentCache.get(location(), k -> newCacheEntry());
                }
                Preconditions.checkNotNull(entry, "CacheEntry should not be null when there is no RuntimeException occurs");
                return entry.toSeekableInputStream();
            } catch (RuntimeIOException ex) {
                throw ex.getCause();
            } catch (RuntimeException ex) {
                throw new IOException("Caught an error while reading through cache", ex);
            }
        }

Line commented on: if (!entry.isExistOnDisk()) {

Revised code:
private SeekableInputStream cachedStream() throws IOException {
            try {
                CacheEntry entry = contentCache.get(location(), k -> newCacheEntry());
                Preconditions.checkNotNull(entry, "CacheEntry should not be null when there is no RuntimeException occurs");
                
                if (!entry.isExistOnDisk()) {
                    LOG.info("local file {} has been deleted, but still in cache, reload it", location());
                    contentCache.invalidate(location());
                    entry = contentCache.get(location(), k -> newCacheEntry());
                }
                Preconditions.checkNotNull(entry, "CacheEntry should not be null when there is no RuntimeException occurs");
                return entry.toSeekableInputStream();
            } catch (RuntimeIOException ex) {
                throw ex.getCause();
            } catch (RuntimeException ex) {
                throw new IOException("Caught an error while reading through cache", ex);
            }
        }