muttakin2301/ccr2000 huggingface dataset:
Code review comment: In old version,  when execute ```replayBatchRemoveTransaction```, txnId could be removed when txnId locates in head of deque. So in V2, how to ensure the consistency between latestTxnIdForShort/latestTxnIdForLong and finalStatusTransactionStateDequeShort/finalStatusTransactionStateDequeLong. Is there the case that latestTxnIdForShort not in current finalStatusTransactionStateDequeShort? How about add a check here?

Code under review:
public void replayBatchRemoveTransaction(BatchRemoveTransactionsOperationV2 operation) {
        writeLock();
        try {
            int numOfClearedTransaction = 0;
            if (operation.getLatestTxnIdForShort() != -1) {
                while (!finalStatusTransactionStateDequeShort.isEmpty()) {
                    TransactionState transactionState = finalStatusTransactionStateDequeShort.pop();
                    clearTransactionState(transactionState.getTransactionId());
                    numOfClearedTransaction++;
                    if (operation.getLatestTxnIdForShort() == transactionState.getTransactionId()) {
                        break;
                    }
                }
            }

            if (operation.getLatestTxnIdForLong() != -1) {
                while (!finalStatusTransactionStateDequeLong.isEmpty()) {
                    TransactionState transactionState = finalStatusTransactionStateDequeLong.pop();
                    clearTransactionState(transactionState.getTransactionId());
                    numOfClearedTransaction++;
                    if (operation.getLatestTxnIdForLong() == transactionState.getTransactionId()) {
                        break;
                    }
                }
            }
            Preconditions.checkState(numOfClearedTransaction == operation.getNumOfClearedTransaction());
        } finally {
            writeUnlock();
        }
    }

Line commented on: TransactionState transactionState = finalStatusTransactionStateDequeShort.pop();

Revised code:
public void replayBatchRemoveTransaction(BatchRemoveTransactionsOperationV2 operation) {
        writeLock();
        try {
            if (operation.getLatestTxnIdForShort() != -1) {
                while (!finalStatusTransactionStateDequeShort.isEmpty()) {
                    TransactionState transactionState = finalStatusTransactionStateDequeShort.pop();
                    clearTransactionState(transactionState.getTransactionId());
                    if (operation.getLatestTxnIdForShort() == transactionState.getTransactionId()) {
                        break;
                    }
                }
            }

            if (operation.getLatestTxnIdForLong() != -1) {
                while (!finalStatusTransactionStateDequeLong.isEmpty()) {
                    TransactionState transactionState = finalStatusTransactionStateDequeLong.pop();
                    clearTransactionState(transactionState.getTransactionId());
                    if (operation.getLatestTxnIdForLong() == transactionState.getTransactionId()) {
                        break;
                    }
                }
            }
        } finally {
            writeUnlock();
        }
    }
Code review comment: Can you please elaborate on this logic , why we needed it first place, and how it will fix our caching issue moving from UUID to incremental counter

Code under review:
private String generateQueryParameter(@NonNull String subject, int counter) {
        
        return subject.replaceAll("[^a-zA-Z\\d]", "_") + counter;
    }

Line commented on: return subject.replaceAll("[^a-zA-Z\\d]", "_") + counter;

Revised code:
private String generateQueryParameter(@NonNull String subject, int counter) {
        
        return subject.replaceAll("[^a-zA-Z\\d]", "_") + counter;
    }
Code review comment: If it is null it returns nil.

Code under review:
public void execute(Context context) {
        @SuppressWarnings(ArtemisConstants.UNCHECKED)
        BMap<String, BValue> messageObj = (BMap<String, BValue>) context.getRefArgument(0);
        ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE);

        String key = context.getStringArgument(0);
        Object property = message.getObjectProperty(key);
        if (property != null) {
            context.setReturnValues(ArtemisUtils.getBValueFromObj(property, context));
        }
    }

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

Revised code:
public void execute(Context context) {
        @SuppressWarnings(ArtemisConstants.UNCHECKED)
        BMap<String, BValue> messageObj = (BMap<String, BValue>) context.getRefArgument(0);
        ClientMessage message = (ClientMessage) messageObj.getNativeData(ArtemisConstants.ARTEMIS_MESSAGE);

        String key = context.getStringArgument(0);
        Object property = message.getObjectProperty(key);
        if (property != null) {
            context.setReturnValues(ArtemisUtils.getBValueFromObj(property, context));
        } else {
            context.setReturnValues();
        }
    }
Code review comment: please make sure args is in the same order.

Code under review:
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
        int type = columnDef.getColumnMeta() >> 8;
        int length = columnDef.getColumnMeta() & 0xff;
        
        if ((type & 0x30) != 0x30) {
            length += ((type & 0x30) ^ 0x30) << 4;
            type |= 0x30;
        }
        switch (MySQLColumnType.valueOf(type)) {
            case MYSQL_TYPE_ENUM:
                return readEnumValue(length, payload);
            case MYSQL_TYPE_SET:
                return payload.getByteBuf().readByte();
            case MYSQL_TYPE_STRING:
                return payload.readStringFix(readActualLength(payload, length));
            default:
                throw new UnsupportedOperationException("");
        }
    }

