muttakin2301/ccr2000 huggingface dataset:
Code review comment: we need to validate whether there are any whitespaces/trivia between the tokens. Can log an error and continue.

Code under review:
private STNode parseTrippleGTToken() {
        STNode openGTToken = parseGTToken();
        STNode middleLGToken = parseGTToken();
        STNode endLGToken = parseGTToken();
        return STNodeFactory.createTrippleGTTokenNode(openGTToken, middleLGToken, endLGToken);
    }

Line commented on: STNode endLGToken = parseGTToken();

Revised code:
private STNode parseTrippleGTToken() {
        STNode openGTToken = parseGTToken();
        reportInvalidShiftOperator(openGTToken);

        STNode middleGTToken = parseGTToken();
        reportInvalidShiftOperator(middleGTToken);

        STNode endLGToken = parseGTToken();
        return STNodeFactory.createTrippleGTTokenNode(openGTToken, middleGTToken, endLGToken);
    }
Code review comment: Moreover, if the credential is required, we can move the validation up to buildClient()

Code under review:
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) {
        this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
        return this;
    }

Line commented on: this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");

Revised code:
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) {
        this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
        return this;
    }
Code review comment: `baseMessage` could be returned here instead of retrieving it from the super class again.

Code under review:
public String getMessage() {
        String baseMessage = super.getMessage();

        if (this.errorCodeValue == null) {
            return super.getMessage();
        } else {
            baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "ErrorCodeValue",
                errorCodeValue);
        }

        if (this.target == null) {
            return baseMessage;
        } else {
            baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "target", target);
        }

        return baseMessage;
    }

Line commented on: return super.getMessage();

Revised code:
public String getMessage() {
        StringBuilder baseMessage = new StringBuilder().append(super.getMessage()).append(" ").append(ERROR_CODE)
            .append(": {").append(errorCodeValue).append("}");

        if (this.target == null) {
            return baseMessage.toString();
        } else {
            return baseMessage.append(", ").append(TARGET).append(": {").append(target).append("}").toString();
        }
    }
Code review comment: duplicated code could probably be moved to a method

Code under review:
String bindUpdate(Class<?> clazz, String query, Map<String, Object> params) {
        String bindUpdate = bindQuery(clazz, query, params);
        boolean containsOperator = false;
        for (String operator : UPDATE_OPERATORS) {
            if (bindUpdate.contains(operator)) {
                containsOperator = true;
            }
        }
        if (!containsOperator) {
            bindUpdate = "{'$set':" + bindUpdate + "}";
        }
        LOGGER.debug(bindUpdate);
        return bindUpdate;
    }

Line commented on: boolean containsOperator = false;

Revised code:
String bindUpdate(Class<?> clazz, String query, Map<String, Object> params) {
        String bindUpdate = bindQuery(clazz, query, params);
        if (!containsUpdateOperator(query)) {
            bindUpdate = "{'$set':" + bindUpdate + "}";
        }
        LOGGER.debug(bindUpdate);
        return bindUpdate;
    }
Code review comment: can be shortened to `notNumberGauges.forEach(gauges::remove);`

Code under review:
public void report() {
		DatadogHttpRequest request = new DatadogHttpRequest();
		List<Gauge> notNumberGauges = new ArrayList<>();
		for (Map.Entry<Gauge, DGauge> entry : gauges.entrySet()) {
			DGauge g = entry.getValue();
			try {
				
				
				g.getMetricValue();
				request.addGauge(g);
			} catch (Exception e) {
				LOGGER.warn("the Gauge {} is not of Number type", g.getMetric());
				notNumberGauges.add(entry.getKey());
			}
		}
		
		if (!notNumberGauges.isEmpty()) {
			notNumberGauges.stream().forEach(g -> gauges.remove(g));
		}
		for (DCounter c : counters.values()) {
			request.addCounter(c);
		}

		for (DMeter m : meters.values()) {
			request.addMeter(m);
		}

		try {
			client.send(request);
		} catch (SocketTimeoutException e) {
			LOGGER.warn("Failed reporting metrics to Datadog because of socket timeout.", e.getMessage());
		} catch (Exception e) {
			LOGGER.warn("Failed reporting metrics to Datadog.", e);
		}
	}

Line commented on: notNumberGauges.stream().forEach(g -> gauges.remove(g));

Revised code:
public void report() {
		DatadogHttpRequest request = new DatadogHttpRequest();

		List<Gauge> gaugesToRemove = new ArrayList<>();
		for (Map.Entry<Gauge, DGauge> entry : gauges.entrySet()) {
			DGauge g = entry.getValue();
			try {
				
				
				g.getMetricValue();
				request.addGauge(g);
			} catch (ClassCastException e) {
				LOGGER.info("The metric {} will not be reported because only number types are supported by this reporter.", g.getMetric());
				gaugesToRemove.add(entry.getKey());
			} catch (Exception e) {
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("The metric {} will not be reported because it threw an exception.", g.getMetric(), e);
				} else {
					LOGGER.info("The metric {} will not be reported because it threw an exception.", g.getMetric());
				}
				gaugesToRemove.add(entry.getKey());
			}
		}
		gaugesToRemove.forEach(gauges::remove);

		for (DCounter c : counters.values()) {
			request.addCounter(c);
		}

		for (DMeter m : meters.values()) {
			request.addMeter(m);
		}

		try {
			client.send(request);
		} catch (SocketTimeoutException e) {
			LOGGER.warn("Failed reporting metrics to Datadog because of socket timeout.", e.getMessage());
		} catch (Exception e) {
			LOGGER.warn("Failed reporting metrics to Datadog.", e);
		}
	}
