muttakin2301/ccr_train_1000 huggingface dataset:
Code review comment: Are these two lines necessary?  Because we haven't even call the `write` method, why do we care about them?

Code before review:
void testClose() {
int numSubpartitions = 10;
TestingTierProducerAgent tierProducerAgent = new TestingTierProducerAgent();
tierProducerAgent.setTryStartNewSegmentReturnValueSupplier(() -> true);
tierProducerAgent.setTryWriteReturnValueSupplier(() -> new Boolean[] {false, true});
assertThat(tierProducerAgent.isClosed()).isFalse();
TieredStorageProducerClient tieredStorageProducerClient =
createTieredStorageProducerClient(
numSubpartitions, Collections.singletonList(tierProducerAgent));
tieredStorageProducerClient.close();
assertThat(tierProducerAgent.isClosed()).isTrue();
}

Line under review: tierProducerAgent.setTryWriteReturnValueSupplier(() -> new Boolean[] {false, true});

Code after addressing the review:
void testClose() {
int numSubpartitions = 10;
AtomicBoolean isClosed = new AtomicBoolean(false);
TestingTierProducerAgent tierProducerAgent =
new TestingTierProducerAgent.Builder()
.setCloseRunnable(() -> isClosed.set(true))
.build();
TieredStorageProducerClient tieredStorageProducerClient =
createTieredStorageProducerClient(
numSubpartitions, Collections.singletonList(tierProducerAgent));
assertThat(isClosed.get()).isFalse();
tieredStorageProducerClient.close();
assertThat(isClosed.get()).isTrue();
}
Code review comment: `ArrayList<JarFile>` should be declared as `Collection<JarFile>`

Code before review:
public void assertInitPluginLifecycleService() {
Map<String, PluginConfiguration> pluginConfigs = new HashMap<>();
ArrayList<JarFile> pluginJars = new ArrayList<>();
PluginLifecycleServiceManager.init(pluginConfigs, pluginJars, new MultipleParentClassLoader(new ArrayList<>()),
true);
}

Line under review: ArrayList<JarFile> pluginJars = new ArrayList<>();

Code after addressing the review:
public void assertInitPluginLifecycleService() {
Map<String, PluginConfiguration> pluginConfigs = new HashMap<>();
Collection<JarFile> pluginJars = new LinkedList<>();
PluginLifecycleServiceManager.init(pluginConfigs, pluginJars, new MultipleParentClassLoader(new LinkedList<>()),
true);
}
Code review comment: Move the `() ->` down to the next line too, so it is `() -> listKeysFirstPage(),`

Code before review:
public PagedFlux<KeyBase> listKeys() {
return new PagedFlux<>(() -> listKeysFirstPage(),
continuationToken -> listKeysNextPage(continuationToken));
}

Line under review: continuationToken -> listKeysNextPage(continuationToken));

Code after addressing the review:
public PagedFlux<KeyBase> listKeys() {
return new PagedFlux<>(() ->
listKeysFirstPage(),
continuationToken -> listKeysNextPage(continuationToken));
}
Code review comment: Is this `if` check a relevant change to this bug fix? If not, could you please extract it to a separate hotfix commit in this PR to avoid confusions?

Code before review:
public void recycle(MemorySegment segment) {
Buffer releasedFloatingBuffer = null;
synchronized (bufferQueue) {
try {
if (inputChannel.isReleased()) {
globalPool.recycleMemorySegments(Collections.singletonList(segment));
} else {
releasedFloatingBuffer =
bufferQueue.addExclusiveBuffer(
new NetworkBuffer(segment, this), numRequiredBuffers);
}
} catch (Throwable t) {
ExceptionUtils.rethrow(t);
} finally {
bufferQueue.notifyAll();
}
}
try {
if (releasedFloatingBuffer == null) {
if (!inputChannel.isReleased()) {
inputChannel.notifyBufferAvailable(1);
}
} else {
releasedFloatingBuffer.recycleBuffer();
}
} catch (Throwable t) {
ExceptionUtils.rethrow(t);
}
}

Line under review: }

Code after addressing the review:
public void recycle(MemorySegment segment) {
@Nullable Buffer releasedFloatingBuffer = null;
synchronized (bufferQueue) {
try {
if (inputChannel.isReleased()) {
globalPool.recycleMemorySegments(Collections.singletonList(segment));
return;
} else {
releasedFloatingBuffer =
bufferQueue.addExclusiveBuffer(
new NetworkBuffer(segment, this), numRequiredBuffers);
}
} catch (Throwable t) {
ExceptionUtils.rethrow(t);
} finally {
bufferQueue.notifyAll();
}
}
if (releasedFloatingBuffer != null) {
releasedFloatingBuffer.recycleBuffer();
} else {
try {
inputChannel.notifyBufferAvailable(1);
} catch (Throwable t) {
ExceptionUtils.rethrow(t);
}
}
}
Code review comment: This should be performed after closing the output stream

Code before review:
private static void runCompressionGzip(File oldFile) {
File gzippedFile = new File(oldFile.getPath() + ".gz");
try (GZIPOutputStream compressor = new GZIPOutputStream(new FileOutputStream(gzippedFile), 0x100000);
FileInputStream inputStream = new FileInputStream(oldFile)) {
byte[] buffer = new byte[0x400000];
long totalBytesRead = 0;
NativeIO nativeIO = new NativeIO();
for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
compressor.write(buffer, 0, read);
nativeIO.dropPartialFileFromCache(inputStream.getFD(), totalBytesRead, read, false);
totalBytesRead += read;
}
compressor.finish();
compressor.flush();
oldFile.delete();
nativeIO.dropFileFromCache(gzippedFile);
} catch (IOException e) {
logger.warning("Got '" + e + "' while compressing '" + oldFile.getPath() + "'.");
}
}

Line under review: nativeIO.dropFileFromCache(gzippedFile);