Line commented on: return payload.readStringFix(readActualLength(payload, length));

Revised code:
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
        int type = columnDef.getColumnMeta() >> 8;
        int length = columnDef.getColumnMeta() & 0xff;
        
        if ((type & 0x30) != 0x30) {
            length += ((type & 0x30) ^ 0x30) << 4;
            type |= 0x30;
        }
        switch (MySQLColumnType.valueOf(type)) {
            case MYSQL_TYPE_ENUM:
                return readEnumValue(length, payload);
            case MYSQL_TYPE_SET:
                return payload.getByteBuf().readByte();
            case MYSQL_TYPE_STRING:
                return payload.readStringFix(readActualLength(length, payload));
            default:
                throw new UnsupportedOperationException("");
        }
    }
Code review comment: I use that pattern in multiple places and had no issue as soon as... you do not touch the RESAssured shared config while running.

Code under review:
public void testWithConcurrentCalls() {
        List<String> results = new CopyOnWriteArrayList<>();
        int count = 100;
        barrier.setMaxConcurrency(count);
        for (int i = 0; i < count; i++) {
            int c = i;
            new Thread(() -> {
                ResponseBody<?> body = RestAssured.given().pathParam("val", c).contentType(MediaType.APPLICATION_JSON)
                        .get("/test/{val}").thenReturn().body();
                String value = body.toString();
                results.add(value);
            }).start();
        }
        await().until(() -> results.size() == count);
        Set<String> asSet = new HashSet<>(results);
        Assertions.assertEquals(asSet.size(), count);
    }

Line commented on: ResponseBody<?> body = RestAssured.given().pathParam("val", c).contentType(MediaType.APPLICATION_JSON)

Revised code:
public void testWithConcurrentCalls() {
        List<String> results = new CopyOnWriteArrayList<>();
        int count = 100;
        barrier.setMaxConcurrency(count);
        for (int i = 0; i < count; i++) {
            int c = i;
            new Thread(() -> {
                ResponseBody<?> body = RestAssured.given().pathParam("val", c).contentType(MediaType.APPLICATION_JSON)
                        .get("/test/{val}").thenReturn().body();
                String value = body.toString();
                results.add(value);
            }).start();
        }
        await().until(() -> results.size() == count);
        Set<String> asSet = new HashSet<>(results);
        Assertions.assertEquals(asSet.size(), count);
    }
Code review comment: `SyntaxKind.PARENTHESIZED_ARG_LIST` does this handle a specific scenario? If yes, can we add a test case for that?

Code under review:
public List<SyntaxKind> getSyntaxKinds() {
        return List.of(SyntaxKind.BOOLEAN_LITERAL, SyntaxKind.NUMERIC_LITERAL, SyntaxKind.STRING_LITERAL,
                SyntaxKind.BINARY_EXPRESSION, SyntaxKind.START_ACTION, SyntaxKind.BRACED_EXPRESSION,
                SyntaxKind.FUNCTION_CALL, SyntaxKind.QUALIFIED_NAME_REFERENCE, SyntaxKind.INDEXED_EXPRESSION,
                SyntaxKind.FIELD_ACCESS, SyntaxKind.METHOD_CALL, SyntaxKind.CHECK_EXPRESSION, 
                SyntaxKind.MAPPING_CONSTRUCTOR, SyntaxKind.TYPEOF_EXPRESSION, SyntaxKind.UNARY_EXPRESSION,
                SyntaxKind.TYPE_TEST_EXPRESSION, SyntaxKind.TRAP_EXPRESSION, SyntaxKind.LIST_CONSTRUCTOR, 
                SyntaxKind.TYPE_CAST_EXPRESSION, SyntaxKind.TABLE_CONSTRUCTOR, SyntaxKind.LET_EXPRESSION,
                SyntaxKind.IMPLICIT_NEW_EXPRESSION, SyntaxKind.EXPLICIT_NEW_EXPRESSION, 
                SyntaxKind.PARENTHESIZED_ARG_LIST, SyntaxKind.ERROR_CONSTRUCTOR, SyntaxKind.OBJECT_CONSTRUCTOR);
    }

Line commented on: SyntaxKind.PARENTHESIZED_ARG_LIST, SyntaxKind.ERROR_CONSTRUCTOR, SyntaxKind.OBJECT_CONSTRUCTOR);

Revised code:
public List<SyntaxKind> getSyntaxKinds() {
        return List.of(SyntaxKind.BOOLEAN_LITERAL, SyntaxKind.NUMERIC_LITERAL, SyntaxKind.STRING_LITERAL,
                SyntaxKind.BINARY_EXPRESSION, SyntaxKind.BRACED_EXPRESSION, SyntaxKind.XML_TEMPLATE_EXPRESSION,
                SyntaxKind.FUNCTION_CALL, SyntaxKind.QUALIFIED_NAME_REFERENCE, SyntaxKind.INDEXED_EXPRESSION,
                SyntaxKind.FIELD_ACCESS, SyntaxKind.METHOD_CALL, SyntaxKind.CHECK_EXPRESSION, SyntaxKind.LET_EXPRESSION,
                SyntaxKind.MAPPING_CONSTRUCTOR, SyntaxKind.TYPEOF_EXPRESSION, SyntaxKind.UNARY_EXPRESSION,
                SyntaxKind.TYPE_TEST_EXPRESSION, SyntaxKind.TRAP_EXPRESSION, SyntaxKind.LIST_CONSTRUCTOR, 
                SyntaxKind.TYPE_CAST_EXPRESSION, SyntaxKind.TABLE_CONSTRUCTOR, SyntaxKind.IMPLICIT_NEW_EXPRESSION, 
                SyntaxKind.EXPLICIT_NEW_EXPRESSION, SyntaxKind.ERROR_CONSTRUCTOR, SyntaxKind.QUERY_EXPRESSION);
    }
