muttakin2301/ccr2000 huggingface dataset:
Code review comment: Maybe it would be better to open a JIRA issue for supporting UPSERT (as a placeholder, simply stating that the semantics need to be defined first) and then link to that ticket from here rather than the one that causes us to disallow it? What do you think?

Code under review:
public void validateInsert(SqlInsert insert) {
        super.validateInsert(insert);

        
        if (insert.isUpsert()) {
            throw new ValidationException("UPSERT INTO statement is not supported");
        }
    }


Revised code:
public void validateInsert(SqlInsert insert) {
        
        
        

        
        if (insert.isUpsert()) {
            throw new ValidationException(
                    "UPSERT INTO statement is not supported. Please use INSERT INTO instead.");
        }
    }
Code review comment: I don't mind either. I like your substitution in principle but agree we shouldn't have substitutions when we can avoid them... my suggestion was more hypotethical about contributing a similar patch upstream: if the driver could store the `Version` initialized in a static block, we wouldn't need patching. But I wonder if there's a reason they went to such lenghts of lazily initializing it (?).  Regarding the `@Fold` annotation... it seems it has been moved in GraalVM into an internal module - but don't worry it's not important. In principle the Fold annotation allows (allowed?) a method computation to be replaced with a constant, whose value is defined by running that method once during build time.

Code under review:
void addNativeImageResources(BuildProducer<NativeImageResourceBuildItem> resources) {
        resources.produce(new NativeImageResourceBuildItem("mariadb.properties", "driver.properties"));
    }

Line commented on: resources.produce(new NativeImageResourceBuildItem("mariadb.properties", "driver.properties"));

Revised code:
void addNativeImageResources(BuildProducer<NativeImageResourceBuildItem> resources) {
        
        
        
        resources.produce(new NativeImageResourceBuildItem("mariadb.properties"));
    }
Code review comment: Ok, let's start with `CLASS`...

Code under review:
private List<BeanInfo> findMatching(TypeAndQualifiers typeAndQualifiers) {
        List<BeanInfo> resolved = new ArrayList<>();
        
        Collection<BeanInfo> potentialBeans = typeAndQualifiers.type.kind() == CLASS
                ? beanDeployment.getBeansByType(typeAndQualifiers.type)
                : beanDeployment.getBeans();
        for (BeanInfo b : potentialBeans) {
            if (Beans.matches(b, typeAndQualifiers)) {
                resolved.add(b);
            }
        }
        return resolved.isEmpty() ? Collections.emptyList() : resolved;
    }

Line commented on: Collection<BeanInfo> potentialBeans = typeAndQualifiers.type.kind() == CLASS

Revised code:
private List<BeanInfo> findMatching(TypeAndQualifiers typeAndQualifiers) {
        List<BeanInfo> resolved = new ArrayList<>();
        
        Collection<BeanInfo> potentialBeans = typeAndQualifiers.type.kind() == CLASS
                ? beanDeployment.getBeansByType(typeAndQualifiers.type)
                : beanDeployment.getBeans();
        for (BeanInfo b : potentialBeans) {
            if (Beans.matches(b, typeAndQualifiers)) {
                resolved.add(b);
            }
        }
        return resolved.isEmpty() ? Collections.emptyList() : resolved;
    }
Code review comment: I wonder if you shouldn't just rely exclusively on `agroalSupport.entries` and get rid of `support.getConfiguredNames()` altogether. `support.getConfiguredNames()` is sometimes returning non-agroal datasource names (which you're working around here), and I've noticed before (#37779) that it may not even return the name of all configured Agroal datasources:  https://github.com/quarkusio/quarkus/blob/5bbae6fc32ca65188b91d0f86db987fde727332f/extensions/datasource/runtime/src/main/java/io/quarkus/datasource/runtime/DataSourceRecorder.java#L21-L29

Code under review:
protected void init() {
        if (!dataSources.isResolvable()) {
            
            return;
        }
        DataSourceSupport support = Arc.container().instance(DataSourceSupport.class)
                .get();
        AgroalDataSourceSupport agroalSupport = Arc.container().instance(AgroalDataSourceSupport.class)
                .get();
        Set<String> names = support.getConfiguredNames();
        Set<String> excludedNames = support.getInactiveOrHealthCheckExcludedNames();
        for (String name : names) {
            if (excludedNames.contains(name) || !agroalSupport.entries.containsKey(name)) {
                continue;
            }
            DataSource ds = dataSources.get().getDataSource(name);
            if (ds != null) {
                checkedDataSources.put(name, ds);
            }
        }
    }

Line commented on: Set<String> names = support.getConfiguredNames();

Revised code:
protected void init() {
        if (!dataSources.isResolvable()) {
            
            return;
        }
        DataSourceSupport support = Arc.container().instance(DataSourceSupport.class)
                .get();
        AgroalDataSourceSupport agroalSupport = Arc.container().instance(AgroalDataSourceSupport.class)
                .get();
        Set<String> excludedNames = support.getInactiveOrHealthCheckExcludedNames();
        for (String name : agroalSupport.entries.keySet()) {
            if (excludedNames.contains(name)) {
                continue;
            }
            DataSource ds = dataSources.get().getDataSource(name);
            if (ds != null) {
                checkedDataSources.put(name, ds);
            }
        }
    }