Code review comment: Your idea is good and easy to implement. I've created the PR#22 (https://github.com/dataArtisans/flink-benchmarks/pull/22) for benchmarks.

Code under review:
public boolean processInput() throws Exception {
		if (!initialized) {
			initialize();
		}

		int readingInputIndex = inputSelection.fairSelectNextIndexOutOf2(availableInputsMask, lastReadInputIndex);
		if (readingInputIndex == -1) {
			return waitForAvailableInput(inputSelection);
		}
		lastReadInputIndex = readingInputIndex;

		
		
		if (availableInputsMask < 3 && inputSelection.isALLMaskOf2()) {
			checkAndSetAvailable(1 - readingInputIndex);
		}

		StreamElement recordOrMark;
		if (readingInputIndex == 0) {
			recordOrMark = input1.pollNextNullable();
			if (recordOrMark != null) {
				processElement1(recordOrMark, input1.getLastChannel());
			}
		} else {
			recordOrMark = input2.pollNextNullable();
			if (recordOrMark != null) {
				processElement2(recordOrMark, input2.getLastChannel());
			}
		}

		if (recordOrMark == null && setUnavailableAndCheckFinished(readingInputIndex)) {
			return false; 
		}

		return true;
	}

Line commented on: checkAndSetAvailable(1 - readingInputIndex);

Revised code:
public boolean processInput() throws Exception {
		if (!isPrepared) {
			
			
			prepareForProcessing();
		}

		int readingInputIndex = selectNextReadingInputIndex();
		if (readingInputIndex == -1) {
			return false;
		}
		lastReadInputIndex = readingInputIndex;

		StreamElement recordOrMark;
		if (readingInputIndex == 0) {
			recordOrMark = input1.pollNextNullable();
			if (recordOrMark != null) {
				processElement1(recordOrMark, input1.getLastChannel());
			}
		} else {
			recordOrMark = input2.pollNextNullable();
			if (recordOrMark != null) {
				processElement2(recordOrMark, input2.getLastChannel());
			}
		}

		if (recordOrMark == null) {
			setUnavailableInput(readingInputIndex);
		}

		return !checkFinished();
	}
Code review comment: Actually, why isn't this in the format string?

Code under review:
public String getMessage() {
        String baseMessage = super.getMessage();

        if (this.errorCodeValue == null) {
            return super.getMessage();
        } else {
            baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "ErrorCodeValue",
                errorCodeValue);
        }

        if (this.target == null) {
            return baseMessage;
        } else {
            baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "target", target);
        }

        return baseMessage;
    }

Line commented on: baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "ErrorCodeValue",

Revised code:
public String getMessage() {
        StringBuilder baseMessage = new StringBuilder().append(super.getMessage()).append(" ").append(ERROR_CODE)
            .append(": {").append(errorCodeValue).append("}");

        if (this.target == null) {
            return baseMessage.toString();
        } else {
            return baseMessage.append(", ").append(TARGET).append(": {").append(target).append("}").toString();
        }
    }
Code review comment: i think make this comment as a method function should be better

Code under review:
public void analyze(Analyzer analyzer) throws UserException {
        
        
        
        Analyzer dummyRootAnalyzer = new Analyzer(analyzer.getCatalog(), analyzer.getContext());
        QueryStmt tmpStmt = queryStmt.clone();
        tmpStmt.analyze(dummyRootAnalyzer);
        this.queryStmt = tmpStmt;
        ArrayList<Expr> resultExprs = getQueryStmt().getResultExprs();
        
        for (Expr expr : resultExprs) {
            if (expr.getType().isDecimalV2()) {
                ErrorReport.reportAnalysisException(ErrorCode.ERR_UNSUPPORTED_TYPE_IN_CTAS, expr.getType());
            }
        }
        if (columnNames != null && columnNames.size() != resultExprs.size()) {
            ErrorReport.reportAnalysisException(ErrorCode.ERR_COL_NUMBER_NOT_MATCH);
        }
        
    }


Revised code:
public void analyze(Analyzer analyzer) throws UserException {
        
        
        
        Analyzer dummyRootAnalyzer = new Analyzer(analyzer.getCatalog(), analyzer.getContext());
        QueryStmt tmpStmt = queryStmt.clone();
        tmpStmt.analyze(dummyRootAnalyzer);
        this.queryStmt = tmpStmt;
        ArrayList<Expr> resultExprs = getQueryStmt().getResultExprs();
        
        for (Expr expr : resultExprs) {
            if (expr.getType().isDecimalV2()) {
                ErrorReport.reportAnalysisException(ErrorCode.ERR_UNSUPPORTED_TYPE_IN_CTAS, expr.getType());
            }
        }
        if (columnNames != null && columnNames.size() != resultExprs.size()) {
            ErrorReport.reportAnalysisException(ErrorCode.ERR_COL_NUMBER_NOT_MATCH);
        }
    }
Code review comment: Since the recommended line length is 120, this line can be merged with the line above.