Code review comment: The type is still `[int...]` right? The shape is `[int, int]`. Updates that change the shape can be done as long as they don't violate the inherent type (given the value is not immutable).  IMO, `[int...]` is the same as `int[]`.

Code under review:
private void checkFixedLength(long length) {
        if (arrayType != null && arrayType.getTag() == TypeTags.TUPLE_TAG) {
            throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
                    RuntimeErrors.CANNOT_CHANGE_TUPLE_SIZE);
        }
        if (((BArrayType) this.arrayType).getState() == ArrayState.CLOSED_SEALED) {
            throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
                    RuntimeErrors.ILLEGAL_ARRAY_SIZE, length);
        }
    }

Line commented on: if (arrayType != null && arrayType.getTag() == TypeTags.TUPLE_TAG) {

Revised code:
private void checkFixedLength(long length) {
        if (arrayType != null && arrayType.getTag() == TypeTags.TUPLE_TAG) {
            throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
                    RuntimeErrors.CANNOT_CHANGE_TUPLE_SIZE);
        }
        if (((BArrayType) this.arrayType).getState() == ArrayState.CLOSED_SEALED) {
            throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
                    RuntimeErrors.ILLEGAL_ARRAY_SIZE, length);
        }
    }
Code review comment: We might need to be more strict here, but in the sample tests I performed, this seemed to work just fine

Code under review:
public boolean canConvert(Class type) {
        return List.class.isAssignableFrom(type);
    }

Line commented on: return List.class.isAssignableFrom(type);

Revised code:
public boolean canConvert(Class type) {
        return (type != null) && SUPPORTED_CLASS_NAMES.contains(type.getName());
    }
Code review comment: should add en UT the unused_output_column_name isn't empty

Code under review:
public void testFilterComplexPredicate() throws Exception {
        connectContext.getSessionVariable().enableTrimOnlyFilteredColumnsInScanStage();
        String sql = "select\n" +
                "            ref_0.d_dow as c1 from tpcds_100g_date_dim as ref_0 \n" +
                "            where ref_0.d_day_name = ref_0.d_day_name limit 137;\n";
        String plan = getThriftPlan(sql);
        Assert.assertTrue(plan.contains("unused_output_column_name:[]"));
    }

Line commented on: Assert.assertTrue(plan.contains("unused_output_column_name:[]"));

Revised code:
public void testFilterComplexPredicate() throws Exception {
        connectContext.getSessionVariable().enableTrimOnlyFilteredColumnsInScanStage();
        String sql = "select\n" +
                "            ref_0.d_dow as c1 from tpcds_100g_date_dim as ref_0 \n" +
                "            where ref_0.d_day_name = ref_0.d_day_name limit 137;\n";
        String plan = getThriftPlan(sql);
        Assert.assertTrue(plan.contains("unused_output_column_name:[]"));
    }
Code review comment: Well, it's the best way to avoid failing tests!

Code under review:
public void testUser() {
        User user = new User("gsmet");
        usersEntityManager.persist(user);

        User savedUser = usersEntityManager.find(User.class, user.getId());
        assertEquals(user.getName(), savedUser.getName());

        OtherUserInSubPackage otherUserInSubPackage = new OtherUserInSubPackage("other-user");
        usersEntityManager.persist(otherUserInSubPackage);

        OtherUserInSubPackage savedOtherUserInSubPackage = usersEntityManager.find(OtherUserInSubPackage.class,
                otherUserInSubPackage.getId());
        assertEquals(otherUserInSubPackage.getName(), savedOtherUserInSubPackage.getName());
    }

Line commented on: assertEquals(otherUserInSubPackage.getName(), savedOtherUserInSubPackage.getName());

Revised code:
public void testUser() {
        User user = new User("gsmet");
        usersEntityManager.persist(user);

        User savedUser = usersEntityManager.find(User.class, user.getId());
        assertEquals(user.getName(), savedUser.getName());

        OtherUserInSubPackage otherUserInSubPackage = new OtherUserInSubPackage("other-user");
        usersEntityManager.persist(otherUserInSubPackage);

        OtherUserInSubPackage savedOtherUserInSubPackage = usersEntityManager.find(OtherUserInSubPackage.class,
                otherUserInSubPackage.getId());
        assertEquals(otherUserInSubPackage.getName(), savedOtherUserInSubPackage.getName());
    }