Code review comment: @heyams I pushed this to show an option that avoids relying on the (confusing to me at least) `additionalProperties`  (here's the full commit I pushed: https://github.com/Azure/azure-sdk-for-java/pull/41106/commits/75f6fe2845fb0e22d7a73afdf1d3beedc3723f2c)

Code under review:
private static void validateSpan(TelemetryItem telemetryItem) throws IOException {
        assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency");
        assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY);
        assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java");
        assertThat(telemetryItem.getTags())
            .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel"));
        assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData");

        
        RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData());
        assertThat(actualData.getName()).isEqualTo("test");
        assertThat(actualData.getProperties())
            .containsExactly(entry("color", "red"), entry("name", "apple"));
    }

Line commented on: RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData());

Revised code:
private static void validateSpan(TelemetryItem telemetryItem) {
        assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency");
        assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY);
        assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service:java");
        assertThat(telemetryItem.getTags())
            .hasEntrySatisfying("ai.internal.sdkVersion", v -> assertThat(v).contains("otel"));
        assertThat(telemetryItem.getData().getBaseType()).isEqualTo("RemoteDependencyData");

        RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData());
        assertThat(actualData.getName()).isEqualTo("test");
        assertThat(actualData.getProperties()).containsExactly(entry("color", "red"), entry("name", "apple"));
    }
Code review comment: possible NPE if the volume of the svId not exist?

Code under review:
public String getStorageVolumeName(String svId) {
        try (LockCloseable lock = new LockCloseable(rwLock.readLock())) {
            return getStorageVolume(svId).getName();
        }
    }

Line commented on: return getStorageVolume(svId).getName();

Revised code:
public String getStorageVolumeName(String svId) {
        try (LockCloseable lock = new LockCloseable(rwLock.readLock())) {
            StorageVolume sv = getStorageVolume(svId);
            if (sv == null) {
                return "";
            }
            return getStorageVolume(svId).getName();
        }
    }
Code review comment: It would be safer to use `cacheMaxSize <= 0 || cacheExpireMs <= 0`.

Code under review:
public void open(FunctionContext context) {
        LOG.info("start open ...");
        Configuration config = prepareRuntimeConfiguration();
        CompletableFuture<AsyncConnection> asyncConnectionFuture = ConnectionFactory.createAsyncConnection(config);
        try {
            asyncConnection = asyncConnectionFuture.get();
            table = asyncConnection.getTable(TableName.valueOf(hTableName), (ExecutorService) Executors.directExecutor());

            this.cache = cacheMaxSize == -1 || cacheExpireMs == 0 ? null : CacheBuilder.newBuilder()
                .recordStats()
                .expireAfterWrite(cacheExpireMs, TimeUnit.MILLISECONDS)
                .maximumSize(cacheMaxSize)
                .build();
            if (cache != null && context != null) {
                context.getMetricGroup().gauge("lookupCacheHitRate", (Gauge<Double>) () -> cache.stats().hitRate());
            }
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Exception while creating connection to HBase.", e);
            throw new RuntimeException("Cannot create connection to HBase.", e);
        }
        this.serde = new HBaseSerde(hbaseTableSchema, nullStringLiteral);
        LOG.info("end open.");
    }

Line commented on: this.cache = cacheMaxSize == -1 || cacheExpireMs == 0 ? null : CacheBuilder.newBuilder()

Revised code:
public void open(FunctionContext context) {
        LOG.info("start open ...");
        final ExecutorService threadPool =
                Executors.newFixedThreadPool(
                        THREAD_POOL_SIZE,
                        new ExecutorThreadFactory(
                                "hbase-aysnc-lookup-worker", Threads.LOGGING_EXCEPTION_HANDLER));
        Configuration config = prepareRuntimeConfiguration();
        CompletableFuture<AsyncConnection> asyncConnectionFuture =
                ConnectionFactory.createAsyncConnection(config);
        try {
            asyncConnection = asyncConnectionFuture.get();
            table = asyncConnection.getTable(TableName.valueOf(hTableName), threadPool);

            this.cache =
                    cacheMaxSize <= 0 || cacheExpireMs <= 0
                            ? null
                            : CacheBuilder.newBuilder()
                                    .recordStats()
                                    .expireAfterWrite(cacheExpireMs, TimeUnit.MILLISECONDS)
                                    .maximumSize(cacheMaxSize)
                                    .build();
            if (cache != null && context != null) {
                context.getMetricGroup()
                        .gauge("lookupCacheHitRate", (Gauge<Double>) () -> cache.stats().hitRate());
            }
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Exception while creating connection to HBase.", e);
            throw new RuntimeException("Cannot create connection to HBase.", e);
        }
        this.serde = new HBaseSerde(hbaseTableSchema, nullStringLiteral);
        LOG.info("end open.");
    }
Code review comment: If no transformers are registered, this method should return the original set of annotations immediately.

Code under review:
public Set<AnnotationInstance> applyTransformers(Type type, AnnotationTarget target, Set<AnnotationInstance> qualifiers) {
        TransformationContextImpl transformationContext = new TransformationContextImpl(target, qualifiers,
                annotationStore);
        for (InjectionPointsTransformer transformer : transformers) {
            if (transformer.appliesTo(type)) {
                transformer.transform(transformationContext);
            }
        }
        return transformationContext.getQualifiers();
    }

Line commented on: transformer.transform(transformationContext);