Code after addressing the review:
private static void runCompressionGzip(File oldFile) {
File gzippedFile = new File(oldFile.getPath() + ".gz");
NativeIO nativeIO = new NativeIO();
try (GZIPOutputStream compressor = new GZIPOutputStream(new FileOutputStream(gzippedFile), 0x100000);
FileInputStream inputStream = new FileInputStream(oldFile)) {
byte[] buffer = new byte[0x400000];
long totalBytesRead = 0;
for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
compressor.write(buffer, 0, read);
nativeIO.dropPartialFileFromCache(inputStream.getFD(), totalBytesRead, read, false);
totalBytesRead += read;
}
compressor.finish();
compressor.flush();
} catch (IOException e) {
logger.warning("Got '" + e + "' while compressing '" + oldFile.getPath() + "'.");
}
oldFile.delete();
nativeIO.dropFileFromCache(gzippedFile);
}
Code review comment: Yeah, didn't want to add extra dependency :)  but yes, I agree. We could use that. 

Code before review:
private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) {
if (line.contains(versionStartTag) && line.contains("azure-cosmos")) {
int startIndex = line.indexOf(versionStartTag);
int endIndex = line.indexOf(versionEndTag);
return line.substring(startIndex + versionStartTag.length(), endIndex);
}
}
} catch (IOException e) {
throw new RuntimeException("Error reading file " + fileName, e);
}
return null;
}

Line under review: try {

Code after addressing the review:
private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) {
if (line.contains(versionStartTag) && line.contains("azure-cosmos")) {
int startIndex = line.indexOf(versionStartTag);
int endIndex = line.indexOf(versionEndTag);
return line.substring(startIndex + versionStartTag.length(), endIndex);
}
}
} catch (IOException e) {
throw new RuntimeException("Error reading file " + fileName, e);
}
return null;
}
Code review comment: Are you afraid that the `System.getProperty("user.home")` is cached at build time?

Code before review:
public String getObjectStoreDir() {
return System.getProperty("user.home") + File.separator + "ObjectStore";
}

Line under review: return System.getProperty("user.home") + File.separator + "ObjectStore";

Code after addressing the review:
public String getObjectStoreDir() {
return System.getProperty("user.home") + File.separator + "ObjectStore";
}
Code review comment: @IrushiL, Thank you for pointing out the issue here. Fixed the logical error. 

Code before review:
public XMLNamespaceDeclarationNode transform(XMLNamespaceDeclarationNode xMLNamespaceDeclarationNode) {
Token xmlnsKeyword = getToken(xMLNamespaceDeclarationNode.xmlnsKeyword());
ExpressionNode namespaceuri = this.modifyNode(xMLNamespaceDeclarationNode.namespaceuri());
Token asKeyword = getToken(xMLNamespaceDeclarationNode.asKeyword().orElse(null));
IdentifierToken namespacePrefix = this.modifyNode(xMLNamespaceDeclarationNode.namespacePrefix().orElse(null));
Token semicolonToken = getToken(xMLNamespaceDeclarationNode.semicolonToken());
if (asKeyword != null || namespacePrefix != null) {
xMLNamespaceDeclarationNode = xMLNamespaceDeclarationNode.modify()
.withNamespacePrefix(namespacePrefix)
.withAsKeyword(formatToken(asKeyword, 1, 1, 0, 0))
.apply();
}
return xMLNamespaceDeclarationNode.modify()
.withNamespaceuri(namespaceuri)
.withXmlnsKeyword(formatToken(xmlnsKeyword, 3, 1, 0, 0))
.withSemicolonToken(formatToken(semicolonToken, 0, 0, 0, 1))
.apply();
}