Code review comment: according to the [scheduler interface draft](https://docs.google.com/document/d/1fstkML72YBO1tGD_dmG2rwvd9bklhRVauh4FSsDDwXU/edit#), the `RestartBackoffTimeStrategy` is responsible for this decision.  ```The delay is computed by a RestartBackoffTimeStrategy that is also responsible for deciding whether a restart should be performed at all (e.g., if the failure cause is SuppressRestartsException).```

Code under review:
public FailureHandlingResult getFailureHandlingResult(ExecutionVertexID failedTask, Throwable cause) {
		if (ThrowableClassifier.getThrowableType(cause) == ThrowableType.NonRecoverableError) {
			return FailureHandlingResult.unrecoverable(new JobException("The failure is not recoverable", cause));
		}

		restartBackoffTimeStrategy.notifyFailure(cause);
		if (restartBackoffTimeStrategy.canRestart()) {
			return FailureHandlingResult.restartable(
				failoverStrategy.getTasksNeedingRestart(failedTask, cause),
				restartBackoffTimeStrategy.getBackoffTime());
		} else {
			return FailureHandlingResult.unrecoverable(
				new JobException("Failed task restarting is suppressed by " + restartBackoffTimeStrategy, cause));
		}
	}

Line commented on: if (ThrowableClassifier.getThrowableType(cause) == ThrowableType.NonRecoverableError) {

Revised code:
public FailureHandlingResult getFailureHandlingResult(ExecutionVertexID failedTask, Throwable cause) {
		if (isUnrecoverableError(cause)) {
			return FailureHandlingResult.unrecoverable(new JobException("The failure is not recoverable", cause));
		}

		restartBackoffTimeStrategy.notifyFailure(cause);
		if (restartBackoffTimeStrategy.canRestart()) {
			return FailureHandlingResult.restartable(
				failoverStrategy.getTasksNeedingRestart(failedTask, cause),
				restartBackoffTimeStrategy.getBackoffTime());
		} else {
			return FailureHandlingResult.unrecoverable(
				new JobException("Failed task restarting is suppressed by " + restartBackoffTimeStrategy, cause));
		}
	}
Code review comment: Should move validation to the maxAutoLockRenewDuration setter.

Code under review:
public ServiceBusReceiverAsyncClient buildAsyncClient() {
            final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
                queueName);
            final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
                SubQueue.NONE);

            validateAndThrow(prefetchCount);
            validateAndThrow(maxAutoLockRenewDuration);

            final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
            final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
                sessionId, isRollingSessionReceiver(), maxConcurrentSessions, maxAutoLockRenewDuration);

            final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
                connectionProcessor, tracerProvider, messageSerializer, receiverOptions);

            return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
                entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
                tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose,
                maxAutoLockRenewDuration, sessionManager);
        }

Line commented on: validateAndThrow(maxAutoLockRenewDuration);

Revised code:
public ServiceBusReceiverAsyncClient buildAsyncClient() {
            final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
                queueName);
            final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
                SubQueue.NONE);

            final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);

            if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) {
                maxAutoLockRenewDuration = Duration.ZERO;
            }

            final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
                sessionId, isRollingSessionReceiver(), maxConcurrentSessions, maxAutoLockRenewDuration);

            final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
                connectionProcessor, tracerProvider, messageSerializer, receiverOptions);

            return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
                entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
                tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
        }
Code review comment: This is only used in dev so we are alright.  Also it's the exact same logic.

Code under review:
public DevClasspathStaticHandler(Set<String> generatedResources, DevClasspathStaticHandlerOptions options) {
        this.generatedResources = generatedResources;
        this.compressedMediaTypes = options.getCompressMediaTypes();
        this.currentClassLoader = Thread.currentThread().getContextClassLoader();
        this.enableCompression = options.isEnableCompression();
        this.indexPage = options.getIndexPage();
        this.defaultEncoding = options.getDefaultEncoding();
    }

Line commented on: this.compressedMediaTypes = options.getCompressMediaTypes();

Revised code:
public DevClasspathStaticHandler(Set<String> generatedResources, DevClasspathStaticHandlerOptions options) {
        this.generatedResources = generatedResources;
        this.compressedMediaTypes = options.getCompressMediaTypes();
        this.currentClassLoader = Thread.currentThread().getContextClassLoader();
        this.enableCompression = options.isEnableCompression();
        this.indexPage = options.getIndexPage();
        this.defaultEncoding = options.getDefaultEncoding();
    }
Code review comment: `/` means `or`. `and/or` is `and or or`, which can be simplified to `or`. (`or` is not `xor` in English)

Code under review:
private static Set<String> findEnabledReportersInConfiguration(Configuration configuration, String includedReportersString) {
		Set<String> includedReporters = reporterListPattern.splitAsStream(includedReportersString)
			.filter(r -> !r.isEmpty()) 
			.collect(Collectors.toSet());

		
		Set<String> namedOrderedReporters = new TreeSet<>(String::compareTo);

		
		for (String key : configuration.keySet()) {
			if (key.startsWith(ConfigConstants.METRICS_REPORTER_PREFIX)) {
				Matcher matcher = reporterClassPattern.matcher(key);
				if (matcher.matches()) {
					String reporterName = matcher.group(1);
					if (includedReporters.isEmpty() || includedReporters.contains(reporterName)) {
						if (namedOrderedReporters.contains(reporterName)) {
							LOG.warn("Duplicate class configuration detected for reporter {}.", reporterName);
						} else {
							namedOrderedReporters.add(reporterName);
						}
					} else {
						LOG.info("Excluding reporter {}, not configured in reporter list ({}).", reporterName, includedReportersString);
					}
				}
			}
		}
		return namedOrderedReporters;
	}