Revised code:
public Set<AnnotationInstance> applyTransformers(Type type, AnnotationTarget target, Set<AnnotationInstance> qualifiers) {
        
        if (transformers.isEmpty()) {
            return qualifiers;
        }
        TransformationContextImpl transformationContext = new TransformationContextImpl(target, qualifiers,
                annotationStore);
        for (InjectionPointsTransformer transformer : transformers) {
            if (transformer.appliesTo(type)) {
                transformer.transform(transformationContext);
            }
        }
        return transformationContext.getQualifiers();
    }
Code review comment: Nothing else @menghaoranss. Will make that commit soon

Code under review:
public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
        Watch.Listener listener = Watch.listener(response -> {
            for (WatchEvent each : response.getEvents()) {
                ChangedType changedType = getEventChangedType(each);
                if (ChangedType.IGNORED != changedType) {
                    dataChangedEventListener.onChange(new DataChangedEvent(each.getKeyValue().getKey().toString(StandardCharsets.UTF_8)
                            , each.getKeyValue().getValue().toString(StandardCharsets.UTF_8), changedType));
                }
            }
        });
        client.getWatchClient().watch(ByteSequence.from(key, StandardCharsets.UTF_8), listener);
    }

Line commented on: , each.getKeyValue().getValue().toString(StandardCharsets.UTF_8), changedType));

Revised code:
public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
        Watch.Listener listener = Watch.listener(response -> {
            for (WatchEvent each : response.getEvents()) {
                ChangedType changedType = getEventChangedType(each);
                if (ChangedType.IGNORED != changedType) {
                    dataChangedEventListener.onChange(new DataChangedEvent(each.getKeyValue().getKey().toString(StandardCharsets.UTF_8),
                            each.getKeyValue().getValue().toString(StandardCharsets.UTF_8), changedType));
                }
            }
        });
        client.getWatchClient().watch(ByteSequence.from(key, StandardCharsets.UTF_8), listener);
    }
Code review comment: If a ballerina test fails it will anyway have the mentioned text in the program output. But, if it fails due to a compilation error, this fails to capture that. So, I'll add an else statement to capture unforeseen errors.

Code under review:
public static void assertForTestFailures(String programOutput, String errMessage) throws BallerinaTestException {
        if (programOutput.contains("error: there are test failures")) {
            throw new BallerinaTestException("Test failed due to " + errMessage + " in test framework");
        }
    }