Line under review: if (asKeyword != null || namespacePrefix != null) {

Code after addressing the review:
public XMLNamespaceDeclarationNode transform(XMLNamespaceDeclarationNode xMLNamespaceDeclarationNode) {
Token xmlnsKeyword = getToken(xMLNamespaceDeclarationNode.xmlnsKeyword());
ExpressionNode namespaceuri = this.modifyNode(xMLNamespaceDeclarationNode.namespaceuri());
Token asKeyword = getToken(xMLNamespaceDeclarationNode.asKeyword().orElse(null));
IdentifierToken namespacePrefix = this.modifyNode(xMLNamespaceDeclarationNode.namespacePrefix().orElse(null));
Token semicolonToken = getToken(xMLNamespaceDeclarationNode.semicolonToken());
int startColumn = getStartColumn(xMLNamespaceDeclarationNode, xMLNamespaceDeclarationNode.kind(), true);
if (asKeyword != null) {
xMLNamespaceDeclarationNode = xMLNamespaceDeclarationNode.modify()
.withAsKeyword(formatToken(asKeyword, 1, 1, 0, 0))
.apply();
}
if (namespacePrefix != null) {
xMLNamespaceDeclarationNode = xMLNamespaceDeclarationNode.modify()
.withNamespacePrefix(namespacePrefix)
.apply();
}
return xMLNamespaceDeclarationNode.modify()
.withNamespaceuri(namespaceuri)
.withXmlnsKeyword(formatToken(xmlnsKeyword, startColumn, 1, 0, 0))
.withSemicolonToken(formatToken(semicolonToken, 0, 0, 0, 1))
.apply();
}
Code review comment: Good catch. I wasn't previously thinking about state restoring.  I think type serializer does need to be checkpointed and restored (code [link](https://github.com/apache/flink/blob/master/flink-runtime/src/main/java/org/apache/flink/runtime/state/StateSerializerProvider.java#L99))  I'm less sure about how type info serialization is used as I didn't manage to find a code reference for its usage.

Code before review:
private void writeObject(ObjectOutputStream oos) throws IOException {
byte[] schemaStrInBytes = schema.toString(false).getBytes(StandardCharsets.UTF_8);
oos.writeInt(schemaStrInBytes.length);
oos.write(schemaStrInBytes);
}

Line under review: byte[] schemaStrInBytes = schema.toString(false).getBytes(StandardCharsets.UTF_8);

Code after addressing the review:
private void writeObject(ObjectOutputStream oos) throws IOException {
byte[] schemaStrInBytes = schema.toString(false).getBytes(StandardCharsets.UTF_8);
oos.writeInt(schemaStrInBytes.length);
oos.write(schemaStrInBytes);
}
Code review comment: Can cpuPeriod() and cpuQuota() be updated to return long?

Code before review:
private CreateContainerCmd createCreateContainerCmd() {
List<Bind> volumeBinds = volumeBindSpecs.stream().map(Bind::parse).collect(Collectors.toList());
final HostConfig hostConfig = new HostConfig()
.withSecurityOpts(new ArrayList<>(securityOpts))
.withBinds(volumeBinds)
.withUlimits(ulimits)
.withCapAdd(addCapabilities.toArray(new Capability[0]))
.withCapDrop(dropCapabilities.toArray(new Capability[0]))
.withPrivileged(privileged);
containerResources.ifPresent(cr -> hostConfig
.withCpuShares(cr.cpuShares())
.withMemory(cr.memoryBytes())
.withMemorySwap(cr.memoryBytes())
.withCpuPeriod(cr.cpuQuota() > 0 ? (long) cr.cpuPeriod() : null)
.withCpuQuota(cr.cpuQuota() > 0 ? (long) cr.cpuQuota() : null));
final CreateContainerCmd containerCmd = docker
.createContainerCmd(dockerImage.asString())
.withHostConfig(hostConfig)
.withName(containerName.asString())
.withLabels(labels)
.withEnv(environmentAssignments);
networkMode
.filter(mode -> ! mode.toLowerCase().equals("host"))
.ifPresent(mode -> containerCmd.withMacAddress(generateMACAddress(hostName, ipv4Address, ipv6Address)));
hostName.ifPresent(containerCmd::withHostName);
networkMode.ifPresent(hostConfig::withNetworkMode);
ipv4Address.ifPresent(containerCmd::withIpv4Address);
ipv6Address.ifPresent(containerCmd::withIpv6Address);
entrypoint.ifPresent(containerCmd::withEntrypoint);
return containerCmd;
}

Line under review: .withCpuPeriod(cr.cpuQuota() > 0 ? (long) cr.cpuPeriod() : null)

Code after addressing the review:
private CreateContainerCmd createCreateContainerCmd() {
List<Bind> volumeBinds = volumeBindSpecs.stream().map(Bind::parse).collect(Collectors.toList());
final HostConfig hostConfig = new HostConfig()
.withSecurityOpts(new ArrayList<>(securityOpts))
.withBinds(volumeBinds)
.withUlimits(ulimits)
.withCapAdd(addCapabilities.toArray(new Capability[0]))
.withCapDrop(dropCapabilities.toArray(new Capability[0]))
.withPrivileged(privileged);
containerResources.ifPresent(cr -> hostConfig
.withCpuShares(cr.cpuShares())
.withMemory(cr.memoryBytes())
.withMemorySwap(cr.memoryBytes())
.withCpuPeriod(cr.cpuQuota() > 0 ? (long) cr.cpuPeriod() : null)
.withCpuQuota(cr.cpuQuota() > 0 ? (long) cr.cpuQuota() : null));
final CreateContainerCmd containerCmd = docker
.createContainerCmd(dockerImage.asString())
.withHostConfig(hostConfig)
.withName(containerName.asString())
.withLabels(labels)
.withEnv(environmentAssignments);
networkMode
.filter(mode -> ! mode.toLowerCase().equals("host"))
.ifPresent(mode -> containerCmd.withMacAddress(generateMACAddress(hostName, ipv4Address, ipv6Address)));
hostName.ifPresent(containerCmd::withHostName);
networkMode.ifPresent(hostConfig::withNetworkMode);
ipv4Address.ifPresent(containerCmd::withIpv4Address);
ipv6Address.ifPresent(containerCmd::withIpv6Address);
entrypoint.ifPresent(containerCmd::withEntrypoint);
return containerCmd;
}
Code review comment: I created a JIRA for this: https://issues.apache.org/jira/browse/BEAM-10611  Please add a TODO here such that we can make improvement on this in the future.

Code before review:
private static Value beamLogicalObjectToZetaSqlValue(Object object, String identifier) {
if (SqlTypes.DATE.getIdentifier().equals(identifier)) {
if (object instanceof Long) {
return Value.createDateValue(((Long) object).intValue());
} else {
return Value.createDateValue((int) ((LocalDate) object).toEpochDay());
}
} else if (SqlTypes.TIME.getIdentifier().equals(identifier)) {
if (object instanceof Long) {
return Value.createTimeValue(
CivilTimeEncoder.encodePacked64TimeNanos(LocalTime.ofNanoOfDay((Long) object)));
} else {
return Value.createTimeValue(CivilTimeEncoder.encodePacked64TimeNanos((LocalTime) object));
}
} else if (SqlTypes.DATETIME.getIdentifier().equals(identifier)) {
LocalDateTime datetime;
if (object instanceof Row) {
datetime =
LocalDateTime.of(
LocalDate.ofEpochDay(((Row) object).getValue("Date")),
LocalTime.ofNanoOfDay(((Row) object).getValue("Time")));
} else {
datetime = (LocalDateTime) object;
}
return Value.createDatetimeValue(
CivilTimeEncoder.encodePacked64DatetimeSeconds(datetime), datetime.getNano());
} else {
throw new UnsupportedOperationException("Unknown Beam logical type: " + identifier);
}
}

Line under review: return Value.createDatetimeValue(

Code after addressing the review:
private static Value beamLogicalObjectToZetaSqlValue(Object object, String identifier) {
if (SqlTypes.DATE.getIdentifier().equals(identifier)) {
if (object instanceof Long) {
return Value.createDateValue(((Long) object).intValue());
} else {
return Value.createDateValue((int) ((LocalDate) object).toEpochDay());
}
} else if (SqlTypes.TIME.getIdentifier().equals(identifier)) {
if (object instanceof Long) {
return Value.createTimeValue(
CivilTimeEncoder.encodePacked64TimeNanos(LocalTime.ofNanoOfDay((Long) object)));
} else {
return Value.createTimeValue(CivilTimeEncoder.encodePacked64TimeNanos((LocalTime) object));
}
} else if (SqlTypes.DATETIME.getIdentifier().equals(identifier)) {
LocalDateTime datetime;
if (object instanceof Row) {
datetime =
LocalDateTime.of(
LocalDate.ofEpochDay(((Row) object).getInt64(DateTime.DATE_FIELD_NAME)),
LocalTime.ofNanoOfDay(((Row) object).getInt64(DateTime.TIME_FIELD_NAME)));
} else {
datetime = (LocalDateTime) object;
}
return Value.createDatetimeValue(
CivilTimeEncoder.encodePacked64DatetimeSeconds(datetime), datetime.getNano());
} else {
throw new UnsupportedOperationException("Unknown Beam logical type: " + identifier);
}
}
Code review comment: As of now, no. We may eventually need to support both import and provided but currently we have no use case for them.

Code before review:
static List<BomDependency> parsePomFileContent(Reader responseStream) {
List<BomDependency> bomDependencies = new ArrayList<>();
ObjectMapper mapper = new XmlMapper();
try {
HashMap<String, Object> value = mapper.readValue(responseStream, HashMap.class);
Object packagingProp = value.getOrDefault("packaging", null);
if(packagingProp != null && packagingProp.toString().equalsIgnoreCase("pom")) {
return parsePomFileContent(responseStream);
}
HashMap<String, Object> dependenciesTag = (HashMap<String, Object>)value.getOrDefault("dependencies", null);
if(dependenciesTag == null) {
return null;
}
ArrayList<HashMap<String, Object>> dependencies =  (ArrayList<HashMap<String, Object>>) dependenciesTag.getOrDefault("dependency", null);
for(HashMap<String, Object> dependency: dependencies) {
String groupId = (String) dependency.getOrDefault("groupId", null);
String artifactId = (String) dependency.getOrDefault("artifactId", null);
String version = (String) dependency.getOrDefault("version", null);
String scope = (String) dependency.getOrDefault("scope", ScopeType.COMPILE.toString());
ScopeType scopeType = ScopeType.COMPILE;
switch(scope) {
case "test" : scopeType = ScopeType.TEST;
break;
default: scopeType = ScopeType.COMPILE;
}
bomDependencies.add(new BomDependency(groupId, artifactId, version, scopeType));
}
} catch (IOException exception) {
exception.printStackTrace();
}
return bomDependencies.stream().distinct().collect(Collectors.toList());
}

Line under review: default: scopeType = ScopeType.COMPILE;

Code after addressing the review:
static List<BomDependency> parsePomFileContent(Reader responseStream) {
List<BomDependency> bomDependencies = new ArrayList<>();
ObjectMapper mapper = new XmlMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
Model value = mapper.readValue(responseStream, Model.class);
List<Dependency> dependencies = value.getDependencies();
if(dependencies == null) {
return bomDependencies;
}
for(Dependency dependency : dependencies) {
ScopeType scopeType = ScopeType.COMPILE;
if("test".equals(dependency.getScope())) {
scopeType = ScopeType.TEST;
}
bomDependencies.add(new BomDependency(
dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getVersion(),
scopeType));
}
} catch (IOException exception) {
exception.printStackTrace();
}
return bomDependencies.stream().distinct().collect(Collectors.toList());
}
Code review comment: With 864788ea19e77a6292976f2b999a8c933034371d we simply rewrite the build file

Code before review:
public void save() {
Path buildFilePath = this.sourceRoot.resolve(TARGET_DIR_NAME).resolve(BUILD_FILE);
boolean shouldUpdate = this.currentPackage().getResolution().autoUpdate();
if (!buildFilePath.toFile().exists()) {
createBuildFile(buildFilePath);
writeBuildFile(buildFilePath);
writeDependencies();
} else {
try {
BuildJson buildJson = readBuildJson(buildFilePath);
writeDependencies();
if (buildJson != null) {
if (shouldUpdate) {
writeBuildFile(buildFilePath);
} else {
buildJson.setLastBuildTime(System.currentTimeMillis());
ProjectUtils.writeBuildFile(buildFilePath, buildJson);
}
} else {
writeBuildFile(buildFilePath);
}
} catch (JsonSyntaxException e) {
throw new ProjectException("Invalid '" + BUILD_FILE + "' file format");
} catch (IOException e) {
throw new ProjectException("Failed to read the '" + BUILD_FILE + "' file");
}
}
}

Line under review: writeDependencies();

Code after addressing the review:
public void save() {
Path buildFilePath = this.sourceRoot.resolve(TARGET_DIR_NAME).resolve(BUILD_FILE);
boolean shouldUpdate = this.currentPackage().getResolution().autoUpdate();
if (!buildFilePath.toFile().exists()) {
createBuildFile(buildFilePath);
writeBuildFile(buildFilePath);
writeDependencies();
} else {
BuildJson buildJson = null;
try {
buildJson = readBuildJson(buildFilePath);
} catch (JsonSyntaxException | IOException e) {
}
writeDependencies();
if (buildJson != null && !shouldUpdate) {
buildJson.setLastBuildTime(System.currentTimeMillis());
writeBuildFile(buildFilePath, buildJson);
} else {
writeBuildFile(buildFilePath);
}
}
}
Code review comment: Can you modify the kernel logic instead of sql parse logic?

Code before review:
private BinaryOperationExpression createPatternMatchingOperationSegment(final AExprContext ctx) {
String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();
ExpressionSegment left = (ExpressionSegment) visit(ctx.aExpr(0));
ListExpression right = new ListExpression(ctx.aExpr(1).start.getStartIndex(), ctx.aExpr().get(ctx.aExpr().size() - 1).stop.getStopIndex());
for (int i = 1; i < ctx.aExpr().size(); i++) {
right.getItems().add((ExpressionSegment) visit(ctx.aExpr().get(i)));
}
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
return new BinaryOperationExpression(ctx.start.getStartIndex(), ctx.stop.getStopIndex(), left, right, operator, text);
}

Line under review: String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();

Code after addressing the review:
private BinaryOperationExpression createPatternMatchingOperationSegment(final AExprContext ctx) {
String operator = getOriginalText(ctx.patternMatchingOperator()).toUpperCase();
ExpressionSegment left = (ExpressionSegment) visit(ctx.aExpr(0));
ListExpression right = new ListExpression(ctx.aExpr(1).start.getStartIndex(), ctx.aExpr().get(ctx.aExpr().size() - 1).stop.getStopIndex());
for (int i = 1; i < ctx.aExpr().size(); i++) {
right.getItems().add((ExpressionSegment) visit(ctx.aExpr().get(i)));
}
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
return new BinaryOperationExpression(ctx.start.getStartIndex(), ctx.stop.getStopIndex(), left, right, operator, text);
}
Code review comment: do we need to validate whether exception is CosmosException? 

Code before review:
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
if (this.request == null) {
logger.error("onBeforeSendRequest has not been invoked with the MetadataRequestRetryPolicy...");
return Mono.just(ShouldRetryResult.error(e));
}
CosmosException cosmosException = Utils.as(e, CosmosException.class);
if (shouldMarkRegionAsUnavailable(cosmosException)) {
URI locationEndpointToRoute = request.requestContext.locationEndpointToRoute;
if (request.isReadOnlyRequest()) {
this.globalEndpointManager.markEndpointUnavailableForRead(locationEndpointToRoute);
} else {
this.globalEndpointManager.markEndpointUnavailableForWrite(locationEndpointToRoute);
}
}
return Mono.just(ShouldRetryResult.error(cosmosException));
}