Line commented on: LOG.info("Excluding reporter {}, not configured in reporter list ({}).", reporterName, includedReportersString);

Revised code:
private static Set<String> findEnabledReportersInConfiguration(Configuration configuration, String includedReportersString) {
		Set<String> includedReporters = reporterListPattern.splitAsStream(includedReportersString)
			.filter(r -> !r.isEmpty()) 
			.collect(Collectors.toSet());

		
		Set<String> namedOrderedReporters = new TreeSet<>(String::compareTo);

		
		for (String key : configuration.keySet()) {
			if (key.startsWith(ConfigConstants.METRICS_REPORTER_PREFIX)) {
				Matcher matcher = reporterClassPattern.matcher(key);
				if (matcher.matches()) {
					String reporterName = matcher.group(1);
					if (includedReporters.isEmpty() || includedReporters.contains(reporterName)) {
						if (namedOrderedReporters.contains(reporterName)) {
							LOG.warn("Duplicate class configuration detected for reporter {}.", reporterName);
						} else {
							namedOrderedReporters.add(reporterName);
						}
					} else {
						LOG.info("Excluding reporter {}, not configured in reporter list ({}).", reporterName, includedReportersString);
					}
				}
			}
		}
		return namedOrderedReporters;
	}
Code review comment: Yes, good catch, I've forgotten about it.

Code under review:
public void broadcastEvent(AbstractEvent event, boolean isPriorityEvent) throws IOException {
        
        
        
        try (BufferConsumer eventBufferConsumer =
                EventSerializer.toBufferConsumer(event, isPriorityEvent)) {
            AbstractEvent deserializedEvent =
                    EventSerializer.fromBuffer(
                            eventBufferConsumer.build(), getClass().getClassLoader());
            output.add(deserializedEvent);
        }
    }

Line commented on: eventBufferConsumer.build(), getClass().getClassLoader());

Revised code:
public void broadcastEvent(AbstractEvent event, boolean isPriorityEvent) throws IOException {
        
        
        
        try (BufferConsumer eventBufferConsumer =
                EventSerializer.toBufferConsumer(event, isPriorityEvent)) {
            Buffer buffer = eventBufferConsumer.build();
            try {
                AbstractEvent deserializedEvent =
                        EventSerializer.fromBuffer(buffer, getClass().getClassLoader());
                output.add(deserializedEvent);
            } finally {
                buffer.recycleBuffer();
            }
        }
    }
Code review comment: Can we assert the content of the file?

Code under review:
public static void main(String[] args) throws IOException {
            List<URL> resources = Collections
                    .list(UberJarMain.class.getClassLoader().getResources("META-INF/cxf/cxf.fixml"));
            System.out.println("RESOURCES: " + resources.size());
        }

Line commented on: System.out.println("RESOURCES: " + resources.size());

Revised code:
public static void main(String[] args) throws IOException {
            List<URL> resources = Collections
                    .list(UberJarMain.class.getClassLoader().getResources("META-INF/cxf/cxf.fixml"));
            System.out.println("RESOURCES: " + resources.size());
        }
Code review comment: The only usage I found you can safely treat a character as a human, and not an well aged java core developer... `ParseException p = new ParseException("Could not parse '" + Text.truncate(expression, 50) + "'");`

Code under review:
public boolean annotate(StringFieldValue text) {
        if (text.getSpanTree(SpanTrees.LINGUISTICS) != null) return true;  

        Tokenizer tokenizer = factory.getTokenizer();
        String input = (text.getString().length() <= config.getMaxTokenizeLength())
                ? text.getString()
                : Text.safeSubstring(text.getString(), config.getMaxTokenizeLength());
        Iterable<Token> tokens = tokenizer.tokenize(input, config.getLanguage(), config.getStemMode(),
                                                    config.getRemoveAccents());
        TermOccurrences termOccurrences = new TermOccurrences(config.getMaxTermOccurrences());
        SpanTree tree = new SpanTree(SpanTrees.LINGUISTICS);
        for (Token token : tokens)
            addAnnotationSpan(text.getString(), tree.spanList(), token, config.getStemMode(), termOccurrences);

        if (tree.numAnnotations() == 0) return false;
        text.setSpanTree(tree);
        return true;
    }

Line commented on: : Text.safeSubstring(text.getString(), config.getMaxTokenizeLength());