Code under review:
public void visit(BLangRecordLiteral recordLiteral) {
        List<BLangRecordLiteral.BLangRecordKeyValue> keyValuePairs = recordLiteral.keyValuePairs;
        keyValuePairs.forEach(kv -> {
            analyzeExpr(kv.valueExpr);
        });

        Set<Object> names = new TreeSet<>((l, r) -> l.equals(r) ? 0 : 1);
        for (BLangRecordLiteral.BLangRecordKeyValue recFieldDecl : keyValuePairs) {
            BLangExpression key = recFieldDecl.getKey();
            if (key.getKind() == NodeKind.SIMPLE_VARIABLE_REF) {
                BLangSimpleVarRef keyRef = (BLangSimpleVarRef) key;
                if (names.contains(keyRef.variableName.value)) {
                    String assigneeType = recordLiteral.parent.type.getKind().typeName();
                    this.dlog.error(key.pos, DiagnosticCode.DUPLICATE_KEY_IN_RECORD_LITERAL,
                            assigneeType, keyRef);
                }
                names.add(keyRef.variableName.value);
            } else if (key.getKind() == NodeKind.LITERAL) {
                BLangLiteral keyLiteral = (BLangLiteral) key;
                if (names.contains(keyLiteral.value)) {
                    String assigneeType = recordLiteral.parent.type.getKind().typeName();
                    this.dlog.error(key.pos, DiagnosticCode.DUPLICATE_KEY_IN_RECORD_LITERAL,
                            assigneeType, keyLiteral);
                }
            }
        }
    }

Line commented on: assigneeType, keyRef);

Revised code:
public void visit(BLangRecordLiteral recordLiteral) {
        List<BLangRecordLiteral.BLangRecordKeyValue> keyValuePairs = recordLiteral.keyValuePairs;
        keyValuePairs.forEach(kv -> {
            analyzeExpr(kv.valueExpr);
        });

        Set<Object> names = new TreeSet<>((l, r) -> l.equals(r) ? 0 : 1);
        for (BLangRecordLiteral.BLangRecordKeyValue recFieldDecl : keyValuePairs) {
            BLangExpression key = recFieldDecl.getKey();
            if (key.getKind() == NodeKind.SIMPLE_VARIABLE_REF) {
                BLangSimpleVarRef keyRef = (BLangSimpleVarRef) key;
                if (names.contains(keyRef.variableName.value)) {
                    String assigneeType = recordLiteral.parent.type.getKind().typeName();
                    this.dlog.error(key.pos, DiagnosticCode.DUPLICATE_KEY_IN_RECORD_LITERAL, assigneeType, keyRef);
                }
                names.add(keyRef.variableName.value);
            } else if (key.getKind() == NodeKind.LITERAL) {
                BLangLiteral keyLiteral = (BLangLiteral) key;
                if (names.contains(keyLiteral.value)) {
                    String assigneeType = recordLiteral.parent.type.getKind().typeName();
                    this.dlog.error(key.pos, DiagnosticCode.DUPLICATE_KEY_IN_RECORD_LITERAL, assigneeType, keyLiteral);
                }
                names.add(keyLiteral.value);
            }
        }
    }
Code review comment: I thought that when the ContextManager is not empty, the stateContext will definitely not be empty. According to ProxyContext to obtain the internal logic of stateContext, judgment should be added.

Code under review:
public List<MetricFamilySamples> collect() {
        if (!MetricsUtil.isClassExisted(PROXY_CLASS)) {
            return Collections.emptyList();
        }
        Optional<GaugeMetricFamily> proxyInfo = FACTORY.createGaugeMetricFamily(MetricIds.PROXY_INFO);
        if (null == ProxyContext.getInstance().getContextManager() || !proxyInfo.isPresent()) {
            return Collections.emptyList();
        }
        Optional<StateContext> stateContext = ProxyContext.getInstance().getStateContext();
        List<MetricFamilySamples> result = new LinkedList<>();
        proxyInfo.get().addMetric(Collections.singletonList(PROXY_STATE), PROXY_STATE_MAP.get(stateContext.get().getCurrentState()));
        result.add(proxyInfo.get());
        return result;
    }