Line under review: CosmosException cosmosException = Utils.as(e, CosmosException.class);

Code after addressing the review:
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
return webExceptionRetryPolicy.shouldRetry(e).flatMap(shouldRetryResult -> {
if (!shouldRetryResult.shouldRetry) {
if (this.request == null || this.webExceptionRetryPolicy == null) {
logger.error("onBeforeSendRequest has not been invoked with the MetadataRequestRetryPolicy...");
return Mono.just(ShouldRetryResult.error(e));
}
if (!(e instanceof CosmosException)) {
logger.debug("exception is not an instance of CosmosException...");
return Mono.just(ShouldRetryResult.error(e));
}
CosmosException cosmosException = Utils.as(e, CosmosException.class);
if (shouldMarkRegionAsUnavailable(cosmosException)) {
URI locationEndpointToRoute = request.requestContext.locationEndpointToRoute;
if (request.isReadOnlyRequest()) {
this.globalEndpointManager.markEndpointUnavailableForRead(locationEndpointToRoute);
} else {
this.globalEndpointManager.markEndpointUnavailableForWrite(locationEndpointToRoute);
}
}
return Mono.just(ShouldRetryResult.error(cosmosException));
}
return Mono.just(shouldRetryResult);
});
}
Code review comment: Add a rule to check whether this jar exists