Line commented on: if (programOutput.contains("error: there are test failures")) {

Revised code:
public static void assertForTestFailures(String programOutput, String errMessage) throws BallerinaTestException {
        if (programOutput.contains("error: there are test failures")) {
            throw new BallerinaTestException("Test failed due to " + errMessage + " in test framework");
        } else if (programOutput.contains("error: compilation contains errors")) {
            throw new BallerinaTestException("Test failed due to a compilation error with following output\n" +
                    programOutput);
        }
    }
Code review comment: Normally, Context, like the name describes, does not do actions

Code under review:
public Collection<Integer> transform(Transformation<?> transformation) {
            return streamGraphGenerator.transform(transformation);
        }

Line commented on: return streamGraphGenerator.transform(transformation);

Revised code:
public Collection<Integer> transform(Transformation<?> transformation) {
            return streamGraphGenerator.transform(transformation);
        }
Code review comment: Would it be possible to add test case for bw compatible code path?

Code under review:
public Params decode(InputStream inStream) throws IOException {
      String prefix = STRING_CODER.decode(inStream);
      String shardTemplate = STRING_CODER.decode(inStream);
      String suffix = STRING_CODER.decode(inStream);
      ResourceId baseFilename;
      if (inStream.available() > 0) {
        baseFilename = FileSystems.matchNewResource(prefix, BOOLEAN_CODER.decode(inStream));
      } else {
        
        baseFilename = FileBasedSink.convertToFileResourceIfPossible(prefix);
      }
      return new Params()
          .withBaseFilename(baseFilename)
          .withShardTemplate(shardTemplate)
          .withSuffix(suffix);
    }

Line commented on: baseFilename = FileBasedSink.convertToFileResourceIfPossible(prefix);

Revised code:
public Params decode(InputStream inStream) throws IOException {
      ResourceId prefix =
          FileBasedSink.convertToFileResourceIfPossible(STRING_CODER.decode(inStream));
      String shardTemplate = STRING_CODER.decode(inStream);
      String suffix = STRING_CODER.decode(inStream);
      return new Params()
          .withBaseFilename(prefix)
          .withShardTemplate(shardTemplate)
          .withSuffix(suffix);
    }
Code review comment: I think we can dlog here since rest param can only be of array type?

Code under review:
public void visit(BLangTupleVarRef varRefExpr) {
        List<BType> results = new ArrayList<>();
        for (int i = 0; i < varRefExpr.expressions.size(); i++) {
            ((BLangVariableReference) varRefExpr.expressions.get(i)).lhsVar = true;
            results.add(checkExpr(varRefExpr.expressions.get(i), env, symTable.noType));
        }
        BTupleType actualType = new BTupleType(results);
        if (varRefExpr.restParam != null) {
            BLangExpression restExpr = (BLangExpression) varRefExpr.restParam;
            ((BLangVariableReference) restExpr).lhsVar = true;
            BType checkedType = checkExpr(restExpr, env, symTable.noType);
            if (checkedType.tag == TypeTags.ARRAY) {
                actualType.restType = ((BArrayType) checkedType).eType;
            } else {
                actualType.restType = checkedType;
            }
        }
        resultType = types.checkType(varRefExpr, actualType, expType);
    }

Line commented on: actualType.restType = checkedType;

Revised code:
public void visit(BLangTupleVarRef varRefExpr) {
        List<BType> results = new ArrayList<>();
        for (int i = 0; i < varRefExpr.expressions.size(); i++) {
            ((BLangVariableReference) varRefExpr.expressions.get(i)).lhsVar = true;
            results.add(checkExpr(varRefExpr.expressions.get(i), env, symTable.noType));
        }
        BTupleType actualType = new BTupleType(results);
        if (varRefExpr.restParam != null) {
            BLangExpression restExpr = (BLangExpression) varRefExpr.restParam;
            ((BLangVariableReference) restExpr).lhsVar = true;
            BType checkedType = checkExpr(restExpr, env, symTable.noType);
            if (checkedType.tag != TypeTags.ARRAY) {
                dlog.error(varRefExpr.pos, DiagnosticCode.INVALID_TYPE_FOR_REST_DESCRIPTOR, checkedType);
                resultType = symTable.semanticError;
                return;
            }
            actualType.restType = ((BArrayType) checkedType).eType;
        }
        resultType = types.checkType(varRefExpr, actualType, expType);
    }
Code review comment: How is `update` different from `updateInternal`  From reading their comments, it seems they are different somehow, but the changelogger seems to be same.  Similar to other states.

Code under review:
public void updateInternal(List<V> valueToStore) throws Exception {
        changeLogger.stateUpdated(valueToStore, getCurrentNamespace());
        delegatedState.updateInternal(valueToStore);
    }

Line commented on: changeLogger.stateUpdated(valueToStore, getCurrentNamespace());

Revised code:
public void updateInternal(List<V> valueToStore) throws Exception {
        delegatedState.updateInternal(valueToStore);
        changeLogger.valueUpdatedInternal(valueToStore, getCurrentNamespace());
    }
Code review comment: Why is Vert.x mentioned here?

Code under review:
AdditionalBeanBuildItem createCDIEventConsumer() {
        
        return AdditionalBeanBuildItem.builder()
                .addBeanClass(KAFKA_EVENT_CONSUMER_CLASS_NAME)
                .setUnremovable().build();
    }


Revised code:
AdditionalBeanBuildItem createCDIEventConsumer() {
        return AdditionalBeanBuildItem.builder()
                .addBeanClass(KAFKA_EVENT_CONSUMER_CLASS_NAME)
                .setUnremovable().build();
    }
Code review comment: It says in the javadoc for ResourceId.java that a resource id represents a file-like resource, so AzfsResourceId does not support resource id's without a container.

Code under review:
public boolean isContainer() {
    return blob == null;
  }

Line commented on: return blob == null;

Revised code:
public boolean isContainer() {
    return blob == null;
  }
Code review comment: Is it possible to find a more specific exception type? RuntimeException is generally only viewed as abstract base class. Maybe IllegalStateException, or InvalidArgumentException (if we take that defaultSubscription only works for 1 subscription).

Code under review:
public Azure withDefaultSubscription() {
            if (profile.subscriptionId() == null) {
                List<Subscription> subscriptions = new ArrayList<>();
                this.subscriptions().list().forEach(subscription -> {
                    subscriptions.add(subscription);
                });
                if (subscriptions.size() == 0) {
                    throw logger.logExceptionAsError(
                        new RuntimeException("Please create a subscription before you start resource management. "
                            + "To learn more, see: https:
                } else if (subscriptions.size() > 1) {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("More than one subscription found in your tenant. "
                        + "Please specify which one below is desired for resource management.");
                    subscriptions.forEach(subscription -> {
                        stringBuilder.append("\n" + subscription.displayName() + " : " + subscription.subscriptionId());
                    });
                    throw logger.logExceptionAsError(new RuntimeException(stringBuilder.toString()));
                } else {
                    profile.withSubscriptionId(subscriptions.get(0).subscriptionId());
                }
            }
            return new Azure(httpPipeline, profile, this);
        }

Line commented on: new RuntimeException("Please create a subscription before you start resource management. "

Revised code:
public Azure withDefaultSubscription() {
            if (profile.subscriptionId() == null) {
                profile.withSubscriptionId(Utils.defaultSubscription(this.subscriptions().list()));
            }
            return new Azure(httpPipeline, profile, this);
        }
Code review comment: Consider adding factory function for `NodeEvent.forBucketSpace` to avoid overloading confusion

Code under review:
private static NodeEvent createNodeEvent(NodeInfo nodeInfo, String description, PerStateParams params) {
        if (params.bucketSpace.isPresent()) {
            return new NodeEvent(nodeInfo, params.bucketSpace.get(), description, NodeEvent.Type.CURRENT, params.currentTime);
        } else {
            return new NodeEvent(nodeInfo, description, NodeEvent.Type.CURRENT, params.currentTime);
        }
    }

Line commented on: return new NodeEvent(nodeInfo, params.bucketSpace.get(), description, NodeEvent.Type.CURRENT, params.currentTime);

Revised code:
private static NodeEvent createNodeEvent(NodeInfo nodeInfo, String description, PerStateParams params) {
        if (params.bucketSpace.isPresent()) {
            return NodeEvent.forBucketSpace(nodeInfo, params.bucketSpace.get(), description, NodeEvent.Type.CURRENT, params.currentTime);
        } else {
            return NodeEvent.forBaseline(nodeInfo, description, NodeEvent.Type.CURRENT, params.currentTime);
        }
    }
Code review comment: Was this required for all or just one of the tests?

Code under review:
static void beforeAll() throws InterruptedException {
        TimeUnit.SECONDS.sleep(180);
        StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
    }

Line commented on: TimeUnit.SECONDS.sleep(180);

Revised code:
static void beforeAll() throws InterruptedException {
        TimeUnit.SECONDS.sleep(180);
        StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
    }
Code review comment: Will need a design or documentation in the case if there is a row that does not match the schema. If you check pubsub json support, it supports a dead letter queue that sends rows to that queue if those rows does not match with the schema. You might reuse the same design.

Code under review:
public PCollection<Row> expand(PCollection<String> input) {
      return input
          .apply(
              ParDo.of(
                  new DoFn<String, Row>() {
                    @ProcessElement
                    public void processElement(ProcessContext context) {
                      context.output(jsonToRow(objectMapper, context.element()));
                    }
                  }))
          .setRowSchema(schema);
    }

Line commented on: public void processElement(ProcessContext context) {

Revised code:
public PCollection<Row> expand(PCollection<String> input) {
      return input
          .apply(
              "linesToRows",
              MapElements.into(TypeDescriptors.rows())
                  .via(s -> Row.withSchema(SCHEMA).addValue(s).build()))
          .setRowSchema(SCHEMA);
    }
Code review comment: Could we add requestId generator? There're much hard-coded code for now

Code under review:
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
        if (evt instanceof CreateSubscriptionEvent) {
            Builder builder = CDCRequest.newBuilder();
            builder.setCreateSubscription(buildCreateSubscriptionRequest());
            builder.setRequestId(UUID.randomUUID().toString());
            ctx.writeAndFlush(builder.build());
        }
    }

Line commented on: builder.setRequestId(UUID.randomUUID().toString());

Revised code:
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
        if (evt instanceof CreateSubscriptionEvent) {
            CDCRequest request = CDCRequest.newBuilder().setCreateSubscription(buildCreateSubscriptionRequest()).setRequestId(RequestIdUtil.generateRequestId()).build();
            ctx.writeAndFlush(request);
        }
    }
Code review comment: According to your Comment, fixed in new version.

Code under review:
public void run() throws InterruptedException {
        ServiceBusSenderClient senderClient = new ServiceBusClientBuilder()
            .connectionString(connectionString)
            .sender()
            .queueName(queueName)
            .buildClient();

        
        sendMessagesAsync(senderClient, 1);
        deadLetterByExceedingMaxDelivery(connectionString, queueName);

        
        sendMessagesAsync(senderClient, Integer.MAX_VALUE);
        this.receiveAndDeadletterMessagesAsync(connectionString, queueName);
        this.pickUpAndFixDeadletters(connectionString, queueName, senderClient);

        senderClient.close();
    }

Line commented on: sendMessagesAsync(senderClient, 1);

Revised code:
public void run() {
        
        
        
        
        
        
        
        
        
        final String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
        final String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");

        final ServiceBusClientBuilder builder = new ServiceBusClientBuilder().connectionString(connectionString);

        try (ServiceBusSenderClient sender = builder.sender().queueName(queueName).buildClient()) {
            
            sendMessages(sender, 1);
            deadLetterByExceedingMaxDelivery(builder, queueName).block();
            receiveAndCompleteDeadLetterQueueMessages(builder, queueName).block();

            
            sendMessages(sender, personList.size());
            receiveAndDeadletterMessages(builder, queueName).block();
            receiveAndFixDeadLetterQueueMessages(builder, queueName, sender).block();
        }
    }
Code review comment: The main part of the fix is `GeneratedClassGizmoAdaptor.isApplicationClass(name)` -> `GeneratedClassGizmoAdaptor.isApplicationClass(className)`!

Code under review:
public boolean test(String name) {
            int idx = name.lastIndexOf(SUFFIX);
            
            String className = name.substring(0, idx).replace("/", ".");
            if (className.contains(ValueResolverGenerator.NESTED_SEPARATOR)) {
                className = className.replace(ValueResolverGenerator.NESTED_SEPARATOR, "$");
            }
            
            className = additionalClassNameSanitizer.apply(className);
            return GeneratedClassGizmoAdaptor.isApplicationClass(className);
        }

Line commented on: return GeneratedClassGizmoAdaptor.isApplicationClass(className);

Revised code:
public boolean test(String name) {
            int idx = name.lastIndexOf(SUFFIX);
            
            String className = name.substring(0, idx).replace("/", ".");
            if (className.contains(ValueResolverGenerator.NESTED_SEPARATOR)) {
                className = className.replace(ValueResolverGenerator.NESTED_SEPARATOR, "$");
            }
            
            className = additionalClassNameSanitizer.apply(className);
            return GeneratedClassGizmoAdaptor.isApplicationClass(className);
        }
Code review comment: Shall we extract `matchExpr.type` and `errorMatchPattern.type` out to variables?

Code under review:
public BType resolvePatternTypeFromMatchExpr(BLangErrorMatchPattern errorMatchPattern, BLangExpression matchExpr) {
        if (matchExpr == null) {
            return errorMatchPattern.type;
        }

        if (isAssignable(matchExpr.type, errorMatchPattern.type)) {
            return matchExpr.type;
        }
        if (isAssignable(errorMatchPattern.type, matchExpr.type)) {
            return errorMatchPattern.type;
        }
        return symTable.noType;
    }

Line commented on: if (isAssignable(matchExpr.type, errorMatchPattern.type)) {

Revised code:
public BType resolvePatternTypeFromMatchExpr(BLangErrorMatchPattern errorMatchPattern, BLangExpression matchExpr) {
        if (matchExpr == null) {
            return errorMatchPattern.type;
        }

        BType matchExprType = matchExpr.type;
        BType patternType = errorMatchPattern.type;
        if (isAssignable(matchExprType, patternType)) {
            return matchExprType;
        }
        if (isAssignable(patternType, matchExprType)) {
            return patternType;
        }
        return symTable.noType;
    }
Code review comment: BTW, it seems that the precision will always set to the default, why not change it to a constant.

Code under review:
public ResourceSpec merge(final ResourceSpec other) {
		checkNotNull(other, "Cannot merge with null resources");

		if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
			return UNKNOWN;
		}

		ResourceSpec target = new ResourceSpec(
				this.cpuCores.merge(other.cpuCores).getValue(),
				this.heapMemoryInMB + other.heapMemoryInMB,
				this.directMemoryInMB + other.directMemoryInMB,
				this.nativeMemoryInMB + other.nativeMemoryInMB,
				this.stateSizeInMB + other.stateSizeInMB,
				this.managedMemoryInMB + other.managedMemoryInMB);
		target.extendedResources.putAll(extendedResources);
		for (Resource resource : other.extendedResources.values()) {
			target.extendedResources.merge(resource.getName(), resource, (v1, v2) -> v1.merge(v2));
		}
		return target;
	}

Line commented on: this.cpuCores.merge(other.cpuCores).getValue(),

Revised code:
public ResourceSpec merge(final ResourceSpec other) {
		checkNotNull(other, "Cannot merge with null resources");

		if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
			return UNKNOWN;
		}

		ResourceSpec target = new ResourceSpec(
			this.cpuCores.merge(other.cpuCores),
			this.taskHeapMemory.add(other.taskHeapMemory),
			this.taskOffHeapMemory.add(other.taskOffHeapMemory),
			this.onHeapManagedMemory.add(other.onHeapManagedMemory),
			this.offHeapManagedMemory.add(other.offHeapManagedMemory));
		target.extendedResources.putAll(extendedResources);
		for (Resource resource : other.extendedResources.values()) {
			target.extendedResources.merge(resource.getName(), resource, (v1, v2) -> v1.merge(v2));
		}
		return target;
	}
Code review comment: should also have 503 and 500 - https://github.com/eclipse/microprofile-health/blob/master/spec/src/main/asciidoc/protocol-wireformat.adoc#status-codes

Code under review:
private APIResponses createAPIResponses() {
        APIResponses responses = new APIResponsesImpl();
        responses.addAPIResponse("200", createAPIResponse());
        return responses;
    }

Line commented on: responses.addAPIResponse("200", createAPIResponse());

Revised code:
private APIResponses createAPIResponses() {
        APIResponses responses = new APIResponsesImpl();
        responses.addAPIResponse("200", createAPIResponse());
        responses.addAPIResponse("503", createAPIResponse());
        responses.addAPIResponse("500", createAPIResponse());
        return responses;
    }
Code review comment: Is this going to `toString` correctly for the headers?  If you want to do associations for URL and status code show it like this:  `URL: %s, Status code: %d`

Code under review:
public void listKeySnippets() {
        KeyClient keyClient = createClient();
        
        for (KeyBase key : keyClient.listKeys()) {
            Key keyWithMaterial = keyClient.getKey(key);
            System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
                keyWithMaterial.keyMaterial().kty());
        }
        

        
        for (KeyBase key : keyClient.listKeys(new Context(key2, value2))) {
            Key keyWithMaterial = keyClient.getKey(key);
            System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
                keyWithMaterial.keyMaterial().kty());
        }
        

        
        keyClient.listKeys().iterableByPage().forEach(resp -> {
            System.out.printf("Response headers are %s. Url %s  and status code %d %n", resp.headers(),
                resp.request().url(), resp.statusCode());
            resp.items().forEach(value -> {
                Key keyWithMaterial = keyClient.getKey(value);
                System.out.printf("Received key with name %s and type %s %n", keyWithMaterial.name(),
                    keyWithMaterial.keyMaterial().kty());
            });
        });
        
    }