Line commented on: if (null == ProxyContext.getInstance().getContextManager() || !proxyInfo.isPresent()) {

Revised code:
public List<MetricFamilySamples> collect() {
        if (!MetricsUtil.isClassExisted(PROXY_CLASS) || null == ProxyContext.getInstance().getContextManager()) {
            return Collections.emptyList();
        }
        Optional<GaugeMetricFamily> proxyInfo = FACTORY.createGaugeMetricFamily(MetricIds.PROXY_INFO);
        Optional<StateContext> stateContext = ProxyContext.getInstance().getStateContext();
        if (!proxyInfo.isPresent() || !stateContext.isPresent()) {
            return Collections.emptyList();
        }
        List<MetricFamilySamples> result = new LinkedList<>();
        proxyInfo.get().addMetric(Collections.singletonList(PROXY_STATE), PROXY_STATE_MAP.get(stateContext.get().getCurrentState()));
        result.add(proxyInfo.get());
        return result;
    }
Code review comment: Add a method, e.g. getJobID to reuse these codes.

Code under review:
public void testStopJob() throws Exception {
        final MockExecutor mockExecutor = new MockExecutor();
        mockExecutor.isSync = false;

        String sessionId = mockExecutor.openSession("test-session");
        OutputStream outputStream = new ByteArrayOutputStream(256);
        try (CliClient client =
                new CliClient(
                        () -> TerminalUtils.createDumbTerminal(outputStream),
                        sessionId,
                        mockExecutor,
                        historyTempFile(),
                        null)) {
            client.executeInNonInteractiveMode(INSERT_INTO_STATEMENT);
            String dmlResult = outputStream.toString();

            Pattern pattern = Pattern.compile("[\\s\\S]*Job ID: (.*)[\\s\\S]*");
            Matcher matcher = pattern.matcher(dmlResult);
            assertThat(matcher.matches()).isTrue();
            String jobId = matcher.group(1);

            client.executeInNonInteractiveMode("STOP JOB '" + jobId + "'");
            String stopResult = outputStream.toString();
            assertThat(stopResult).contains(CliStrings.MESSAGE_STOP_JOB_STATEMENT);
        }
    }

Line commented on: String jobId = matcher.group(1);

Revised code:
public void testStopJob() throws Exception {
        final MockExecutor mockExecutor = new MockExecutor();
        mockExecutor.isSync = false;

        String sessionId = mockExecutor.openSession("test-session");
        OutputStream outputStream = new ByteArrayOutputStream(256);
        try (CliClient client =
                new CliClient(
                        () -> TerminalUtils.createDumbTerminal(outputStream),
                        sessionId,
                        mockExecutor,
                        historyTempFile(),
                        null)) {
            client.executeInNonInteractiveMode(INSERT_INTO_STATEMENT);
            String dmlResult = outputStream.toString();
            String jobId = extractJobId(dmlResult);
            client.executeInNonInteractiveMode("STOP JOB '" + jobId + "'");
            String stopResult = outputStream.toString();
            assertThat(stopResult).contains(CliStrings.MESSAGE_STOP_JOB_STATEMENT);
        }
    }
Code review comment: Ah, I missed it! Will fix now

Code under review:
public Charset convert(String value) {
        try {
            return Charset.forName(value);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

Line commented on: throw new IllegalArgumentException(e);

Revised code:
public Charset convert(String value) {
        try {
            return Charset.forName(value);
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to create Charset from: '" + value + "'", e);
        }
    }
Code review comment: Perhaps it's this file that should be deleted?

Code under review:
public void require_that_valid_tar_application_can_be_unpacked() throws IOException {
        File outFile = createTarFile();
        try (CompressedApplicationInputStream unpacked = streamFromTarGz(outFile)) {
            File outApp = unpacked.decompress();
            assertTestApp(outApp);
        }
    }

Line commented on: File outFile = createTarFile();

Revised code:
public void require_that_valid_tar_application_can_be_unpacked() throws IOException {
        File outFile = createTarFile();
        try (CompressedApplicationInputStream unpacked = streamFromTarGz(outFile)) {
            File outApp = unpacked.decompress();
            assertTestApp(outApp);
        }
    }
Code review comment: I'll probably replace the job error with a job status some time soon, and then this won't be an issue :)

Code under review:
public boolean isOutOfCapacity() {
        return jobError.filter(error -> error == DeploymentJobs.JobError.outOfCapacity).isPresent();
    }

Line commented on: return jobError.filter(error -> error == DeploymentJobs.JobError.outOfCapacity).isPresent();

Revised code:
public boolean isOutOfCapacity() {
        return jobError.filter(error -> error == DeploymentJobs.JobError.outOfCapacity).isPresent();
    }
Code review comment: Currently, the method of geting the mapping is compatible. Alias and index can be queried. Therefore, the mapping relationship is not maintained.

Code under review:
public List<String> listTableNames(SessionContext ctx, String dbName) {
        List<String> indexes = esRestClient.getIndexes().stream().distinct().collect(Collectors.toList());
        esRestClient.getAliases().entrySet().stream().filter(e -> indexes.contains(e.getKey()))
                .flatMap(e -> e.getValue().stream()).distinct().forEach(indexes::add);
        return indexes;
    }

Line commented on: esRestClient.getAliases().entrySet().stream().filter(e -> indexes.contains(e.getKey()))

Revised code:
public List<String> listTableNames(SessionContext ctx, String dbName) {
        return esRestClient.listTable();
    }
Code review comment: Can't we check for a flag instead? ENUM_MEMBER for example.

Code under review:
public void visit(BLangFiniteTypeNode finiteTypeNode, AnalyzerData data) {
        boolean foundUnaryExpr = false;
        boolean isErroredExprInFiniteType = false;
        NodeKind valueKind;
        BLangExpression value;

        for (int i = 0; i < finiteTypeNode.valueSpace.size(); i++) {
            value = finiteTypeNode.valueSpace.get(i);
            valueKind = value.getKind();

            if (valueKind == NodeKind.UNARY_EXPR) {
                foundUnaryExpr = true;
                BType resultType = typeChecker.checkExpr(value, data.env, symTable.noType, data.prevEnvs);
                if (resultType == symTable.semanticError) {
                    isErroredExprInFiniteType = true;
                }
                
                BLangNumericLiteral newNumericLiteral =
                        Types.constructNumericLiteralFromUnaryExpr((BLangUnaryExpr) value);
                finiteTypeNode.valueSpace.set(i, newNumericLiteral);
            } else if ((valueKind == NodeKind.LITERAL || valueKind == NodeKind.NUMERIC_LITERAL) &&
                    ((BLangLiteral) value).originalValue == null) {
                
                continue;
            } else {
                analyzeNode(value, data);
            }
        }

        
        BFiniteType finiteType = (BFiniteType) finiteTypeNode.getBType();
        if (foundUnaryExpr && finiteType != null) {
            if (isErroredExprInFiniteType) {
                finiteTypeNode.setBType(symTable.semanticError);
            } else {
                finiteType.setValueSpace(new LinkedHashSet<>(finiteTypeNode.valueSpace));
            }
        }
    }


Revised code:
public void visit(BLangFiniteTypeNode finiteTypeNode, AnalyzerData data) {
        boolean foundUnaryExpr = false;
        boolean isErroredExprInFiniteType = false;
        NodeKind valueKind;
        BLangExpression value;

        for (int i = 0; i < finiteTypeNode.valueSpace.size(); i++) {
            value = finiteTypeNode.valueSpace.get(i);
            valueKind = value.getKind();

            if (valueKind == NodeKind.UNARY_EXPR) {
                foundUnaryExpr = true;
                BType resultType = typeChecker.checkExpr(value, data.env, symTable.noType, data.prevEnvs);
                if (resultType == symTable.semanticError) {
                    isErroredExprInFiniteType = true;
                }
                
                BLangNumericLiteral newNumericLiteral =
                        Types.constructNumericLiteralFromUnaryExpr((BLangUnaryExpr) value);
                finiteTypeNode.valueSpace.set(i, newNumericLiteral);
            } else if ((valueKind == NodeKind.LITERAL || valueKind == NodeKind.NUMERIC_LITERAL) &&
                    ((BLangLiteral) value).originalValue == null) {
                
                continue;
            } else {
                analyzeNode(value, data);
            }
        }

        if (foundUnaryExpr && isErroredExprInFiniteType) {
            finiteTypeNode.setBType(symTable.semanticError);
        }
    }
Code review comment: Or you could just use a if statement, and then you would not be using any metaspace or incurring a runtime cost.

Code under review:
public Object getReference(Bean<?> bean, Type beanType, CreationalContext<?> ctx) {
        Objects.requireNonNull(bean, () -> "Managed Bean [" + beanType + "] is null");
        Objects.requireNonNull(ctx, "CreationalContext is null");
        if (bean instanceof InjectableBean && ctx instanceof CreationalContextImpl) {
            return ArcContainerImpl.instance().beanInstanceHandle((InjectableBean) bean, (CreationalContextImpl) ctx).get();
        }
        throw new IllegalArgumentException(
                "Arguments must be instances of " + InjectableBean.class + " and " + CreationalContextImpl.class + ": \nbean: " + bean + "\nctx: " + ctx);
    }

Line commented on: Objects.requireNonNull(bean, () -> "Managed Bean [" + beanType + "] is null");

Revised code:
public Object getReference(Bean<?> bean, Type beanType, CreationalContext<?> ctx) {
        if (bean == null) {
            throw new NullPointerException("Managed Bean [" + beanType + "] is null");
        }
        Objects.requireNonNull(ctx, "CreationalContext is null");
        if (bean instanceof InjectableBean && ctx instanceof CreationalContextImpl) {
            return ArcContainerImpl.instance().beanInstanceHandle((InjectableBean) bean, (CreationalContextImpl) ctx).get();
        }
        throw new IllegalArgumentException(
                "Arguments must be instances of " + InjectableBean.class + " and " + CreationalContextImpl.class + ": \nbean: " + bean + "\nctx: " + ctx);
    }
Code review comment: I followed the same pattern used for other test cases in this specific test

Code under review:
public void testInferredArrayInitWithInGrpExpr() {
        Object[] args = {};
        Object returns = BRunUtil.invoke(compileResult, "testInferredArrayInitWithInGrpExpr", args);

        Assert.assertTrue(returns instanceof BArray);

        BArray arrayValue = (BArray) returns;
        Assert.assertEquals(arrayValue.size(), 3);
        Assert.assertEquals(arrayValue.getInt(0), 1);
        Assert.assertEquals(arrayValue.getInt(1), 2);
        Assert.assertEquals(arrayValue.getBString(2).getValue(), "a");
    }

Line commented on: Assert.assertEquals(arrayValue.getBString(2).getValue(), "a");

Revised code:
public void testInferredArrayInitWithInGrpExpr() {
        BRunUtil.invoke(compileResult, "testInferredArrayInitWithInGrpExpr");
    }
Code review comment: "Result". But this message is in itself quite fishy. Could we make the error conditions here more crisp?

Code under review:
static boolean warmup(Linguistics linguistics) {
        Query query = new Query("search/?yql=select%20*%20from%20sources%20where%20title%20contains%20'xyz';");
        Result result = insertQuery(query, new ParserEnvironment().setLinguistics(linguistics));
        if (result != null) {
            log.warning("Something fishy. Reult = " + result.toString());
            return false;
        }
        if ( ! "select * from sources where title contains \"xyz\";".equals(query.yqlRepresentation())) {
            log.warning("Unexpected yql: " + query.yqlRepresentation());
            return false;
        }
        return true;
    }

Line commented on: log.warning("Something fishy. Reult = " + result.toString());

Revised code:
static boolean warmup(Linguistics linguistics) {
        Query query = new Query("search/?yql=select%20*%20from%20sources%20where%20title%20contains%20'xyz';");
        Result result = insertQuery(query, new ParserEnvironment().setLinguistics(linguistics));
        if (result != null) {
            log.warning("Warmup code trigger an error. Error = " + result.toString());
            return false;
        }
        if ( ! "select * from sources where title contains \"xyz\";".equals(query.yqlRepresentation())) {
            log.warning("Warmup code generated unexpected yql: " + query.yqlRepresentation());
            return false;
        }
        return true;
    }
Code review comment: ```suggestion         return (int) nodes.stream().filter(node -> node.isWorking()).count(); ```

Code under review:
public int workingNodes() {
        return (int) nodes.stream().filter(node -> node.isWorking() == Boolean.TRUE).count();
    }

Line commented on: return (int) nodes.stream().filter(node -> node.isWorking() == Boolean.TRUE).count();

Revised code:
public int workingNodes() {
        return (int) nodes.stream().filter(node -> node.isWorking() == Boolean.TRUE).count();
    }
Code review comment: @michalvavrik Sure, the question is, is this extra check done inside Permission related to the authorization ?

Code under review:
public boolean implies(Permission permission) {
        if (permission instanceof WorkdayPermission) {

            WorkdayPermission that = (WorkdayPermission) permission;
            
            if (that.getName().equals("worker") && that.getActions().contains("adult")) {

                
                final WorkdayEvaluator workdayEvaluator = Arc.container().instance(WorkdayEvaluator.class).get();
                return workdayEvaluator.isWorkday(that.day);
            }
        }
        return false;
    }

Line commented on: if (that.getName().equals("worker") && that.getActions().contains("adult")) {

Revised code:
public boolean implies(Permission permission) {
        if (permission instanceof WorkdayPermission) {

            WorkdayPermission that = (WorkdayPermission) permission;
            
            if (that.getName().equals("worker") && that.getActions().contains("adult")) {

                
                final WorkdayEvaluator workdayEvaluator = Arc.container().instance(WorkdayEvaluator.class).get();
                return workdayEvaluator.isWorkday(that.day);
            }
        }
        return false;
    }
Code review comment: Yes, that's a good point. However, it is currently used by production code and a lot of testing code paths. I would move this issue out of the scope of this PR. WDYT?

Code under review:
public ExecutionAttemptID() {
		this(new ExecutionVertexID(), 0);
	}

Line commented on: this(new ExecutionVertexID(), 0);

Revised code:
public ExecutionAttemptID() {
		this(new ExecutionVertexID(new JobVertexID(), 0), 0);
	}
Code review comment: Yeah I wasn't sure how this architecture was intended to work.  I feel like we should have a consistent way to set up the configuration but we do not yet.  So again I opted to preserve the existing behavior as much as possible.

Code under review:
public void stop() {
        if (oldSystemProps != null) {
            for (Map.Entry<String, String> e : oldSystemProps.entrySet()) {
                if (e.getValue() == null) {
                    System.clearProperty(e.getKey());
                } else {
                    System.setProperty(e.getKey(), e.getValue());
                }

            }
        }
        oldSystemProps = null;
        for (QuarkusTestResourceLifecycleManager testResource : testResources) {
            try {
                testResource.stop();
            } catch (Exception e) {
                throw new RuntimeException("Unable to stop Quarkus test resource " + testResource, e);
            }
        }
        ConfigProviderResolver cpr = ConfigProviderResolver.instance();
        try {
            cpr.releaseConfig(cpr.getConfig());
        } catch (IllegalStateException ignored) {
        }
    }

Line commented on: cpr.releaseConfig(cpr.getConfig());

Revised code:
public void stop() {
        if (oldSystemProps != null) {
            for (Map.Entry<String, String> e : oldSystemProps.entrySet()) {
                if (e.getValue() == null) {
                    System.clearProperty(e.getKey());
                } else {
                    System.setProperty(e.getKey(), e.getValue());
                }

            }
        }
        oldSystemProps = null;
        for (QuarkusTestResourceLifecycleManager testResource : testResources) {
            try {
                testResource.stop();
            } catch (Exception e) {
                throw new RuntimeException("Unable to stop Quarkus test resource " + testResource, e);
            }
        }
        ConfigProviderResolver cpr = ConfigProviderResolver.instance();
        try {
            cpr.releaseConfig(cpr.getConfig());
        } catch (IllegalStateException ignored) {
        }
    }
Code review comment: Just curious, was there a case when it actually was a `String`? Which option was that?

Code under review:
public String[] getOptionValues(String name) {
        final Object o = options.get(name);
        return o == null ? null : o instanceof String ? new String[] { o.toString() } : (String[]) o;
    }

Line commented on: return o == null ? null : o instanceof String ? new String[] { o.toString() } : (String[]) o;

Revised code:
public String[] getOptionValues(String name) {
        final Object o = options.get(name);
        return o == null ? null : o instanceof String ? new String[] { o.toString() } : (String[]) o;
    }
Code review comment: Please use `Entry` instead of `Map.Entry`

Code under review:
public void init(final ShardingSphereMetaData metaData, final SQLStatement sqlStatement) {
        resource = metaData.getResource();
        dataSourcePropsMap = new LinkedHashMap<>(metaData.getResource().getDataSources().size(), 1);
        for (Map.Entry<String, DataSource> entry : metaData.getResource().getDataSources().entrySet()) {
            dataSourcePropsMap.put(entry.getKey(), DataSourcePropertiesCreator.create(entry.getValue()));
        }
        dataSourceNames = dataSourcePropsMap.keySet().iterator();
    }

Line commented on: for (Map.Entry<String, DataSource> entry : metaData.getResource().getDataSources().entrySet()) {

Revised code:
public void init(final ShardingSphereMetaData metaData, final SQLStatement sqlStatement) {
        resource = metaData.getResource();
        dataSourcePropsMap = new LinkedHashMap<>(metaData.getResource().getDataSources().size(), 1);
        for (Entry<String, DataSource> entry : metaData.getResource().getDataSources().entrySet()) {
            dataSourcePropsMap.put(entry.getKey(), DataSourcePropertiesCreator.create(entry.getValue()));
        }
        dataSourceNames = dataSourcePropsMap.keySet().iterator();
    }
Code review comment: It's required, I have analyzed [here](https://github.com/apache/flink/pull/19993#discussion_r901261999).   > For old code, the unit-test gets stuck in the second dataFuture.get(). After the change, the unit-test worked fine.

Code under review:
public void testCanBeClosed() throws Exception {
        long checkpointId = 1L;
        ChannelStateWriteRequestDispatcher processor =
                new ChannelStateWriteRequestDispatcherImpl(
                        "dummy task",
                        0,
                        getStreamFactoryFactory(),
                        new ChannelStateSerializerImpl());
        try (ChannelStateWriteRequestExecutorImpl worker =
                new ChannelStateWriteRequestExecutorImpl(TASK_NAME, processor)) {
            worker.start();
            worker.submit(
                    new CheckpointStartRequest(
                            checkpointId,
                            new ChannelStateWriter.ChannelStateWriteResult(),
                            CheckpointStorageLocationReference.getDefault()));
            worker.submit(
                    ChannelStateWriteRequest.write(
                            checkpointId,
                            new ResultSubpartitionInfo(0, 0),
                            new CompletableFuture<>()));
            worker.submit(
                    ChannelStateWriteRequest.write(
                            checkpointId,
                            new ResultSubpartitionInfo(0, 0),
                            new CompletableFuture<>()));
        }
    }

Line commented on: new CompletableFuture<>()));

Revised code:
public void testCanBeClosed() throws Exception {
        long checkpointId = 1L;
        ChannelStateWriteRequestDispatcher processor =
                new ChannelStateWriteRequestDispatcherImpl(
                        "dummy task",
                        0,
                        getStreamFactoryFactory(),
                        new ChannelStateSerializerImpl());
        try (ChannelStateWriteRequestExecutorImpl worker =
                new ChannelStateWriteRequestExecutorImpl(TASK_NAME, processor)) {
            worker.start();
            worker.submit(
                    new CheckpointStartRequest(
                            checkpointId,
                            new ChannelStateWriter.ChannelStateWriteResult(),
                            CheckpointStorageLocationReference.getDefault()));
            worker.submit(
                    ChannelStateWriteRequest.write(
                            checkpointId,
                            new ResultSubpartitionInfo(0, 0),
                            new CompletableFuture<>()));
            worker.submit(
                    ChannelStateWriteRequest.write(
                            checkpointId,
                            new ResultSubpartitionInfo(0, 0),
                            new CompletableFuture<>()));
        }
    }
Code review comment: loadAzureVmMetaData is part of init and not meant to call multiple times , why we used AtomicReference here ?

Code under review:
private void loadAzureVmMetaData() {
        AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();

        if (metadataSnapshot != null) {
            this.populateAzureVmMetaData(metadataSnapshot);
            return;
        }

        URI targetEndpoint = null;
        try {
            targetEndpoint = new URI(AZURE_VM_METADATA);
        } catch (URISyntaxException ex) {
            logger.info("Unable to parse azure vm metadata url");
            return;
        }
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Metadata", "true");
        HttpHeaders httpHeaders = new HttpHeaders(headers);
        HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
            httpHeaders);
        Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
        httpResponseMono
            .flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
                AzureVMMetadata.class)).doOnSuccess(metadata -> {
                azureVmMetaDataSingleton.compareAndSet(null, metadata);
                this.populateAzureVmMetaData(metadata);
            }).onErrorResume(throwable -> {
                logger.info("Client is not on azure vm");
                logger.debug("Unable to get azure vm metadata", throwable);
                return Mono.empty();
            }).subscribe();
    }