Code before review:
public static URLClassLoader getClassLoader(String jarPath, ClassLoader parent) throws MalformedURLException {
URL url = new URL(jarPath);
return URLClassLoader.newInstance(new URL[] {url}, parent);
}

Line under review: URL url = new URL(jarPath);

Code after addressing the review:
public static URLClassLoader getClassLoader(String jarPath, ClassLoader parent)
throws MalformedURLException, FileNotFoundException {
File file = new File(jarPath);
if (!file.exists()) {
throw new FileNotFoundException("Can not find local file: " + jarPath);
}
URL url = file.toURI().toURL();
return URLClassLoader.newInstance(new URL[] {url}, parent);
}
Code review comment: nit: shorter branch first is slightly easier to read

Code before review:
private Schema payloadSchema() {
if (useFlatSchema()) {
Schema.Builder builder = Schema.builder();
for (Schema.Field field : messageSchema().getFields()) {
if (field.getName().equals(TIMESTAMP_FIELD)) {
continue;
}
builder.addField(field);
}
return builder.build();
} else {
return messageSchema().getField(PAYLOAD_FIELD).getType().getRowSchema();
}
}

Line under review: continue;

Code after addressing the review:
private Schema payloadSchema() {
if (!useFlatSchema()) {
return messageSchema().getField(PAYLOAD_FIELD).getType().getRowSchema();
} else {
return new Schema(
messageSchema().getFields().stream()
.filter(f -> !f.getName().equals(TIMESTAMP_FIELD))
.collect(Collectors.toList()));
}
}
Code review comment: Is it valid when no Condition, or no Action?  If it is valid, should we let user create without calling them? Would avoid user write `define...().withMatchConditions().withActions().attach()`

Code before review:
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) {
List<DeliveryRuleAction> actionList = new ArrayList<>();
if (actions != null) {
actionList.addAll(Arrays.asList(actions));
}
innerModel().withActions(actionList);
return this;
}

Line under review: }

Code after addressing the review:
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) {
List<DeliveryRuleAction> actionList = new ArrayList<>();
if (actions != null) {
actionList.addAll(Arrays.asList(actions));
}
innerModel().withActions(actionList);
return this;
}
Code review comment: Shouldn't we reset the original TCCL after the command is run?

Code before review:
public void run(Runnable command) {
Thread.currentThread().setContextClassLoader(classLoader);
command.run();
}

Line under review: command.run();

Code after addressing the review:
public void run(Runnable command) {
ClassLoader originalTccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
command.run();
} finally {
Thread.currentThread().setContextClassLoader(originalTccl);
}
}
Code review comment: According with documentation, I could do just this. Tell me what do you think.   ```         Path artifact = target.getOutputDirectory().resolve(name);         File file = new File(artifact.toString());         file.setExecutable(true, true); ```

Code before review:
public static void writeExecutableFile(OutputTargetBuildItem target, String name, String output) throws IOException {
writeFile(target, name, output);
Path artifact = target.getOutputDirectory().resolve(name);
Set<PosixFilePermission> permissions = new HashSet<>();
permissions.add(PosixFilePermission.OWNER_READ);
permissions.add(PosixFilePermission.OWNER_WRITE);
permissions.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(artifact, permissions);
}

Line under review: Files.setPosixFilePermissions(artifact, permissions);

Code after addressing the review:
public static void writeExecutableFile(OutputTargetBuildItem target, String name, String output) throws IOException {
writeFile(target, name, output);
Path artifact = target.getOutputDirectory().resolve(name);
artifact.toFile().setExecutable(true, true);
}
Code review comment: This comment seems out of place, no?

Code before review:
public Enumeration<URL> getResources(String nm) throws IOException {
ClassLoaderState state = getState();
String name = sanitizeName(nm);
boolean banned = state.bannedResources.contains(name);
Set<URL> resources = new LinkedHashSet<>();
if (name.startsWith(META_INF_SERVICES)) {
try {
Class<?> c = loadClass(name.substring(META_INF_SERVICES.length()));
if (c.getClassLoader() == this) {
banned = true;
}
} catch (ClassNotFoundException ignored) {
}
}
for (ClassPathElement i : elements) {
ClassPathResource res = i.getResource(nm);
if (res != null) {
resources.add(res.getUrl());
}
}
if (!banned) {
if (resources.isEmpty() || aggregateParentResources) {
Enumeration<URL> res = parent.getResources(nm);
while (res.hasMoreElements()) {
resources.add(res.nextElement());
}
}
}
return Collections.enumeration(resources);
}