Revised code:
public boolean annotate(StringFieldValue text) {
        if (text.getSpanTree(SpanTrees.LINGUISTICS) != null) return true;  

        Tokenizer tokenizer = factory.getTokenizer();
        String input = (text.getString().length() <= config.getMaxTokenizeLength())
                ? text.getString()
                : Text.substringByCodepoints(text.getString(), 0, config.getMaxTokenizeLength());
        Iterable<Token> tokens = tokenizer.tokenize(input, config.getLanguage(), config.getStemMode(),
                                                    config.getRemoveAccents());
        TermOccurrences termOccurrences = new TermOccurrences(config.getMaxTermOccurrences());
        SpanTree tree = new SpanTree(SpanTrees.LINGUISTICS);
        for (Token token : tokens)
            addAnnotationSpan(text.getString(), tree.spanList(), token, config.getStemMode(), termOccurrences);

        if (tree.numAnnotations() == 0) return false;
        text.setSpanTree(tree);
        return true;
    }
Code review comment: Yes, good point, will remove that

Code under review:
public byte[] toJson() {
        try {
            Slime slime = new Slime();
            toSlime(slime.setObject());
            return SlimeUtils.toJsonBytes(slime);
        }
        catch (IOException e) {
            throw new RuntimeException("Serialization of " + this + " to json failed", e);
        }
    }

Line commented on: throw new RuntimeException("Serialization of " + this + " to json failed", e);

Revised code:
public byte[] toJson() {
        try {
            Slime slime = new Slime();
            toSlime(slime.setObject());
            return SlimeUtils.toJsonBytes(slime);
        }
        catch (IOException e) {
            throw new RuntimeException("Serialization of session data to json failed", e);
        }
    }
Code review comment: Thus iterating chars for comparison is rarely right: you must use the codepoint static methods on `Character` to ask if a codepoint is on 1 or 2 chars. Now, it's possible that the 2-char codepoints have both chars greater than the ascii range, and you're only escaping (5) ascii values so your code may work, but we should check.

Code under review:
private String doEscape(CharSequence value, int index, StringBuilder builder) {
        int length = value.length();
        while (++index < length) {
            char c = value.charAt(index);
            String replacement = replacements.get(c);
            if (replacement != null) {
                builder.append(replacement);
            } else {
                builder.append(c);
            }
        }
        return builder.toString();
    }

Line commented on: char c = value.charAt(index);

Revised code:
private String doEscape(CharSequence value, int index, StringBuilder builder) {
        int length = value.length();
        while (++index < length) {
            char c = value.charAt(index);
            String replacement = replacements.get(c);
            if (replacement != null) {
                builder.append(replacement);
            } else {
                builder.append(c);
            }
        }
        return builder.toString();
    }
Code review comment: Put null checking in method at the first place.

Code under review:
public ScoringParameter(String name, GeoPoint value) {
        this(name, toLonLatStrings(value));
    }

Line commented on: this(name, toLonLatStrings(value));

Revised code:
public ScoringParameter(String name, GeoPoint value) {
        this(name, toLonLatStrings(value));
    }
Code review comment: Please check for status code 200 as well

Code under review:
public void createResources() throws CosmosException {
        final String containerName = _configuration.getCollectionId();
        final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
        final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
        try {
            LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
            final CosmosAsyncContainer container = database.getContainer(containerName);
            final Optional<CosmosContainerResponse> response = getContainerProperties(container);
            if (response.isPresent()) {
                LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
                applyDesiredContainerPolicies(container, response.get().getProperties());
                return;
            }

            createContainer(database, containerName, collectionAttributes);
        } catch (CosmosException e) {
            LOGGER.error("Exception while configuring collection {}", containerName, e);
            throw e;
        }
    }