Line commented on: AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();

Revised code:
private void loadAzureVmMetaData() {
        AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();

        if (metadataSnapshot != null) {
            this.populateAzureVmMetaData(metadataSnapshot);
            return;
        }

        URI targetEndpoint = null;
        try {
            targetEndpoint = new URI(AZURE_VM_METADATA);
        } catch (URISyntaxException ex) {
            logger.info("Unable to parse azure vm metadata url");
            return;
        }
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Metadata", "true");
        HttpHeaders httpHeaders = new HttpHeaders(headers);
        HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(),
            httpHeaders);
        Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest);
        httpResponseMono
            .flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson,
                AzureVMMetadata.class)).doOnSuccess(metadata -> {
                azureVmMetaDataSingleton.compareAndSet(null, metadata);
                this.populateAzureVmMetaData(metadata);
            }).onErrorResume(throwable -> {
                logger.info("Client is not on azure vm");
                logger.debug("Unable to get azure vm metadata", throwable);
                return Mono.empty();
            }).subscribe();
    }
Code review comment: Lets rename exprs to indexExprs for readability

Code under review:
private void assignValueToArrayMapAccessExpr(BValue rValue, ArrayMapAccessExpr lExpr) {
        ArrayMapAccessExpr accessExpr = lExpr;
        if (!(accessExpr.getType() == BTypes.typeMap)) {
            BArray arrayVal = (BArray) accessExpr.getRExpr().execute(this);

            Expression[] exprs = accessExpr.getIndexExprs();
            if (exprs.length > 1) {
                arrayVal = retrieveArray(arrayVal, exprs);
            }

            BInteger indexVal = (BInteger) exprs[0].execute(this);
            arrayVal.add(indexVal.intValue(), rValue);

        } else {
            BMap<BString, BValue> mapVal = (BMap<BString, BValue>) accessExpr.getRExpr().execute(this);
            BString indexVal = (BString) accessExpr.getIndexExprs()[0].execute(this);
            mapVal.put(indexVal, rValue);
            
            
        }
    }