Line commented on: System.out.printf("Response headers are %s. Url %s  and status code %d %n", resp.headers(),

Revised code:
public void listKeySnippets() {
        KeyClient keyClient = createClient();
        
        for (KeyBase key : keyClient.listKeys()) {
            Key keyWithMaterial = keyClient.getKey(key);
            System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
                keyWithMaterial.keyMaterial().kty());
        }
        

        
        for (KeyBase key : keyClient.listKeys(new Context(key2, value2))) {
            Key keyWithMaterial = keyClient.getKey(key);
            System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
                keyWithMaterial.keyMaterial().kty());
        }
        

        
        keyClient.listKeys().iterableByPage().forEach(resp -> {
            System.out.printf("Got response headers . Url: %s, Status code: %d %n",
                resp.request().url(), resp.statusCode());
            resp.items().forEach(value -> {
                Key keyWithMaterial = keyClient.getKey(value);
                System.out.printf("Received key with name %s and type %s %n", keyWithMaterial.name(),
                    keyWithMaterial.keyMaterial().kty());
            });
        });
        
    }
Code review comment: @geoand: This is needed in order to deal with some `tck` issues which cause `config.getValue().initAndExit` to be always true. There is a comment right above (see lines 30-31)

Code under review:
public void exitIfNeeded() {
        
        
        boolean initAndExitConfigured = propertyConfigured(QUARKUS_INIT_AND_EXIT);
        if (initAndExitConfigured && config.getValue().initAndExit) {
            if (ConfigProvider.getConfig().getValue(QUARKUS_INIT_AND_EXIT, boolean.class)) {
                preventFurtherRecorderSteps(5, "Error attempting to gracefully shutdown after initialization",
                        () -> new PreventFurtherStepsException("Gracefully exiting after initialization.", 0));
            }
        }
    }