Line commented on: if (response.isPresent()) {

Revised code:
public void createResources() throws CosmosException {
        final String containerName = _configuration.getCollectionId();
        final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
        final CollectionAttributes collectionAttributes = _entityConfiguration.collectionAttributes();
        try {
            LOGGER.info("Checking for container {} in the database {}", containerName, database.getId());
            final CosmosAsyncContainer container = database.getContainer(containerName);
            final Optional<CosmosContainerResponse> response = getContainerProperties(container);
            if (response.isPresent()) {
                LOGGER.info("Container {} already exists in the database {}", containerName, database.getId());
                applyDesiredContainerPolicies(container, response.get().getProperties());
                return;
            }

            createContainer(database, containerName, collectionAttributes);
        } catch (CosmosException e) {
            LOGGER.error("Exception while configuring collection {}", containerName, e);
            throw e;
        }
    }
Code review comment: There can be instances where the parent is not visited. The ExternalTreeList Node implementation is one such instance. (The apply method does not visit the transformer). Hense, the parent will not be visited. IMO, to handle such scenarios a loop is required since we can't guarantee that the ContextTypeResolver always resolves a context for a given node

Code under review:
public Optional<TypeSymbol> getContextType() {

        if (this.isContextTypeFound) {
            return this.contextType;
        }

        this.isContextTypeFound = true;
        if (this.getNodeAtCursor() == null) {
            this.contextType = Optional.empty();
            return this.contextType;
        }

        NonTerminalNode node = getNodeAtCursor();
        do {
            ContextTypeResolver contextTypeResolver = new ContextTypeResolver(this);
            this.contextType = node.apply(contextTypeResolver);
            if (this.contextType == null) {
                this.contextType = Optional.empty();
            }
            node = node.parent();
        } while (this.contextType.isEmpty() && node.parent() != null);

        return this.contextType;
    }

Line commented on: do {

Revised code:
public Optional<TypeSymbol> getContextType() {

        if (this.isContextTypeFound) {
            return Optional.ofNullable(this.contextType);
        }

        this.isContextTypeFound = true;
        if (this.getNodeAtCursor() == null) {
            this.contextType = null;
            return Optional.ofNullable(contextType);
        }

        NonTerminalNode node = getNodeAtCursor();
        do {
            ContextTypeResolver contextTypeResolver = new ContextTypeResolver(this);
            Optional<TypeSymbol> typeSymbol = node.apply(contextTypeResolver);
            if (typeSymbol == null || typeSymbol.isEmpty()) {
                this.contextType = null;
            } else {
                this.contextType = typeSymbol.get();
            }
            node = node.parent();
        } while (this.contextType == null && node != null);

        return Optional.ofNullable(this.contextType);
    }
Code review comment: Addressed with https://github.com/ballerina-platform/ballerina-lang/pull/31829/commits/111094729f69d3296a3c694581dabfdebc283d93

Code under review:
public void visit(BIRBasicBlock birBasicBlock) {
        
        addCpAndWriteString(birBasicBlock.id.value);
        
        
        buf.writeInt(birBasicBlock.instructions.size() + 1);

        birBasicBlock.instructions.forEach(instruction -> {
            
            writePosition(instruction.pos);
            writeScopes(instruction);
            buf.writeByte(instruction.kind.getValue());
            
            instruction.accept(this);
        });

        BIRTerminator terminator = birBasicBlock.terminator;
        if (terminator == null) {
            throw new BLangCompilerException("Basic block without a terminator : " + birBasicBlock.id);
        }

        
        writePosition(terminator.pos);
        if (terminator.kind != InstructionKind.RETURN) {
            writeScopes(terminator);
        }
        buf.writeByte(terminator.kind.getValue());
        
        terminator.accept(this);
    }

Line commented on: writeScopes(terminator);

Revised code:
public void visit(BIRBasicBlock birBasicBlock) {
        
        addCpAndWriteString(birBasicBlock.id.value);
        
        
        buf.writeInt(birBasicBlock.instructions.size() + 1);

        birBasicBlock.instructions.forEach(instruction -> {
            
            writePosition(instruction.pos);
            writeScopes(instruction);
            buf.writeByte(instruction.kind.getValue());
            
            instruction.accept(this);
        });

        BIRTerminator terminator = birBasicBlock.terminator;
        if (terminator == null) {
            throw new BLangCompilerException("Basic block without a terminator : " + birBasicBlock.id);
        }

        
        writePosition(terminator.pos);
        writeScope(terminator);
        buf.writeByte(terminator.kind.getValue());
        
        terminator.accept(this);
    }
Code review comment: can you actually remove a public method? I suspect that you need to make it a no-op that logs a warning

Code under review:
public WriteWithResults withWriteResults() {
      return new WriteWithResults(
          getBigtableConfig(),
          getBigtableWriteOptions(),
          getServiceFactory(),
          getBadRecordErrorHandler(),
          getBadRecordRouter());
    }

Line commented on: getBadRecordErrorHandler(),

Revised code:
public WriteWithResults withWriteResults() {
      return new WriteWithResults(
          getBigtableConfig(),
          getBigtableWriteOptions(),
          getServiceFactory(),
          getBadRecordErrorHandler(),
          getBadRecordRouter());
    }
Code review comment: since `%s` can become large, should we also do some line break and indention here

Code under review:
public String asSerializableString(String table) {
            switch (type) {
                case SLIDE:
                    return String.format(
                            "HOP((%s), DESCRIPTOR(%s), %s, %s)",
                            table,
                            timeAttribute.asSerializableString(),
                            slide.asSerializableString(),
                            size.asSerializableString());
                case SESSION:
                    throw new TableException("Session windows are not SQL serializable yet.");
                case TUMBLE:
                    return String.format(
                            "TUMBLE((%s), DESCRIPTOR(%s), %s)",
                            table,
                            timeAttribute.asSerializableString(),
                            size.asSerializableString());
                default:
                    throw new IllegalStateException("Unknown window type: " + type);
            }
        }

Line commented on: table,

Revised code:
public String asSerializableString(String table) {
            switch (type) {
                case SLIDE:
                    return String.format(
                            "HOP((%s\n), DESCRIPTOR(%s), %s, %s)",
                            OperationUtils.indent(table),
                            timeAttribute.asSerializableString(),
                            slide.asSerializableString(),
                            size.asSerializableString());
                case SESSION:
                    throw new TableException("Session windows are not SQL serializable yet.");
                case TUMBLE:
                    return String.format(
                            "TUMBLE((%s\n), DESCRIPTOR(%s), %s)",
                            OperationUtils.indent(table),
                            timeAttribute.asSerializableString(),
                            size.asSerializableString());
                default:
                    throw new IllegalStateException("Unknown window type: " + type);
            }
        }
Code review comment: What's the meaning of finstId?

Code under review:
public Future<PFetchDataResult> fetchData(PFetchDataRequest request, RpcCallback<PFetchDataResult> callback) {
            String fid = DebugUtil.printId(request.finstId);
            String queryId = resultSinkInstanceToQueryId.get(fid);
            if (queryId == null) {
                LOG.warn("no queryId found for finstId {}", fid);
                PFetchDataResult result = new PFetchDataResult();
                result.status = statusPB(TStatusCode.INTERNAL_ERROR, "no queryId found for finstId " + fid);
                return CompletableFuture.completedFuture(result);
            }
            final QueryProgress progress = queryProgresses.get(queryId);
            if (progress == null) {
                LOG.warn("no progress found for finstId {} queryId", fid, queryId);
                PFetchDataResult result = new PFetchDataResult();
                result.status = statusPB(TStatusCode.INTERNAL_ERROR,
                        "no progress found for finstId " + request.finstId + " queryId " + queryId);
                return CompletableFuture.completedFuture(result);
            }
            return progress.getFetchDataResult();
        }

Line commented on: LOG.warn("no progress found for finstId {} queryId", fid, queryId);

Revised code:
public Future<PFetchDataResult> fetchData(PFetchDataRequest request, RpcCallback<PFetchDataResult> callback) {
            String fid = DebugUtil.printId(request.finstId);
            String queryId = resultSinkInstanceToQueryId.get(fid);
            if (queryId == null) {
                LOG.warn("no queryId found for finstId {}", fid);
                PFetchDataResult result = new PFetchDataResult();
                result.status = statusPB(TStatusCode.INTERNAL_ERROR, "no queryId found for finstId " + fid);
                return CompletableFuture.completedFuture(result);
            }
            final QueryProgress progress = queryProgresses.get(queryId);
            if (progress == null) {
                LOG.warn("no progress found for finstId {} queryId", fid, queryId);
                PFetchDataResult result = new PFetchDataResult();
                result.status = statusPB(TStatusCode.INTERNAL_ERROR,
                        "no progress found for finstId " + request.finstId + " queryId " + queryId);
                return CompletableFuture.completedFuture(result);
            }
            return progress.getFetchDataResult();
        }
Code review comment: That would make JdbcIOTest stuck again. This piece of code already exists in JdbcIOTest.beforeClass. What happens is that the timeout setting set once in JdbcIOTest.beforeClass somehow gets reset if JdbcIOExceptionHandlingParameterizedTest is running, as both uses same embed derby server.

Code under review:
public static void beforeClass() {
    
    
    System.setProperty("derby.locks.waitTimeout", "2");
    System.setProperty("derby.stream.error.file", "build/derby.log");
  }

Line commented on: System.setProperty("derby.stream.error.file", "build/derby.log");

Revised code:
public static void beforeClass() {
    
    
    System.setProperty("derby.locks.waitTimeout", "2");
    System.setProperty("derby.stream.error.file", "build/derby.log");
  }
Code review comment: This is OK for creating table/partition. But for alter operation, there is a daemon scheduler to add/remove replicas on be to match the replication_num property. This check cannot cover the alter case.

Code under review:
private List<Long> chosenBackendIdBySeq(int replicationNum) throws DdlException {
        List<Long> chosenBackendIds =
                systemInfoService.seqChooseBackendIds(replicationNum, true, true);
        if (!CollectionUtils.isEmpty(chosenBackendIds)) {
            return chosenBackendIds;
        } else if (replicationNum > 1) {
            throw new DdlException(String.format("Unable to find %d alive nodes with different IPs to create %d replicas",
                    replicationNum, replicationNum));
        } else {
            throw new DdlException("No alive nodes");
        }
    }

Line commented on: if (!CollectionUtils.isEmpty(chosenBackendIds)) {

Revised code:
private List<Long> chosenBackendIdBySeq(int replicationNum) throws DdlException {
        List<Long> chosenBackendIds =
                systemInfoService.seqChooseBackendIds(replicationNum, true, true);
        if (!CollectionUtils.isEmpty(chosenBackendIds)) {
            return chosenBackendIds;
        } else if (replicationNum > 1) {
            throw new DdlException(String.format("Unable to find %d alive nodes on different hosts to create %d replicas",
                    replicationNum, replicationNum));
        } else {
            throw new DdlException("No alive nodes");
        }
    }
Code review comment: So we removed the dependency on semconv package in this PR https://github.com/Azure/azure-sdk-for-java/pull/18940 since it was moved out of the core oTel lib and was to be managed independently (possible breaking changes). I missed doing these updates to the exporter lib in the last PR so covering them now.

Code under review:
private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
        String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
        if (httpMethod != null) {
            applyHttpClientSpan(attributes, remoteDependencyData);
            return;
        }
        String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
        if (rpcSystem != null) {
            applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
            return;
        }
        String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
        if (dbSystem != null) {
            applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
            return;
        }
        String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
        if (messagingSystem != null) {
            applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
            return;
        }
    }

Line commented on: String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));

Revised code:
private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
        String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
        if (httpMethod != null) {
            applyHttpClientSpan(attributes, remoteDependencyData);
            return;
        }
        String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
        if (rpcSystem != null) {
            applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
            return;
        }
        String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
        if (dbSystem != null) {
            applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
            return;
        }
        String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
        if (messagingSystem != null) {
            applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
            return;
        }
    }