Line commented on: Expression[] exprs = accessExpr.getIndexExprs();

Revised code:
private void assignValueToArrayMapAccessExpr(BValue rValue, ArrayMapAccessExpr lExpr) {
        ArrayMapAccessExpr accessExpr = lExpr;
        if (!(accessExpr.getType() == BTypes.typeMap)) {
            BArray arrayVal = (BArray) accessExpr.getRExpr().execute(this);

            Expression[] indexExprs = accessExpr.getIndexExprs();
            if (indexExprs.length > 1) {
                arrayVal = retrieveArray(arrayVal, indexExprs);
            }

            BInteger indexVal = (BInteger) indexExprs[0].execute(this);
            arrayVal.add(indexVal.intValue(), rValue);

        } else {
            BMap<BString, BValue> mapVal = (BMap<BString, BValue>) accessExpr.getRExpr().execute(this);
            BString indexVal = (BString) accessExpr.getIndexExprs()[0].execute(this);
            mapVal.put(indexVal, rValue);
            
            
        }
    }
Code review comment: That sounds good. Maybe add a comment on the bug or here with a comment on what are the limitations.  Previously we had a conversation about not receiving progress updates as an indicator of sdk harness failure. We could consider that as an option.

Code under review:
public void unregisterWorkerClient(FnApiControlClient controlClient) {
      
      WorkCountingSdkWorkerHarness worker = workerMap.remove(controlClient);

      if (worker != null) {
        worker.closed.set(true);
        workers.remove(worker);
      }
      LOG.info("Unregistered Control client {}", worker != null ? worker.getWorkerId() : null);

      
      
      
      sdkHarnessesAreHealthy.set(false);
      LOG.info("SDK harness {} became unhealthy", worker != null ? worker.getWorkerId() : null);
    }