Line commented on: if (initAndExitConfigured && config.getValue().initAndExit) {

Revised code:
public void exitIfNeeded() {
        
        
        boolean initAndExitConfigured = propertyConfigured(QUARKUS_INIT_AND_EXIT);
        if (initAndExitConfigured && config.getValue().initAndExit) {
            if (ConfigProvider.getConfig().getValue(QUARKUS_INIT_AND_EXIT, boolean.class)) {
                preventFurtherRecorderSteps(5, "Error attempting to gracefully shutdown after initialization",
                        () -> new PreventFurtherStepsException("Gracefully exiting after initialization.", 0));
            }
        }
    }
Code review comment: We can optimize the code as follow: ```         return LogicalTypeMerging.findCommonType(                         Arrays.asList(                                 inputDataType.getLogicalType(),                                 nullReplacementDataType.getLogicalType()))                 .map(t -> t.copy(nullReplacementDataType.getLogicalType().isNullable()))                 .map(TypeConversions::fromLogicalToDataType); ```

Code under review:
public Optional<DataType> inferType(CallContext callContext) {
        final List<DataType> argumentDataTypes = callContext.getArgumentDataTypes();
        final DataType inputDataType = argumentDataTypes.get(0);
        final DataType nullReplacementDataType = argumentDataTypes.get(1);

        if (!inputDataType.getLogicalType().isNullable()) {
            return Optional.of(inputDataType);
        }

        return LogicalTypeMerging.findCommonType(
                        Arrays.asList(
                                inputDataType.getLogicalType(),
                                nullReplacementDataType.getLogicalType()))
                .map(
                        commonType ->
                                nullReplacementDataType.getLogicalType().isNullable()
                                        ? commonType
                                        : commonType.copy(false))
                .map(TypeConversions::fromLogicalToDataType);
    }

Line commented on: return LogicalTypeMerging.findCommonType(

Revised code:
public Optional<DataType> inferType(CallContext callContext) {
        final List<DataType> argumentDataTypes = callContext.getArgumentDataTypes();
        final DataType inputDataType = argumentDataTypes.get(0);
        final DataType nullReplacementDataType = argumentDataTypes.get(1);

        if (!inputDataType.getLogicalType().isNullable()) {
            return Optional.of(inputDataType);
        }

        return LogicalTypeMerging.findCommonType(
                        Arrays.asList(
                                inputDataType.getLogicalType(),
                                nullReplacementDataType.getLogicalType()))
                .map(t -> t.copy(nullReplacementDataType.getLogicalType().isNullable()))
                .map(TypeConversions::fromLogicalToDataType);
    }
Code review comment: Same here about simplifying the logic.

Code under review:
public void handle(RoutingContext event) {
        HttpServerRequest request = event.request();
        HttpServerResponse response = event.response();

        if (graphQLRuntimeConfig.enable) {

            GraphQLSchema graphQLSchema = CDI.current().select(GraphQLSchema.class).get();
            SchemaPrinter schemaPrinter = CDI.current().select(SchemaPrinter.class).get();

            String schemaString = schemaPrinter.print(graphQLSchema);

            if (request.method().equals(HttpMethod.OPTIONS)) {
                response.headers().set(HttpHeaders.ALLOW, ALLOWED_METHODS);
            } else if (request.method().equals(HttpMethod.GET)) {
                response.headers().set(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
                response.end(Buffer.buffer(schemaString));
            } else {
                response.setStatusCode(405).end();
            }
        } else {
            response.setStatusCode(404);
            response.end();
        }
    }

Line commented on: if (graphQLRuntimeConfig.enable) {

Revised code:
public void handle(RoutingContext event) {
        HttpServerRequest request = event.request();
        HttpServerResponse response = event.response();

        GraphQLSchema graphQLSchema = CDI.current().select(GraphQLSchema.class).get();
        SchemaPrinter schemaPrinter = CDI.current().select(SchemaPrinter.class).get();

        String schemaString = schemaPrinter.print(graphQLSchema);

        if (request.method().equals(HttpMethod.OPTIONS)) {
            response.headers().set(HttpHeaders.ALLOW, ALLOWED_METHODS);
        } else if (request.method().equals(HttpMethod.GET)) {
            response.headers().set(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
            response.end(Buffer.buffer(schemaString));
        } else {
            response.setStatusCode(405).end();
        }
    }
Code review comment: No,  it will return an Empty notExistClause*Context, it's EXISTS() method will return null

Code under review:
public ASTNode visitCreateTable(final CreateTableContext ctx) {
        CreateTableStatement result = new CreateTableStatement((SimpleTableSegment) visit(ctx.tableName()), null != ctx.notExistClause_().EXISTS());
        if (null != ctx.createDefinitionClause()) {
            CollectionValue<CreateDefinitionSegment> createDefinitions = (CollectionValue<CreateDefinitionSegment>) visit(ctx.createDefinitionClause());
            for (CreateDefinitionSegment each : createDefinitions.getValue()) {
                if (each instanceof ColumnDefinitionSegment) {
                    result.getColumnDefinitions().add((ColumnDefinitionSegment) each);
                } else if (each instanceof ConstraintDefinitionSegment) {
                    result.getConstraintDefinitions().add((ConstraintDefinitionSegment) each);
                }
            }
        }
        return result;
    }

Line commented on: CreateTableStatement result = new CreateTableStatement((SimpleTableSegment) visit(ctx.tableName()), null != ctx.notExistClause_().EXISTS());

Revised code:
public ASTNode visitCreateTable(final CreateTableContext ctx) {
        CreateTableStatement result = new CreateTableStatement((SimpleTableSegment) visit(ctx.tableName()), null != ctx.notExistClause_());
        if (null != ctx.createDefinitionClause()) {
            CollectionValue<CreateDefinitionSegment> createDefinitions = (CollectionValue<CreateDefinitionSegment>) visit(ctx.createDefinitionClause());
            for (CreateDefinitionSegment each : createDefinitions.getValue()) {
                if (each instanceof ColumnDefinitionSegment) {
                    result.getColumnDefinitions().add((ColumnDefinitionSegment) each);
                } else if (each instanceof ConstraintDefinitionSegment) {
                    result.getConstraintDefinitions().add((ConstraintDefinitionSegment) each);
                }
            }
        }
        return result;
    }
Code review comment: Shall we use `configValueMap.get(v1).getValue()` inside the assertion calls? Creating new variables can be redundant if we don't use them multiple times.

Code under review:
public void testCliWhenUnsupportedTypesWithinToml() {
        ArrayType arrayType = TypeCreator.createArrayType(TYPE_STRING);
        VariableKey v1 = new VariableKey(module, "v1", PredefinedTypes.TYPE_INT, true);
        Type v2Type = new BIntersectionType(module, new Type[]{arrayType, PredefinedTypes.TYPE_READONLY},
                arrayType, 0, true);
        VariableKey v2 = new VariableKey(module, "v2", v2Type, true);
        RuntimeDiagnosticLog diagnosticLog = new RuntimeDiagnosticLog();
        ConfigResolver configResolver =
                new ConfigResolver(Map.ofEntries(Map.entry(module, new VariableKey[]{v1, v2})), diagnosticLog,
                        List.of(new CliProvider(ROOT_MODULE, "-CmyOrg.test_module.v1=87"),
                                new TomlFileProvider(ROOT_MODULE,
                                        getConfigPath("UnsupportedCLITypeConfig.toml"), Set.of(module))));
        Map<VariableKey, ConfigValue> configValueMap = configResolver.resolveConfigs();
        Object v1Value = configValueMap.get(v1).getValue();
        Object v2Value = configValueMap.get(v2).getValue();
        Assert.assertEquals(v1Value, 87L);
        Assert.assertEquals(v2Value.toString(), "[\"hello\",\"world\"]");
        Assert.assertEquals(0, diagnosticLog.getErrorCount());
    }

Line commented on: Object v2Value = configValueMap.get(v2).getValue();

Revised code:
public void testCliWhenUnsupportedTypesWithinToml() {
        ArrayType arrayType = TypeCreator.createArrayType(TYPE_STRING);
        VariableKey v1 = new VariableKey(module, "v1", PredefinedTypes.TYPE_INT, true);
        Type v2Type = new BIntersectionType(module, new Type[]{arrayType, PredefinedTypes.TYPE_READONLY},
                arrayType, 0, true);
        VariableKey v2 = new VariableKey(module, "v2", v2Type, true);
        RuntimeDiagnosticLog diagnosticLog = new RuntimeDiagnosticLog();
        ConfigResolver configResolver =
                new ConfigResolver(Map.ofEntries(Map.entry(module, new VariableKey[]{v1, v2})), diagnosticLog,
                        List.of(new CliProvider(ROOT_MODULE, "-CmyOrg.test_module.v1=87"),
                                new TomlFileProvider(ROOT_MODULE,
                                        getConfigPath("UnsupportedCLITypeConfig.toml"), Set.of(module))));
        Map<VariableKey, ConfigValue> configValueMap = configResolver.resolveConfigs();
        Assert.assertEquals(configValueMap.get(v1).getValue(), 87L);
        Assert.assertEquals(configValueMap.get(v2).getValue().toString(), "[\"hello\",\"world\"]");
        Assert.assertEquals(0, diagnosticLog.getErrorCount());
    }
Code review comment: Due to the concurrent access the synchronization is actually quite hard. I think I have pushed a good solution now.

Code under review:
public void setCurrentKey(Object key) {
    if (stateful && usesTimers) {
      
      
      
      
      synchronized (getKeyedStateBackend()) {
        super.setCurrentKey(key);
      }
    } else if (usesTimers) {
      
      
      super.setCurrentKey(key);
    } else {
      throw new UnsupportedOperationException(
          "Current key for state backend can only be set by state requests from SDK workers or when processing timers.");
    }
  }

Line commented on: if (stateful && usesTimers) {

Revised code:
public void setCurrentKey(Object key) {
    
    
    if (!usesTimers) {
      throw new UnsupportedOperationException(
          "Current key for state backend can only be set by state requests from SDK workers or when processing timers.");
    }
  }