muttakin2301/ccr_train_1000 huggingface dataset:
Code review comment: ```ballerina public function main() {     record {| int j; |} x = {j: 1};     record { never i?; int j; } y = x; }` ```  For each of these, we need to make sure we add runtime tests also.

Code before review:
private boolean checkFieldEquivalency(BRecordType lhsType, BRecordType rhsType, Set<TypePair> unresolvedTypes) {
Map<String, BField> rhsFields = new LinkedHashMap<>(rhsType.fields);
for (BField lhsField : lhsType.fields.values()) {
BField rhsField = rhsFields.get(lhsField.name.value);
if (rhsField == null) {
if (!Symbols.isOptional(lhsField.symbol) || lhsField.type.tag == NEVER) {
return false;
}
continue;
}
if (hasIncompatibleReadOnlyFlags(lhsField.symbol.flags, rhsField.symbol.flags)) {
return false;
}
if (!Symbols.isOptional(lhsField.symbol) && Symbols.isOptional(rhsField.symbol)) {
return false;
}
if (!isAssignable(rhsField.type, lhsField.type, unresolvedTypes)) {
return false;
}
rhsFields.remove(lhsField.name.value);
}
if (lhsType.sealed) {
for (BField field : rhsFields.values()) {
if (!isNeverTypeOrStructureTypeWithARequiredNeverMember(field.type)) {
return false;
}
}
return true;
}
BType lhsRestFieldType = lhsType.restFieldType;
for (BField field : rhsFields.values()) {
if (!isAssignable(field.type, lhsRestFieldType, unresolvedTypes)) {
return false;
}
}
return true;
}

Line under review: if (!Symbols.isOptional(lhsField.symbol) || lhsField.type.tag == NEVER) {

Code after addressing the review:
private boolean checkFieldEquivalency(BRecordType lhsType, BRecordType rhsType, Set<TypePair> unresolvedTypes) {
Map<String, BField> rhsFields = new LinkedHashMap<>(rhsType.fields);
for (BField lhsField : lhsType.fields.values()) {
BField rhsField = rhsFields.get(lhsField.name.value);
if (rhsField == null) {
if (!Symbols.isOptional(lhsField.symbol) || isInvalidNeverField(lhsField, rhsType)) {
return false;
}
continue;
}
if (hasIncompatibleReadOnlyFlags(lhsField.symbol.flags, rhsField.symbol.flags)) {
return false;
}
if (!Symbols.isOptional(lhsField.symbol) && Symbols.isOptional(rhsField.symbol)) {
return false;
}
if (!isAssignable(rhsField.type, lhsField.type, unresolvedTypes)) {
return false;
}
rhsFields.remove(lhsField.name.value);
}
if (lhsType.sealed) {
for (BField field : rhsFields.values()) {
if (!isNeverTypeOrStructureTypeWithARequiredNeverMember(field.type)) {
return false;
}
}
return true;
}
BType lhsRestFieldType = lhsType.restFieldType;
for (BField field : rhsFields.values()) {
if (!isAssignable(field.type, lhsRestFieldType, unresolvedTypes)) {
return false;
}
}
return true;
}
Code review comment: I believe this (and below) exception messages are not correct anymore.

Code before review:
public void open(TableInputSplit split) throws IOException {
initTable();
if (table == null) {
throw new IOException("The HBase table has not been opened! " +
"This needs to be done in configure().");
}
if (scan == null) {
throw new IOException("Scan has not been initialized! " +
"This needs to be done in configure().");
}
if (split == null) {
throw new IOException("Input split is null!");
}
logSplitInfo("opening", split);
currentRow = split.getStartRow();
scan.setStartRow(currentRow);
scan.setStopRow(split.getEndRow());
resultScanner = table.getScanner(scan);
endReached = false;
scannedRows = 0;
}

Line under review: "This needs to be done in configure().");

Code after addressing the review:
public void open(TableInputSplit split) throws IOException {
initTable();
if (split == null) {
throw new IOException("Input split is null!");
}
logSplitInfo("opening", split);
currentRow = split.getStartRow();
scan.setStartRow(currentRow);
scan.setStopRow(split.getEndRow());
resultScanner = table.getScanner(scan);
endReached = false;
scannedRows = 0;
}
Code review comment: Ok, thanks for the reminder!

Code before review:
public void run(SourceContext<OUT> ctx) throws Exception {
final RMQCollector collector = new RMQCollector(ctx);
while (running) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
synchronized (ctx.getCheckpointLock()) {
if (!autoAck) {
final long deliveryTag = delivery.getEnvelope().getDeliveryTag();
if (usesCorrelationId) {
final String correlationId = delivery.getProperties().getCorrelationId();
Preconditions.checkNotNull(correlationId, "RabbitMQ source was instantiated " +
"with usesCorrelationId set to true but a message was received with " +
"correlation id set to null!");
if (!addId(correlationId)) {
continue;
}
}
sessionIds.add(deliveryTag);
}
schema.deserialize(delivery.getBody(), collector);
if (collector.isEndOfStreamSignalled()) {
this.running = false;
return;
}
}
}
}

Line under review: schema.deserialize(delivery.getBody(), collector);

Code after addressing the review:
public void run(SourceContext<OUT> ctx) throws Exception {
final RMQCollector collector = new RMQCollector(ctx);
while (running) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
synchronized (ctx.getCheckpointLock()) {
if (!autoAck) {
final long deliveryTag = delivery.getEnvelope().getDeliveryTag();
if (usesCorrelationId) {
final String correlationId = delivery.getProperties().getCorrelationId();
Preconditions.checkNotNull(correlationId, "RabbitMQ source was instantiated " +
"with usesCorrelationId set to true but a message was received with " +
"correlation id set to null!");
if (!addId(correlationId)) {
continue;
}
}
sessionIds.add(deliveryTag);
}
schema.deserialize(delivery.getBody(), collector);
if (collector.isEndOfStreamSignalled()) {
this.running = false;
return;
}
}
}
}
Code review comment: Can we use the tenant_iam_role flag for this as well?

Code before review:
private void addParameterStoreValidationHandler(ApplicationContainerCluster cluster, DeployState deployState) {
if (deployState.zone().system() == SystemName.PublicCd) {
BindingPattern bindingPattern = SystemBindingPattern.fromHttpPath("/validate-secret-store");
Handler<AbstractConfigProducer<?>> handler = new Handler<>(
new ComponentModel("com.yahoo.jdisc.cloud.aws.AwsParameterStoreValidationHandler", null, null, null));
handler.addServerBindings(bindingPattern);
cluster.addComponent(handler);
}
}

Line under review: if (deployState.zone().system() == SystemName.PublicCd) {

Code after addressing the review:
private void addParameterStoreValidationHandler(ApplicationContainerCluster cluster, DeployState deployState) {
if (deployState.featureFlags().tenantIamRole()) {
BindingPattern bindingPattern = SystemBindingPattern.fromHttpPath("/validate-secret-store");
Handler<AbstractConfigProducer<?>> handler = new Handler<>(
new ComponentModel("com.yahoo.jdisc.cloud.aws.AwsParameterStoreValidationHandler", null, null, null));
handler.addServerBindings(bindingPattern);
cluster.addComponent(handler);
}
}
Code review comment: Should we use https://github.com/ballerina-platform/ballerina-lang/blob/master/bvm/ballerina-runtime/src/main/java/org/ballerinalang/jvm/StringUtils.java#L112 instead?

Code before review:
public static Object next(Strand strand, ObjectValue m) {
IteratorValue xmlIterator = (IteratorValue) m.getNativeData("&iterator&");
if (xmlIterator == null) {
xmlIterator = ((XMLValue) m.get(new BmpStringValue("m"))).getIterator();
m.addNativeData("&iterator&", xmlIterator);
}
if (xmlIterator.hasNext()) {
Object xmlValue = xmlIterator.next();
Map<String, BField> fields = new HashMap<>();
BUnionType type = new BUnionType(Arrays.asList(BTypes.typeString, BTypes.typeXML));
fields.put("value", new BField(type, "value", Flags.PUBLIC + Flags.REQUIRED));
BRecordType recordType = new BRecordType("$$returnType$$", null, 0, fields,
null, true, 0);
return BallerinaValues.createRecord(new MapValueImpl<>(recordType), xmlValue);
}
return null;
}

Line under review: xmlIterator = ((XMLValue) m.get(new BmpStringValue("m"))).getIterator();

Code after addressing the review:
public static Object next(Strand strand, ObjectValue m) {
IteratorValue xmlIterator = (IteratorValue) m.getNativeData("&iterator&");
if (xmlIterator == null) {
xmlIterator = ((XMLValue) m.get("m")).getIterator();
m.addNativeData("&iterator&", xmlIterator);
}
if (xmlIterator.hasNext()) {
Object xmlValue = xmlIterator.next();
return BallerinaValues.createRecord(new MapValueImpl<>(BTypes.xmlItrNextReturnType), xmlValue);
}
return null;
}
Code review comment: Document indexing doesn't always complete instantly, so I don't want to begin testing while it is still running nor do I want to spam the service with a ton of requests.

Code before review:
protected Mono<Void> populateIndex(int documentCount, String documentSize) {
/*
* Generate the count of documents using the given size. Then, upload the documents in batches of 100, this
* prevents the batch from triggering the services request size limit to fail. Finally, continuously poll the
* index for its document count until it is equal to the count passed.
*/
return Mono.defer(() -> {
List<Hotel> hotels = DocumentGenerator.generateHotels(documentCount, DocumentSize.valueOf(documentSize));
return Flux.range(0, (int) Math.ceil(hotels.size() / 100D))
.map(i -> hotels.subList(i * 100, Math.min((i + 1) * 100, hotels.size())))
.flatMap(hotelDocuments -> searchAsyncClient.indexDocuments(new IndexDocumentsBatch<Hotel>()
.addUploadActions(hotelDocuments)))
.then();
}).then(Mono.defer(() -> searchAsyncClient.getDocumentCount()
.delaySubscription(Duration.ofSeconds(1))
.filter(count -> count == documentCount)
.repeatWhenEmpty(Flux::repeat)
.then()));
}

Line under review: .delaySubscription(Duration.ofSeconds(1))

Code after addressing the review:
protected Mono<Void> populateIndex(int documentCount, String documentSize) {
/*
* Generate the count of documents using the given size. Then, upload the documents in batches of 100, this
* prevents the batch from triggering the services request size limit to fail. Finally, continuously poll the
* index for its document count until it is equal to the count passed.
*/
return Mono.defer(() -> {
List<Hotel> hotels = DocumentGenerator.generateHotels(documentCount, DocumentSize.valueOf(documentSize));
return Flux.range(0, (int) Math.ceil(hotels.size() / 100D))
.map(i -> hotels.subList(i * 100, Math.min((i + 1) * 100, hotels.size())))
.flatMap(hotelDocuments -> searchAsyncClient.indexDocuments(new IndexDocumentsBatch<Hotel>()
.addUploadActions(hotelDocuments)))
.then();
}).then(Mono.defer(() -> searchAsyncClient.getDocumentCount()
.delaySubscription(Duration.ofSeconds(1))
.filter(count -> count == documentCount)
.repeatWhenEmpty(Flux::repeat)
.then()));
}
Code review comment: Try to leave one comments and resolve the rests

Code before review:
public static DataChangeDetectionPolicy map(com.azure.search.documents.implementation.models.DataChangeDetectionPolicy obj) {
if (obj instanceof HighWaterMarkChangeDetectionPolicy) {
return HighWaterMarkChangeDetectionPolicyConverter.map((HighWaterMarkChangeDetectionPolicy) obj);
}
if (obj instanceof SqlIntegratedChangeTrackingPolicy) {
return SqlIntegratedChangeTrackingPolicyConverter.map((SqlIntegratedChangeTrackingPolicy) obj);
}
throw LOGGER.logExceptionAsError(new RuntimeException(String.format(ABSTRACT_EXTERNAL_ERROR_MSG,
obj.getClass().getSimpleName())));
}

Line under review: if (obj instanceof HighWaterMarkChangeDetectionPolicy) {

Code after addressing the review:
public static DataChangeDetectionPolicy map(com.azure.search.documents.implementation.models.DataChangeDetectionPolicy obj) {
if (obj instanceof HighWaterMarkChangeDetectionPolicy) {
return HighWaterMarkChangeDetectionPolicyConverter.map((HighWaterMarkChangeDetectionPolicy) obj);
}
if (obj instanceof SqlIntegratedChangeTrackingPolicy) {
return SqlIntegratedChangeTrackingPolicyConverter.map((SqlIntegratedChangeTrackingPolicy) obj);
}
throw LOGGER.logExceptionAsError(new RuntimeException(String.format(ABSTRACT_EXTERNAL_ERROR_MSG,
obj.getClass().getSimpleName())));
}
Code review comment: It is an big time but not too big time for timeout balancing the  load success rate and the cluster overload. 

Code before review:
public void fillByteBuffer(ByteBuffer buffer) throws IOException, InterruptedException {
if (closed) {
throw new IOException("Stream is already closed.");
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), buffer.limit());
queue.offer(inputStream, 300, TimeUnit.SECONDS);
}

Line under review: queue.offer(inputStream, 300, TimeUnit.SECONDS);

Code after addressing the review:
public void fillByteBuffer(ByteBuffer buffer) throws IOException, InterruptedException {
if (closed) {
throw new IOException("Stream is already closed.");
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), buffer.limit());
queue.offer(inputStream, 300, TimeUnit.SECONDS);
}
Code review comment: Hello @gastaldi, do you mean it's broken because it isn't doing a check to see if the `file` is a directory, or something else?

Code before review:
public InputStream getResourceAsStream(String unsanitisedName) {
String name = sanitizeName(unsanitisedName);
ClassLoaderState state = getState();
if (state.bannedResources.contains(name)) {
return null;
}
if (name.endsWith(".class")) {
ClassPathElement[] providers = state.loadableResources.get(name);
if (providers != null) {
return new ByteArrayInputStream(providers[0].getResource(name).getData());
}
} else {
for (ClassPathElement i : elements) {
ClassPathResource res = i.getResource(name);
if (res != null) {
if (res.isDirectory()) {
try {
return res.getUrl().openStream();
} catch (IOException e) {
log.debug("Ignoring exception that occurred while opening a stream for resource " + unsanitisedName,
e);
continue;
}
}
return new ByteArrayInputStream(res.getData());
}
}
}
return parent.getResourceAsStream(unsanitisedName);
}

Line under review: return res.getUrl().openStream();

Code after addressing the review:
public InputStream getResourceAsStream(String unsanitisedName) {
String name = sanitizeName(unsanitisedName);
ClassLoaderState state = getState();
if (state.bannedResources.contains(name)) {
return null;
}
if (name.endsWith(".class")) {
ClassPathElement[] providers = state.loadableResources.get(name);
if (providers != null) {
return new ByteArrayInputStream(providers[0].getResource(name).getData());
}
} else {
for (ClassPathElement i : elements) {
ClassPathResource res = i.getResource(name);
if (res != null) {
if (res.isDirectory()) {
try {
return res.getUrl().openStream();
} catch (IOException e) {
log.debug("Ignoring exception that occurred while opening a stream for resource " + unsanitisedName,
e);
continue;
}
}
return new ByteArrayInputStream(res.getData());
}
}
}
return parent.getResourceAsStream(unsanitisedName);
}
Code review comment: Yes, that is true. `CosmosConfig` is not directly related to the database name.  In fact, I was also wondering, if we can completely get rid of `database` from `CosmosConfig` and customers can directly override the method `getDatabaseName()` from `CosmosConfigurationSupport` class.  That's what spring-data-mongodb does. They don't have any config tied to the database.  They only have `getDatabaseName()` in `MongoConfigurationSupport` class.   However, it will not hurt to keep it in `CosmosConfig`, because of easiness of use.  Having `database` in `CosmosConfig` provides the user ability to use the database from the `CosmosConfig` bean.   What are your thoughts on this @zhoufenqin @saragluna 

Code before review:
public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
}

Line under review: .build();

Code after addressing the review:
public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
}
Code review comment: ```suggestion             return JAXBContext.newInstance(classes.toArray(new Class[0]), properties); ```

Code before review:
public JAXBContext jaxbContext(Instance<JaxbContextCustomizer> customizers) {
try {
Map<String, Object> properties = new HashMap<>();
List<JaxbContextCustomizer> sortedCustomizers = sortCustomizersInDescendingPriorityOrder(customizers);
for (JaxbContextCustomizer customizer : sortedCustomizers) {
customizer.customizeContextProperties(properties);
}
String[] classNamesToBeBounded = JaxbContextConfigRecorder.getClassesToBeBound();
List<Class<?>> classes = new ArrayList<>();
for (int i = 0; i < classNamesToBeBounded.length; i++) {
Class<?> clazz = getClassByName(classNamesToBeBounded[i]);
if (!clazz.isPrimitive()) {
classes.add(clazz);
}
}
return JAXBContext.newInstance(classes.toArray(new Class[classes.size()]), properties);
} catch (JAXBException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}

Line under review: return JAXBContext.newInstance(classes.toArray(new Class[classes.size()]), properties);

Code after addressing the review:
public JAXBContext jaxbContext(Instance<JaxbContextCustomizer> customizers) {
try {
Map<String, Object> properties = new HashMap<>();
List<JaxbContextCustomizer> sortedCustomizers = sortCustomizersInDescendingPriorityOrder(customizers);
for (JaxbContextCustomizer customizer : sortedCustomizers) {
customizer.customizeContextProperties(properties);
}
String[] classNamesToBeBounded = JaxbContextConfigRecorder.getClassesToBeBound();
List<Class<?>> classes = new ArrayList<>();
for (int i = 0; i < classNamesToBeBounded.length; i++) {
Class<?> clazz = getClassByName(classNamesToBeBounded[i]);
if (!clazz.isPrimitive()) {
classes.add(clazz);
}
}
return JAXBContext.newInstance(classes.toArray(new Class[0]), properties);
} catch (JAXBException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
Code review comment: this is a private method that is used within this file that is supposed to simplify the code that deals with UUIDs. Also, `32 - length` is a start index, so it will return exactly what's asked for.  It's still error-prone (length can be bigger than 32), but given it's never meant to be shared outside of this file, simplicity seems more important to me.

Code before review:
private static String getRandomId(int length) {
return CoreUtils.randomUuid().toString()
.replace("-", "")
.substring(32 - length);
}

Line under review: .substring(32 - length);

Code after addressing the review:
private static String getRandomId(int length) {
return CoreUtils.randomUuid().toString()
.replace("-", "")
.substring(32 - length);
}
Code review comment: Maybe make the comment a bit clearer? E.g. "Exception correctly aborts the entire pipeline because no error handler was registered?"

Code before review:
public void testBRHEnabledPTransform() {
PCollection<Integer> record = pipeline.apply(Create.of(1, 2, 3, 4));
record.apply(new BRHEnabledPTransform());
thrown.expect(RuntimeException.class);
pipeline.run();
}

Line under review: thrown.expect(RuntimeException.class);

Code after addressing the review:
public void testBRHEnabledPTransform() {
PCollection<Integer> record = pipeline.apply(Create.of(1, 2, 3, 4));
record.apply(new BRHEnabledPTransform());
thrown.expect(RuntimeException.class);
pipeline.run();
}
Code review comment: Is the usual format we use in ballerina compilation errors?

Code before review:
private List<Executable> getExecutables(Class<?> clazz, String methodName, JMethodKind kind) {
if (kind == JMethodKind.CONSTRUCTOR) {
if (Modifier.isAbstract(clazz.getModifiers())) {
String classType = clazz.isInterface() ? "interface" : "abstract class";
throw new JInteropException(DiagnosticErrorCode.INSTANTIATION_ERROR,
"Cannot instantiate " + classType + " '" + clazz.getName() + "'");
}
return Arrays.asList(getConstructors(clazz));
} else {
List<Executable> list = new ArrayList<>();
for (Method method : getMethods(clazz)) {
if (method.getName().equals(methodName)) {
list.add(method);
}
}
return list;
}
}

Line under review: "Cannot instantiate " + classType + " '" + clazz.getName() + "'");

Code after addressing the review:
private List<Executable> getExecutables(Class<?> clazz, String methodName, JMethodKind kind) {
if (kind == JMethodKind.CONSTRUCTOR) {
if (Modifier.isAbstract(clazz.getModifiers())) {
throw new JInteropException(DiagnosticErrorCode.INSTANTIATION_ERROR,
"'" + clazz.getName() + "' is abstract, and cannot be instantiated");
}
return Arrays.asList(getConstructors(clazz));
} else {
List<Executable> list = new ArrayList<>();
for (Method method : getMethods(clazz)) {
if (method.getName().equals(methodName)) {
list.add(method);
}
}
return list;
}
}
Code review comment: Yeah, I had initially done it that way to have booleans for each of the log levels but the performance improvements were not noticeable by doing that way vs the current approach.   Moreover, `is*Enabled` methods in DefaultLogger are much faster than their logback counterparts (557664530 ops/sec vs 501866764 ops/sec). So, didn't want to micro-optimize.   However, if you think evaluating it once in the constructor will improve overall readability, I am fine with making this change.

Code before review:
public DefaultLogger(String className) {
String classPath;
try {
classPath = Class.forName(className).getCanonicalName();
} catch (ClassNotFoundException e) {
classPath = className;
}
this.classPath = classPath;
this.configuredLogLevel =
LogLevel.fromString(Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_LOG_LEVEL))
.getLogLevel();
}

Line under review: .getLogLevel();

Code after addressing the review:
public DefaultLogger(String className) {
String classPath;
try {
classPath = Class.forName(className).getCanonicalName();
} catch (ClassNotFoundException e) {
classPath = className;
}
this.classPath = classPath;
int configuredLogLevel =
LogLevel.fromString(Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_LOG_LEVEL))
.getLogLevel();
isTraceEnabled = LogLevel.VERBOSE.getLogLevel() > configuredLogLevel;
isDebugEnabled = LogLevel.VERBOSE.getLogLevel() >= configuredLogLevel;
isInfoEnabled = LogLevel.INFORMATIONAL.getLogLevel() >= configuredLogLevel;
isWarnEnabled = LogLevel.WARNING.getLogLevel() >= configuredLogLevel;
isErrorEnabled = LogLevel.ERROR.getLogLevel() >= configuredLogLevel;
}
Code review comment: @mkouba @Ladicek removed the `select()` invocation where it was superfluous.

Code before review:
public void testSyntheticObserver() {
MyObserver.EVENTS.clear();
Arc.container().beanManager().getEvent().select(String.class).fire("foo");
assertEquals(2, MyObserver.EVENTS.size(), "Events: " + MyObserver.EVENTS);
assertTrue(MyObserver.EVENTS.contains("foo"));
assertTrue(MyObserver.EVENTS.contains("foo_MyObserver"));
MyObserver.EVENTS.clear();
Arc.container().beanManager().getEvent().select(String.class, NamedLiteral.of("bla")).fire("foo");
assertEquals(3, MyObserver.EVENTS.size(), "Events: " + MyObserver.EVENTS);
assertTrue(MyObserver.EVENTS.contains("foo"));
assertTrue(MyObserver.EVENTS.contains("foo_MyObserver"));
assertTrue(MyObserver.EVENTS.contains("synthetic2"));
}

Line under review: Arc.container().beanManager().getEvent().select(String.class).fire("foo");

Code after addressing the review:
public void testSyntheticObserver() {
MyObserver.EVENTS.clear();
Arc.container().beanManager().getEvent().fire("foo");
assertEquals(2, MyObserver.EVENTS.size(), "Events: " + MyObserver.EVENTS);
assertTrue(MyObserver.EVENTS.contains("foo"));
assertTrue(MyObserver.EVENTS.contains("foo_MyObserver"));
MyObserver.EVENTS.clear();
Arc.container().beanManager().getEvent().select(String.class, NamedLiteral.of("bla")).fire("foo");
assertEquals(3, MyObserver.EVENTS.size(), "Events: " + MyObserver.EVENTS);
assertTrue(MyObserver.EVENTS.contains("foo"));
assertTrue(MyObserver.EVENTS.contains("foo_MyObserver"));
assertTrue(MyObserver.EVENTS.contains("synthetic2"));
}
Code review comment: We can't rely on the `999-SNAPSHOT` version in the tests.

Code before review:
public void shouldImportConditionalDependency() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("conditional-test-project");
runGradleWrapper(projectDir, "clean", ":runner:quarkusBuild", "-Dquarkus.package.type=mutable-jar");
final File buildDir = new File(projectDir, "runner" + File.separator + "build");
final Path mainLib = buildDir.toPath().resolve("quarkus-app").resolve("lib").resolve("main");
assertThat(mainLib.resolve("org.acme.ext-a-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-b-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-c-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-e-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-d-1.0-SNAPSHOT.jar")).doesNotExist();
assertThat(mainLib.resolve("org.acme.transitive-dependency-1.0-SNAPSHOT.jar")).doesNotExist();
final Path deploymentLib = buildDir.toPath().resolve("quarkus-app").resolve("lib").resolve("deployment");
assertThat(deploymentLib.resolve("org.acme.transitive-dependency-1.0-SNAPSHOT.jar")).exists();
assertThat(deploymentLib.resolve("io.quarkus.quarkus-agroal-999-SNAPSHOT.jar")).doesNotExist();
}

Line under review: assertThat(deploymentLib.resolve("io.quarkus.quarkus-agroal-999-SNAPSHOT.jar")).doesNotExist();

Code after addressing the review:
public void shouldImportConditionalDependency() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("conditional-test-project");
runGradleWrapper(projectDir, "clean", ":runner:quarkusBuild", "-Dquarkus.package.type=mutable-jar");
final File buildDir = new File(projectDir, "runner" + File.separator + "build");
final Path mainLib = buildDir.toPath().resolve("quarkus-app").resolve("lib").resolve("main");
assertThat(mainLib.resolve("org.acme.ext-a-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-b-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-c-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-e-1.0-SNAPSHOT.jar")).exists();
assertThat(mainLib.resolve("org.acme.ext-d-1.0-SNAPSHOT.jar")).doesNotExist();
assertThat(mainLib.resolve("org.acme.transitive-dependency-1.0-SNAPSHOT.jar")).doesNotExist();
final Path deploymentLib = buildDir.toPath().resolve("quarkus-app").resolve("lib").resolve("deployment");
assertThat(deploymentLib.resolve("org.acme.transitive-dependency-1.0-SNAPSHOT.jar")).exists();
assertThat(deploymentLib.resolve("io.quarkus.quarkus-agroal-" + getQuarkusVersion() + ".jar")).doesNotExist();
}
Code review comment: why only process those node?

Code before review:
private boolean hasCTEConsumerUnderJoin(PhysicalPlan root, Set<CTEId> cteIds) {
if (root instanceof PhysicalCTEConsumer) {
cteIds.add(((PhysicalCTEConsumer) root).getCteId());
return true;
} else if (root.children().size() != 1) {
return false;
} else if (root instanceof PhysicalDistribute
|| root instanceof PhysicalFilter
|| root instanceof PhysicalProject) {
return hasCTEConsumerUnderJoin((PhysicalPlan) root.child(0), cteIds);
} else {
return false;
}
}

Line under review: return false;

Code after addressing the review:
private boolean hasCTEConsumerUnderJoin(PhysicalPlan root, Set<CTEId> cteIds) {
if (root instanceof PhysicalCTEConsumer) {
cteIds.add(((PhysicalCTEConsumer) root).getCteId());
return true;
} else if (root.children().size() != 1) {
return false;
} else if (root instanceof PhysicalDistribute
|| root instanceof PhysicalFilter
|| root instanceof PhysicalProject) {
return hasCTEConsumerUnderJoin((PhysicalPlan) root.child(0), cteIds);
} else {
return false;
}
}
Code review comment: what's that ? BlockHole ?

Code before review:
public static void collectMaterializedViewMetrics(MetricVisitor visitor, boolean minifyMetrics) {
MaterializedViewMetricsRegistry instance = MaterializedViewMetricsRegistry.getInstance();
for (Map.Entry<MvId, MaterializedViewMetricsEntity> e : instance.idToMVMetrics.entrySet()) {
IMaterializedViewMetricsEntity mvEntity = e.getValue();
if (mvEntity == null || mvEntity instanceof  MaterializedViewMetricsBlackHoleEntity) {
continue;
}
MvId mvId = e.getKey();
MaterializedViewMetricsEntity entity = (MaterializedViewMetricsEntity) mvEntity;
for (Metric m : entity.getMetrics()) {
if (minifyMetrics) {
if (null == m.getValue()) {
continue;
}
if (Metric.MetricType.GAUGE == m.type) {
continue;
}
if (Metric.MetricType.COUNTER == m.type && ((Long) m.getValue()).longValue() == 0L) {
continue;
}
}
m.addLabel(new MetricLabel("db_name", entity.dbName))
.addLabel(new MetricLabel("mv_name", entity.mvName))
.addLabel(new MetricLabel("mv_id", String.valueOf(mvId.getId())));
visitor.visit(m);
}
}
if (!minifyMetrics) {
for (Map.Entry<String, Histogram> e : MaterializedViewMetricsRegistry.getInstance()
.metricRegistry.getHistograms().entrySet()) {
visitor.visitHistogram(e.getKey(), e.getValue());
}
}
}

Line under review: if (mvEntity == null || mvEntity instanceof  MaterializedViewMetricsBlackHoleEntity) {

Code after addressing the review:
public static void collectMaterializedViewMetrics(MetricVisitor visitor, boolean minifyMetrics) {
MaterializedViewMetricsRegistry instance = MaterializedViewMetricsRegistry.getInstance();
for (Map.Entry<MvId, MaterializedViewMetricsEntity> e : instance.idToMVMetrics.entrySet()) {
IMaterializedViewMetricsEntity mvEntity = e.getValue();
if (mvEntity == null || mvEntity instanceof  MaterializedViewMetricsBlackHoleEntity) {
continue;
}
MvId mvId = e.getKey();
MaterializedViewMetricsEntity entity = (MaterializedViewMetricsEntity) mvEntity;
for (Metric m : entity.getMetrics()) {
if (minifyMetrics) {
if (null == m.getValue()) {
continue;
}
if (Metric.MetricType.GAUGE == m.type) {
continue;
}
if (Metric.MetricType.COUNTER == m.type && ((Long) m.getValue()).longValue() == 0L) {
continue;
}
}
m.addLabel(new MetricLabel("db_name", entity.dbName))
.addLabel(new MetricLabel("mv_name", entity.mvName))
.addLabel(new MetricLabel("mv_id", String.valueOf(mvId.getId())));
visitor.visit(m);
}
}
if (!minifyMetrics) {
for (Map.Entry<String, Histogram> e : MaterializedViewMetricsRegistry.getInstance()
.metricRegistry.getHistograms().entrySet()) {
visitor.visitHistogram(e.getKey(), e.getValue());
}
}
}
Code review comment: it seems that simple range/in/eq predicates's column can be prefix of columns of rollup.

Code before review:
private int calcSortScore(MaterializedView mv, Set<String> equivalenceColumns, Set<String> nonEquivalenceColumns) {
List<Column> schema = mv.getBaseSchema();
int score = 0;
for (Column col : schema) {
String columName = col.getName().toLowerCase();
if (equivalenceColumns.contains(columName)) {
score++;
} else if (nonEquivalenceColumns.contains(columName)) {
score++;
break;
} else {
break;
}
}
return score;
}


Code after addressing the review:
private int calcSortScore(MaterializedView mv, Set<String> equivalenceColumns, Set<String> nonEquivalenceColumns) {
List<Column> keyColumns = mv.getKeyColumnsByIndexId(mv.getBaseIndexId());
int score = 0;
for (Column col : keyColumns) {
String columName = col.getName().toLowerCase();
if (equivalenceColumns.contains(columName)) {
score++;
} else if (nonEquivalenceColumns.contains(columName)) {
score++;
break;
} else {
break;
}
}
return score;
}
Code review comment: Could we set `rowEvents = new ArrayList<>();` on CommitTXEvent, but wait next BeginTXEvent

Code before review:
private void processEventWithTX(final AbstractWALEvent event) {
if (event instanceof BeginTXEvent) {
rowEvents = new ArrayList<>();
return;
}
if (event instanceof AbstractRowEvent) {
rowEvents.add((AbstractRowEvent) event);
return;
}
if (event instanceof CommitTXEvent) {
List<Record> records = new LinkedList<>();
for (AbstractWALEvent each : rowEvents) {
records.add(walEventConverter.convert(each));
}
records.add(walEventConverter.convert(event));
channel.pushRecords(records);
}
}

Line under review: }

Code after addressing the review:
private void processEventWithTX(final AbstractWALEvent event) {
if (event instanceof BeginTXEvent) {
rowEvents = new ArrayList<>();
return;
}
if (event instanceof AbstractRowEvent) {
rowEvents.add((AbstractRowEvent) event);
return;
}
if (event instanceof CommitTXEvent) {
List<Record> records = new LinkedList<>();
for (AbstractWALEvent each : rowEvents) {
records.add(walEventConverter.convert(each));
}
records.add(walEventConverter.convert(event));
channel.pushRecords(records);
}
}
Code review comment: Is this change necessary? Since the hashed operator id is the ground truth and always exists.

Code before review:
public CheckpointMetadata map(CheckpointMetadata value) throws Exception {
final List<OperatorState> mapped =
value.getOperatorStates().stream()
.map(
operatorState -> {
OperatorIdentifier operatorIdentifier;
if (operatorState.getOperatorUid().isPresent()) {
operatorIdentifier =
OperatorIdentifier.forUid(
operatorState.getOperatorUid().get());
} else {
operatorIdentifier =
OperatorIdentifier.forUidHash(
operatorState
.getOperatorID()
.toHexString());
}
final OperatorIdentifier transformedIdentifier =
uidTransformationMap.remove(operatorIdentifier);
if (transformedIdentifier != null) {
return operatorState.copyWithNewIDs(
transformedIdentifier.getUid().orElse(null),
transformedIdentifier.getOperatorId());
}
return operatorState;
})
.collect(Collectors.toList());
return new CheckpointMetadata(value.getCheckpointId(), mapped, value.getMasterStates());
}

Line under review: }

Code after addressing the review:
public CheckpointMetadata map(CheckpointMetadata value) throws Exception {
final List<OperatorState> mapped =
value.getOperatorStates().stream()
.map(
operatorState -> {
OperatorIdentifier operatorIdentifier;
if (operatorState.getOperatorUid().isPresent()) {
operatorIdentifier =
OperatorIdentifier.forUid(
operatorState.getOperatorUid().get());
} else {
operatorIdentifier =
OperatorIdentifier.forUidHash(
operatorState
.getOperatorID()
.toHexString());
}
final OperatorIdentifier transformedIdentifier =
uidTransformationMap.remove(operatorIdentifier);
if (transformedIdentifier != null) {
return operatorState.copyWithNewIDs(
transformedIdentifier.getUid().orElse(null),
transformedIdentifier.getOperatorId());
}
return operatorState;
})
.collect(Collectors.toList());
return new CheckpointMetadata(value.getCheckpointId(), mapped, value.getMasterStates());
}
Code review comment: I believe when `query` is null or empty this should continue clearing the query

Code before review:
public UrlBuilder setQuery(String query) {
if (query != null && !query.isEmpty()) {
with(query, UrlTokenizerState.QUERY);
}
return this;
}

Line under review: if (query != null && !query.isEmpty()) {

Code after addressing the review:
public UrlBuilder setQuery(String query) {
if (query == null || query.isEmpty()) {
this.query.clear();
} else {
with(query, UrlTokenizerState.QUERY);
}
return this;
}
Code review comment: now that using async client, ideally would not return constant success value here

Code before review:
public CompletableResultCode export(Collection<SpanData> spans) {
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe();
return CompletableResultCode.ofSuccess();
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return CompletableResultCode.ofFailure();
}
}

Line under review: return CompletableResultCode.ofSuccess();

Code after addressing the review:
public CompletableResultCode export(Collection<SpanData> spans) {
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe();
return CompletableResultCode.ofSuccess();
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return CompletableResultCode.ofFailure();
}
}
Code review comment: Can be simplifed to `mails.getOrDefault(recipient, List.of())`.

Code before review:
public List<Mail> inbox(String recipient) {
if (!mails.containsKey(recipient)) {
return List.of();
}
return mails.get(recipient);
}

Line under review: return mails.get(recipient);

Code after addressing the review:
public List<Mail> inbox(String recipient) {
return mails.getOrDefault(recipient, List.of());
}
Code review comment: only cachedPartitionNames,  cachedSnapshotId would be assigned at new IcebergTable

Code before review:
public void setCachedPartitionNames(List<String> cachedPartitionNames) {
writeLock();
try {
this.cachedPartitionNames = cachedPartitionNames;
} finally {
writeUnlock();
}
}

Line under review: this.cachedPartitionNames = cachedPartitionNames;

Code after addressing the review:
public void setCachedPartitionNames(List<String> cachedPartitionNames) {
writeLock();
try {
this.cachedPartitionNames = cachedPartitionNames;
} finally {
writeUnlock();
}
}
Code review comment: when `enableBucketShuffleJoin = false`, we should never do bucket shuffle at all. so when `isEnableBucketShuffleJoin = false`, function `isBucketShuffleDownGrade` should always return true?

Code before review:
private boolean isBucketShuffleDownGrade(Plan oneSidePlan, DistributionSpecHash otherSideSpec) {
boolean isBucketShuffleDownGrade = ConnectContext.get().getSessionVariable().isEnableBucketShuffleJoin();
if (!isBucketShuffleDownGrade) {
return false;
} else if (otherSideSpec.getShuffleType() != ShuffleType.EXECUTION_BUCKETED
|| !(oneSidePlan instanceof GroupPlan)) {
return false;
} else {
PhysicalOlapScan candidate = findDownGradeBucketShuffleCandidate((GroupPlan) oneSidePlan);
if (candidate == null || candidate.getTable() == null
|| candidate.getTable().getDefaultDistributionInfo() == null) {
return false;
} else {
int prunedPartNum = candidate.getSelectedPartitionIds().size();
int bucketNum = candidate.getTable().getDefaultDistributionInfo().getBucketNum();
int totalBucketNum = prunedPartNum * bucketNum;
int backEndNum = Math.max(1, ConnectContext.get().getEnv().getClusterInfo()
.getBackendsNumber(true));
int paraNum = Math.max(1, ConnectContext.get().getSessionVariable().getParallelExecInstanceNum());
int totalParaNum = Math.min(10, backEndNum * paraNum);
return totalBucketNum < totalParaNum;
}
}
}

Line under review: boolean isBucketShuffleDownGrade = ConnectContext.get().getSessionVariable().isEnableBucketShuffleJoin();

Code after addressing the review:
private boolean isBucketShuffleDownGrade(Plan oneSidePlan, DistributionSpecHash otherSideSpec) {
boolean isEnableBucketShuffleJoin = ConnectContext.get().getSessionVariable().isEnableBucketShuffleJoin();
if (!isEnableBucketShuffleJoin) {
return true;
} else if (otherSideSpec.getShuffleType() != ShuffleType.EXECUTION_BUCKETED
|| !(oneSidePlan instanceof GroupPlan)) {
return false;
} else {
PhysicalOlapScan candidate = findDownGradeBucketShuffleCandidate((GroupPlan) oneSidePlan);
if (candidate == null || candidate.getTable() == null
|| candidate.getTable().getDefaultDistributionInfo() == null) {
return false;
} else {
int prunedPartNum = candidate.getSelectedPartitionIds().size();
int bucketNum = candidate.getTable().getDefaultDistributionInfo().getBucketNum();
int totalBucketNum = prunedPartNum * bucketNum;
int backEndNum = Math.max(1, ConnectContext.get().getEnv().getClusterInfo()
.getBackendsNumber(true));
int paraNum = Math.max(1, ConnectContext.get().getSessionVariable().getParallelExecInstanceNum());
int totalParaNum = Math.min(10, backEndNum * paraNum);
return totalBucketNum < totalParaNum;
}
}
}
Code review comment: No, If the received exception message is not equal to those two strings it will anyway `throw exception;`. The problem was `exception.getMessage();` sometimes may be null, and then couldn't use `equals` method on `null`.

Code before review:
public DecimalValue(String value) {
if (isHexValueString(value)) {
this.value = hexToDecimalFloatingPointNumber(value);
} else {
try {
this.value = new BigDecimal(value, MathContext.DECIMAL128);
} catch (NumberFormatException exception) {
String message = exception.getMessage();
if ((message != null) && (message.equals("Too many nonzero exponent digits.") ||
message.equals("Exponent overflow."))) {
throw ErrorCreator.createError(BallerinaErrorReasons.LARGE_EXPONENT_ERROR,
BLangExceptionHelper.getErrorDetails(RuntimeErrors.LARGE_EXPONENTS_IN_DECIMAL, value));
}
throw exception;
}
}
if (!this.booleanValue()) {
this.valueKind = DecimalValueKind.ZERO;
}
}

Line under review: if ((message != null) && (message.equals("Too many nonzero exponent digits.") ||

Code after addressing the review:
public DecimalValue(String value) {
if (isHexValueString(value)) {
this.value = hexToDecimalFloatingPointNumber(value);
} else {
try {
this.value = new BigDecimal(value, MathContext.DECIMAL128);
} catch (NumberFormatException exception) {
String message = exception.getMessage();
if ((message != null) && (message.equals("Too many nonzero exponent digits.") ||
message.equals("Exponent overflow."))) {
throw ErrorCreator.createError(BallerinaErrorReasons.LARGE_EXPONENT_ERROR,
BLangExceptionHelper.getErrorDetails(RuntimeErrors.LARGE_EXPONENTS_IN_DECIMAL, value));
}
throw exception;
}
}
if (!this.booleanValue()) {
this.valueKind = DecimalValueKind.ZERO;
}
}
Code review comment: Just to understand it: The fatal error handler is used when running the cluster but not utilized when initializing it, isn't it? I was just wondering whether we should use the `fatalErrorHandler` here. But looking through the code made me conclude that it's not necessary because failure during startup are handled in the [ClusterEntrypoint#startCluster:197](https://github.com/apache/flink/blob/6b4f8a4dce08b2852cfea9db8b5dffff0712aac6/flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/ClusterEntrypoint.java#L197) and handled properly in `ClusterEntrypoint.runClusterEntrypoint`.

Code before review:
private MultipleComponentLeaderElectionService getOrInitializeSingleLeaderElectionService() {
if (multipleComponentLeaderElectionService == null) {
try {
multipleComponentLeaderElectionService =
new DefaultMultipleComponentLeaderElectionService(
fatalErrorHandler,
"Single leader election service.",
new ZooKeeperMultipleComponentLeaderElectionDriverFactory(
leaderNamespacedCuratorFramework));
} catch (Exception e) {
throw new FlinkRuntimeException(
String.format(
"Could not initialize the %s",
DefaultMultipleComponentLeaderElectionService.class
.getSimpleName()),
e);
}
}
return multipleComponentLeaderElectionService;
}

Line under review: throw new FlinkRuntimeException(

Code after addressing the review:
private MultipleComponentLeaderElectionService getOrInitializeSingleLeaderElectionService() {
synchronized (lock) {
if (multipleComponentLeaderElectionService == null) {
try {
multipleComponentLeaderElectionService =
new DefaultMultipleComponentLeaderElectionService(
fatalErrorHandler,
new ZooKeeperMultipleComponentLeaderElectionDriverFactory(
leaderNamespacedCuratorFramework));
} catch (Exception e) {
throw new FlinkRuntimeException(
String.format(
"Could not initialize the %s",
DefaultMultipleComponentLeaderElectionService.class
.getSimpleName()),
e);
}
}
return multipleComponentLeaderElectionService;
}
}
Code review comment: In general, I'm all for _not_ "hiding" versions in code, be it inline or constants. Even some of our explicit descriptors (e.g. codestarts IIRC) should be filtered by Maven instead.  The only downside I see with build-parent is that you end up building the entire project, although only a (tiny) fraction of modules is affected.

Code before review:
public String getEffectiveBuilderImage() {
final String builderImageName = this.builderImage.toUpperCase();
if (builderImageName.equals(BuilderImageProvider.GRAALVM.name())) {
return "quay.io/quarkus/ubi-quarkus-native-image:21.3-java11";
} else if (builderImageName.equals(BuilderImageProvider.MANDREL.name())) {
return "quay.io/quarkus/ubi-quarkus-mandrel:21.3-java11";
} else {
return this.builderImage;
}
}

Line under review: return "quay.io/quarkus/ubi-quarkus-mandrel:21.3-java11";

Code after addressing the review:
public String getEffectiveBuilderImage() {
final String builderImageName = this.builderImage.toUpperCase();
if (builderImageName.equals(BuilderImageProvider.GRAALVM.name())) {
return DEFAULT_GRAALVM_BUILDER_IMAGE;
} else if (builderImageName.equals(BuilderImageProvider.MANDREL.name())) {
return DEFAULT_MANDREL_BUILDER_IMAGE;
} else {
return this.builderImage;
}
}
Code review comment: Why do we need this change?

Code before review:
public void invoke(IN value, SinkFunction.Context context) throws Exception {
buckets.onElement(
value,
context.currentProcessingTime(),
context.timestamp(),
context.currentWatermark());
}

Line under review: buckets.onElement(

Code after addressing the review:
public void invoke(IN value, SinkFunction.Context context) throws Exception {
this.helper.onElement(
value,
context.currentProcessingTime(),
context.timestamp(),
context.currentWatermark());
}
Code review comment: check children.size() equal first to avoid index out of bound

Code before review:
public boolean equals(Object o) {
if (!(o instanceof MapLiteral)) {
return false;
}
if (this == o) {
return true;
}
MapLiteral that = (MapLiteral) o;
for (int i = 0; i < children.size(); i++) {
if (!children.get(i).equals(that.children.get(i))) {
return false;
}
}
return true;
}

Line under review: for (int i = 0; i < children.size(); i++) {

Code after addressing the review:
public boolean equals(Object o) {
if (!(o instanceof MapLiteral)) {
return false;
}
if (this == o) {
return true;
}
MapLiteral that = (MapLiteral) o;
return Objects.equals(children, that.children);
}
Code review comment: ```Files.readAllBytes``` was giving some errors

Code before review:
public void testAddAndRemoveExtension() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("add-remove-extension-single-module");
runGradleWrapper(projectDir, ":addExtension", "--extensions=hibernate-orm");
final Path Build = projectDir.toPath().resolve("build.gradle");
assertThat(Build).exists();
assertThat(Files.readString(Build)).contains("implementation 'io.quarkus:quarkus-hibernate-orm'");
runGradleWrapper(projectDir, ":removeExtension", "--extensions=hibernate-orm");
assertThat(Files.readString(Build)).doesNotContain("implementation 'io.quarkus:quarkus-hibernate-orm'");
}

Line under review: assertThat(Files.readString(Build)).contains("implementation 'io.quarkus:quarkus-hibernate-orm'");

Code after addressing the review:
public void testAddAndRemoveExtension() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("add-remove-extension-single-module");
runGradleWrapper(projectDir, ":addExtension", "--extensions=hibernate-orm");
final Path build = projectDir.toPath().resolve("build.gradle");
assertThat(build).exists();
assertThat(new String(Files.readAllBytes(build))).contains("implementation 'io.quarkus:quarkus-hibernate-orm'");
runGradleWrapper(projectDir, ":removeExtension", "--extensions=hibernate-orm");
assertThat(new String(Files.readAllBytes(build))).doesNotContain("implementation 'io.quarkus:quarkus-hibernate-orm'");
}