Line commented on: sdkHarnessesAreHealthy.set(false);

Revised code:
public void unregisterWorkerClient(FnApiControlClient controlClient) {
      
      WorkCountingSdkWorkerHarness worker = workerMap.remove(controlClient);

      if (worker != null) {
        worker.closed.set(true);
        workers.remove(worker);
      }
      LOG.info("Unregistered Control client {}", worker != null ? worker.getWorkerId() : null);

      
      
      
      sdkHarnessesAreHealthy.set(false);
      LOG.info("SDK harness {} became unhealthy", worker != null ? worker.getWorkerId() : null);
    }
Code review comment: +1 changed it to emit results in processElement as well. Could not measure a noticeable difference in my test though.

Code under review:
public void finishBundle() {
      try {
        
        
        remoteBundle.close();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      KV<String, OutputT> result;
      while ((result = outputQueue.poll()) != null) {
        outputManager.output(outputMap.get(result.getKey()), (WindowedValue) result.getValue());
      }
    }


Revised code:
public void finishBundle() {
      try {
        
        
        remoteBundle.close();
        emitResults();
      } catch (Exception e) {
        throw new RuntimeException("Failed to finish remote bundle", e);
      }
    }
Code review comment: Can't we return here? Or we have to unnecessarily check the tag in L3701 and return?

Code under review:
private void addAsRecordTypeDefinition(BType type, Location pos) {
        if (type.tag == TypeTags.UNION) {
            for (BType memberType : ((BUnionType) type).getMemberTypes()) {
                addAsRecordTypeDefinition(memberType, pos);
            }
        }
        if (type.tag != TypeTags.RECORD) {
            return;
        }
        BRecordType recordType = (BRecordType) type;
        if (isRecordTypeDefExist(recordType.tsymbol, env)) {
            return;
        }
        BLangRecordTypeNode recordTypeNode = new BLangRecordTypeNode();
        recordTypeNode.pos = pos;
        recordTypeNode.type = recordType;
        List<BLangSimpleVariable> typeDefFields = new ArrayList<>();
        for (BField field : recordType.fields.values()) {
            typeDefFields.add(ASTBuilderUtil.createVariable(field.pos, field.name.value, field.type, null,
                    field.symbol));
        }
        recordTypeNode.fields = typeDefFields;
        recordTypeNode.symbol = recordType.tsymbol;
        recordTypeNode.isAnonymous = true;
        recordTypeNode.isLocal = true;
        recordTypeNode.type.tsymbol.scope = new Scope(recordTypeNode.type.tsymbol);
        recordTypeNode.initFunction =
                rewrite(TypeDefBuilderHelper.createInitFunctionForRecordType(recordTypeNode, env, names, symTable),
                        env);
        TypeDefBuilderHelper.addTypeDefinition(recordType, recordType.tsymbol, recordTypeNode, env);
    }

Line commented on: BRecordType recordType = (BRecordType) type;

Revised code:
private void addAsRecordTypeDefinition(BType type, Location pos) {
        if (type.tag == TypeTags.UNION) {
            for (BType memberType : ((BUnionType) type).getMemberTypes()) {
                addAsRecordTypeDefinition(memberType, pos);
            }
            return;
        }
        if (type.tag != TypeTags.RECORD) {
            return;
        }
        BRecordType recordType = (BRecordType) type;
        if (isRecordTypeDefExist(recordType.tsymbol, env)) {
            return;
        }
        BLangRecordTypeNode recordTypeNode = new BLangRecordTypeNode();
        recordTypeNode.pos = pos;
        recordTypeNode.type = recordType;
        List<BLangSimpleVariable> typeDefFields = new ArrayList<>();
        for (BField field : recordType.fields.values()) {
            typeDefFields.add(ASTBuilderUtil.createVariable(field.pos, field.name.value, field.type, null,
                    field.symbol));
        }
        recordTypeNode.fields = typeDefFields;
        recordTypeNode.symbol = recordType.tsymbol;
        recordTypeNode.isAnonymous = true;
        recordTypeNode.isLocal = true;
        recordTypeNode.type.tsymbol.scope = new Scope(recordTypeNode.type.tsymbol);
        recordTypeNode.initFunction =
                rewrite(TypeDefBuilderHelper.createInitFunctionForRecordType(recordTypeNode, env, names, symTable),
                        env);
        TypeDefBuilderHelper.addTypeDefinition(recordType, recordType.tsymbol, recordTypeNode, env);
    }