Code after addressing the review:
public Enumeration<URL> getResources(String nm) throws IOException {
ClassLoaderState state = getState();
String name = sanitizeName(nm);
boolean banned = state.bannedResources.contains(name);
Set<URL> resources = new LinkedHashSet<>();
if (name.startsWith(META_INF_SERVICES)) {
try {
Class<?> c = loadClass(name.substring(META_INF_SERVICES.length()));
if (c.getClassLoader() == this) {
banned = true;
}
} catch (ClassNotFoundException ignored) {
}
}
for (ClassPathElement i : elements) {
ClassPathResource res = i.getResource(nm);
if (res != null) {
resources.add(res.getUrl());
}
}
if (!banned) {
if (resources.isEmpty() || aggregateParentResources) {
Enumeration<URL> res = parent.getResources(nm);
while (res.hasMoreElements()) {
resources.add(res.nextElement());
}
}
}
return Collections.enumeration(resources);
}
Code review comment: Why do we need this exactly?

Code before review:
public Receive createReceive() {
return ReceiveBuilder.create()
.match(
RemoteHandshakeMessage.class,
withCleanContextClassLoader(this::handleHandshakeMessage))
.match(
ControlMessages.class,
withCleanContextClassLoader(this::handleControlMessage))
.matchAny(withCleanContextClassLoader(this::handleMessage))
.build();
}

Line under review: .matchAny(withCleanContextClassLoader(this::handleMessage))

Code after addressing the review:
public Receive createReceive() {
return ReceiveBuilder.create()
.match(RemoteHandshakeMessage.class, this::handleHandshakeMessage)
.match(ControlMessages.class, this::handleControlMessage)
.matchAny(this::handleMessage)
.build();
}
Code review comment: I see 2 paths above for assigning to `from`:  ```     String from =         String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());      if (!Strings.isNullOrEmpty(options.getPrismLocation())) {       checkArgument(           !options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),           "Provided --prismLocation URL is not an Apache Beam Github "               + "Release page URL or download URL: ",           from);        from = options.getPrismLocation();     } ```  In either of these assignments are followed, won't `from` start with either `GITHUB_DOWNLOAD_PREFIX` or `GITHUB_TAG_PREFIX` which both start with `https://`?

Code before review:
String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache Beam Github "
+ "Release page URL or download URL: ",
from);
from = options.getPrismLocation();
}
String fromFileName = getNameWithoutExtension(from);
Path to = Paths.get(userHome(), PRISM_BIN_PATH, fromFileName);
if (Files.exists(to)) {
return to.toString();
}
createDirectoryIfNeeded(to);
if (from.startsWith("http")) {
String result = resolve(new URL(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
String result = resolve(Paths.get(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}

Line under review: if (from.startsWith("http")) {

Code after addressing the review:
String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache Beam Github "
+ "Release page URL or download URL: ",
from);
from = options.getPrismLocation();
}
String fromFileName = getNameWithoutExtension(from);
Path to = Paths.get(userHome(), PRISM_BIN_PATH, fromFileName);
if (Files.exists(to)) {
return to.toString();
}
createDirectoryIfNeeded(to);
if (from.startsWith("http")) {
String result = resolve(new URL(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
String result = resolve(Paths.get(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
Code review comment: I don't think the comment `// this is not used any more in the new scheduler` is needed. It would not be consistent to comment here because there is another invocation of this constructor where we do not comment. I would remove the parameters `slotProvider` and `slotRequestTimeout` from the `DefaultScheduler`, and if possible pass a _"throwing"_ implementation/invalid value to `SchedulerBase`.

Code before review:
public DefaultScheduler build() throws Exception {
return new DefaultScheduler(
log,
jobGraph,
backPressureStatsTracker,
ioExecutor,
jobMasterConfiguration,
new SimpleSlotProvider(jobGraph.getJobID(), 0),
futureExecutor,
delayExecutor,
userCodeLoader,
checkpointRecoveryFactory,
rpcTimeout,
blobWriter,
jobManagerJobMetricGroup,
DEFAULT_TIMEOUT,
shuffleMaster,
partitionTracker,
schedulingStrategyFactory,
failoverStrategyFactory,
restartBackoffTimeStrategy,
executionVertexOperations,
executionVertexVersioner,
executionSlotAllocatorFactory);
}

Line under review: new SimpleSlotProvider(jobGraph.getJobID(), 0),

Code after addressing the review:
public DefaultScheduler build() throws Exception {
return new DefaultScheduler(
log,
jobGraph,
backPressureStatsTracker,
ioExecutor,
jobMasterConfiguration,
futureExecutor,
delayExecutor,
userCodeLoader,
checkpointRecoveryFactory,
rpcTimeout,
blobWriter,
jobManagerJobMetricGroup,
shuffleMaster,
partitionTracker,
schedulingStrategyFactory,
failoverStrategyFactory,
restartBackoffTimeStrategy,
executionVertexOperations,
executionVertexVersioner,
executionSlotAllocatorFactory);
}
Code review comment: Shall we move this to a constant?

Code before review:
public static Object removeIfHasKey(Strand strand, MapValue<?, ?> m, String k) {
String op = "removeIfHasKey()";
checkIsMapOnlyOperation(m.getType(), op);
checkValidFieldForRecord(m, k, op);
try {
return m.remove(k);
} catch (org.ballerinalang.jvm.util.exceptions.BLangFreezeException e) {
throw BallerinaErrors.createError(e.getMessage(),
"Failed to remove element from map: " + e.getDetail());
}
}

Line under review: String op = "removeIfHasKey()";

Code after addressing the review:
public static Object removeIfHasKey(Strand strand, MapValue<?, ?> m, String k) {
String op = Constants.REMOVE_IF_HAS_KEY;
checkIsMapOnlyOperation(m.getType(), op);
checkValidFieldForRecord(m, k, op);
try {
return m.remove(k);
} catch (org.ballerinalang.jvm.util.exceptions.BLangFreezeException e) {
throw BallerinaErrors.createError(e.getMessage(),
"Failed to remove element from map: " + e.getDetail());
}
}
Code review comment: Hmm I wonder how are we going to handle parallel artifact upload streams in the future. Fine to leave as a TODO for now, I suspect it'd require some small API changes.

Code before review:
public void onNext(PutArtifactRequest putArtifactRequest) {
if (metadata == null) {
metadata = putArtifactRequest.getMetadata();
try {
ResourceId artifactsDirId = getArtifactDirResourceId(
putArtifactRequest.getMetadata().getStagingSessionToken());
LOG.info("Going to stage artifact {} in {}.", metadata.getMetadata().getName(),
artifactsDirId);
artifactId = artifactsDirId
.resolve(encodedFileName(metadata.getMetadata()),
StandardResolveOptions.RESOLVE_FILE);
artifactWritableByteChannel = FileSystems.create(artifactId, MimeTypes.BINARY);
} catch (IOException e) {
LOG.error("Staging failed for artifact {} for staging token {}",
encodedFileName(metadata.getMetadata()), metadata.getStagingSessionToken());
outboundObserver.onError(e);
}
} else {
try {
artifactWritableByteChannel
.write(putArtifactRequest.getData().getData().asReadOnlyByteBuffer());
} catch (IOException e) {
LOG.error("Staging failed for artifact {} to file {}.", metadata.getMetadata().getName(),
artifactId);
outboundObserver.onError(e);
}
}
}


Code after addressing the review:
public void onNext(PutArtifactRequest putArtifactRequest) {
if (metadata == null) {
checkNotNull(putArtifactRequest);
checkNotNull(putArtifactRequest.getMetadata());
metadata = putArtifactRequest.getMetadata();
try {
ResourceId artifactsDirId = getArtifactDirResourceId(
putArtifactRequest.getMetadata().getStagingSessionToken());
artifactId = artifactsDirId.resolve(encodedFileName(metadata.getMetadata()),
StandardResolveOptions.RESOLVE_FILE);
LOG.info("Going to stage artifact {} to {}.", metadata.getMetadata().getName(),
artifactId);
artifactWritableByteChannel = FileSystems.create(artifactId, MimeTypes.BINARY);
} catch (Exception e) {
LOG.error("Staging failed for artifact {} for staging token {}",
encodedFileName(metadata.getMetadata()), metadata.getStagingSessionToken());
outboundObserver.onError(e);
}
} else {
try {
artifactWritableByteChannel
.write(putArtifactRequest.getData().getData().asReadOnlyByteBuffer());
} catch (IOException e) {
LOG.error("Staging failed for artifact {} to file {}.", metadata.getMetadata().getName(),
artifactId);
outboundObserver.onError(e);
}
}
}
Code review comment: If we're using this private method in `restRead` too, it should go below it to be more readable. Could you move this?

Code before review:
private void testWrite() {
Pipeline pipeline = Pipeline.create(options);
BigQueryIO.Write.Method method = BigQueryIO.Write.Method.valueOf(writeMethod);
pipeline
.apply("Read from source", Read.from(new SyntheticBoundedSource(sourceOptions)))
.apply("Gather time", ParDo.of(new TimeMonitor<>(NAMESPACE, WRITE_TIME_METRIC_NAME)))
.apply("Map records", ParDo.of(new MapKVToV()))
.apply(
"Write to BQ",
BigQueryIO.<byte[]>write()
.to(tableQualifier)
.withFormatFunction(
input -> {
TableRow tableRow = new TableRow();
tableRow.set("data", input);
return tableRow;
})
.withCustomGcsTempLocation(ValueProvider.StaticValueProvider.of(tempRoot))
.withMethod(method)
.withSchema(
new TableSchema()
.setFields(
Collections.singletonList(
new TableFieldSchema().setName("data").setType("BYTES")))));
PipelineResult pipelineResult = pipeline.run();
pipelineResult.waitUntilFinish();
extractAndPublishTime(pipelineResult, WRITE_TIME_METRIC_NAME);
}

Line under review: .apply("Read from source", Read.from(new SyntheticBoundedSource(sourceOptions)))

Code after addressing the review:
private void testWrite() {
Pipeline pipeline = Pipeline.create(options);
BigQueryIO.Write.Method method = BigQueryIO.Write.Method.valueOf(options.getWriteMethod());
pipeline
.apply("Read from source", Read.from(new SyntheticBoundedSource(sourceOptions)))
.apply("Gather time", ParDo.of(new TimeMonitor<>(NAMESPACE, WRITE_TIME_METRIC_NAME)))
.apply("Map records", ParDo.of(new MapKVToV()))
.apply(
"Write to BQ",
BigQueryIO.<byte[]>write()
.to(tableQualifier)
.withFormatFunction(
input -> {
TableRow tableRow = new TableRow();
tableRow.set("data", input);
return tableRow;
})
.withCustomGcsTempLocation(ValueProvider.StaticValueProvider.of(tempRoot))
.withMethod(method)
.withSchema(
new TableSchema()
.setFields(
Collections.singletonList(
new TableFieldSchema().setName("data").setType("BYTES")))));
PipelineResult pipelineResult = pipeline.run();
pipelineResult.waitUntilFinish();
extractAndPublishTime(pipelineResult, WRITE_TIME_METRIC_NAME);
}
Code review comment: This logic won't be required anymore.

Code before review:
private void setCurrentReader(int index) {
Preconditions.checkArgument(index != currentSourceIndex);
if (currentReader != null) {
try {
currentReader.close();
} catch (Exception e) {
throw new RuntimeException("Failed to close current reader", e);
}
LOG.debug(
"Reader closed: subtask={} sourceIndex={} currentReader={}",
readerContext.getIndexOfSubtask(),
currentSourceIndex,
currentReader);
}
Source source = switchedSources.sourceOf(index);
SourceReader<T, ?> reader;
try {
reader = source.createReader(readerContext);
} catch (Exception e) {
throw new RuntimeException("Failed tp create reader", e);
}
reader.start();
currentSourceIndex = index;
currentReader = reader;
completeAndResetAvailabilityHelper();
LOG.debug(
"Reader started: subtask={} sourceIndex={} {}",
readerContext.getIndexOfSubtask(),
currentSourceIndex,
reader);
if (!restoredSplits.isEmpty()) {
List<HybridSourceSplit> splits = new ArrayList<>(restoredSplits.size());
Iterator<HybridSourceSplit> it = restoredSplits.iterator();
while (it.hasNext()) {
HybridSourceSplit hybridSplit = it.next();
if (hybridSplit.sourceIndex() == index) {
splits.add(hybridSplit);
it.remove();
}
}
addSplits(splits);
}
}

Line under review: completeAndResetAvailabilityHelper();

Code after addressing the review:
private void setCurrentReader(int index) {
Preconditions.checkArgument(index != currentSourceIndex);
if (currentReader != null) {
try {
currentReader.close();
} catch (Exception e) {
throw new RuntimeException("Failed to close current reader", e);
}
LOG.debug(
"Reader closed: subtask={} sourceIndex={} currentReader={}",
readerContext.getIndexOfSubtask(),
currentSourceIndex,
currentReader);
}
Source source = switchedSources.sourceOf(index);
SourceReader<T, ?> reader;
try {
reader = source.createReader(readerContext);
} catch (Exception e) {
throw new RuntimeException("Failed tp create reader", e);
}
reader.start();
currentSourceIndex = index;
currentReader = reader;
availabilityFuture.complete(null);
LOG.debug(
"Reader started: subtask={} sourceIndex={} {}",
readerContext.getIndexOfSubtask(),
currentSourceIndex,
reader);
if (!restoredSplits.isEmpty()) {
List<HybridSourceSplit> splits = new ArrayList<>(restoredSplits.size());
Iterator<HybridSourceSplit> it = restoredSplits.iterator();
while (it.hasNext()) {
HybridSourceSplit hybridSplit = it.next();
if (hybridSplit.sourceIndex() == index) {
splits.add(hybridSplit);
it.remove();
}
}
addSplits(splits);
}
}
Code review comment: Shall we call `analyzeNode` instead? ```suggestion         conversionExpr.annAttachments.forEach(annotationAttachment -> analyzeNode(annotationAttachment, env)); ```

Code before review:
public void visit(BLangTypeConversionExpr conversionExpr) {
analyzeExpr(conversionExpr.expr);
conversionExpr.annAttachments.forEach(annotationAttachment -> annotationAttachment.accept(this));
}

Line under review: conversionExpr.annAttachments.forEach(annotationAttachment -> annotationAttachment.accept(this));

Code after addressing the review:
public void visit(BLangTypeConversionExpr conversionExpr) {
analyzeExpr(conversionExpr.expr);
conversionExpr.annAttachments.forEach(annotationAttachment -> analyzeNode(annotationAttachment, env));
}
Code review comment: the purpose of `getCreateDocumentRequest` is just to create the request. retry-policy interaction should happen outside. why are we moving this?

Code before review:
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PUT);
if(request.requestContext != null && documentClientRetryPolicy.getRetryCount() > 0) {
documentClientRetryPolicy.updateEndTime();
request.requestContext.updateRetryContext(documentClientRetryPolicy, true);
}
return getStoreProxy(request).processMessage(request);
}

Line under review: return getStoreProxy(request).processMessage(request);

Code after addressing the review:
private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) {
populateHeaders(request, RequestVerb.PUT);
if(request.requestContext != null && documentClientRetryPolicy.getRetryCount() > 0) {
documentClientRetryPolicy.updateEndTime();
request.requestContext.updateRetryContext(documentClientRetryPolicy, true);
}
return getStoreProxy(request).processMessage(request);
}
Code review comment: These are [already cleared](https://github.com/ballerina-platform/ballerina-lang/blob/274e1dca660da80cc2854bbba37cec60a9b51acb/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java#L3527) at the end of this method though, via [`inferIsolation`](https://github.com/ballerina-platform/ballerina-lang/blob/274e1dca660da80cc2854bbba37cec60a9b51acb/compiler/ballerina-lang/src/main/java/org/wso2/ballerinalang/compiler/semantics/analyzer/IsolationAnalyzer.java#L332).

Code before review:
public BLangPackage analyze(BLangPackage pkgNode) {
this.arrowFunctionTempSymbolMap.clear();
this.isolationInferenceInfoMap.clear();
this.dlog.setCurrentPackageId(pkgNode.packageID);
SymbolEnv pkgEnv = this.symTable.pkgEnvMap.get(pkgNode.symbol);
Set<BSymbol> moduleLevelVarSymbols = getModuleLevelVarSymbols(pkgNode.globalVars);
populateNonPublicMutableOrNonIsolatedVars(moduleLevelVarSymbols);
List<BLangClassDefinition> classDefinitions = pkgNode.classDefinitions;
populateNonPublicIsolatedInferableClasses(classDefinitions);
analyzeNode(pkgNode, pkgEnv);
inferIsolation(moduleLevelVarSymbols, getPubliclyExposedObjectTypes(pkgNode), classDefinitions);
logServiceIsolationWarnings(classDefinitions);
return pkgNode;
}

Line under review: this.isolationInferenceInfoMap.clear();

Code after addressing the review:
public BLangPackage analyze(BLangPackage pkgNode) {
this.arrowFunctionTempSymbolMap.clear();
this.isolationInferenceInfoMap.clear();
this.dlog.setCurrentPackageId(pkgNode.packageID);
SymbolEnv pkgEnv = this.symTable.pkgEnvMap.get(pkgNode.symbol);
Set<BSymbol> moduleLevelVarSymbols = getModuleLevelVarSymbols(pkgNode.globalVars);
populateNonPublicMutableOrNonIsolatedVars(moduleLevelVarSymbols);
List<BLangClassDefinition> classDefinitions = pkgNode.classDefinitions;
populateNonPublicIsolatedInferableClasses(classDefinitions);
analyzeNode(pkgNode, pkgEnv);
inferIsolation(moduleLevelVarSymbols, getPubliclyExposedObjectTypes(pkgNode), classDefinitions);
logServiceIsolationWarnings(classDefinitions);
return pkgNode;
}
Code review comment: Hi, there is problem in here. When we are loading image, we shouldn't write the editLog, or else some error will report (Because bdbje is open only after the image has been loaded).

Code before review:
public static DeleteHandler read(DataInput in) throws IOException {
String json = Text.readString(in);
DeleteHandler deleteHandler = GsonUtils.GSON.fromJson(json, DeleteHandler.class);
deleteHandler.removeOldDeleteInfos();
return deleteHandler;
}

Line under review: return deleteHandler;

Code after addressing the review:
public static DeleteHandler read(DataInput in) throws IOException {
String json = Text.readString(in);
DeleteHandler deleteHandler = GsonUtils.GSON.fromJson(json, DeleteHandler.class);
deleteHandler.removeOldDeleteInfos(new Timestamp());
return deleteHandler;
}