yashmayya commented on code in PR #17028:
URL: https://github.com/apache/pinot/pull/17028#discussion_r2467172926


##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/SegmentIndexCreationDriverImpl.java:
##########
@@ -578,10 +578,26 @@ private void buildStarTreeV2IfNecessary(File indexDir)
     if (CollectionUtils.isNotEmpty(starTreeIndexConfigs) || 
enableDefaultStarTree) {
       MultipleTreesBuilder.BuildMode buildMode =
           _config.isOnHeap() ? MultipleTreesBuilder.BuildMode.ON_HEAP : 
MultipleTreesBuilder.BuildMode.OFF_HEAP;
-      try (
-          MultipleTreesBuilder builder = new 
MultipleTreesBuilder(starTreeIndexConfigs, enableDefaultStarTree, indexDir,
-              buildMode)) {
+      MultipleTreesBuilder builder = new 
MultipleTreesBuilder(starTreeIndexConfigs, enableDefaultStarTree, indexDir,
+          buildMode);
+      try {
         builder.build();
+      } catch (Exception e) {
+        String tableNameWithType = _config.getTableConfig().getTableName();
+        LOGGER.error("Failed to build star-tree index for table: {}, 
skipping", tableNameWithType, e);
+        if (_instanceType == InstanceType.MINION) {
+          MinionMetrics.get().addMeteredTableValue(tableNameWithType, 
MinionMeter.STAR_TREE_INDEX_BUILD_FAILURES, 1);
+        } else {
+          ServerMetrics.get().addMeteredTableValue(tableNameWithType, 
ServerMeter.STAR_TREE_INDEX_BUILD_FAILURES, 1);
+        }
+      } finally {
+        try {
+          builder.close();
+        } catch (Exception e) {
+          LOGGER.error("Closing builder threw an exception, potentially 
leaving the star-tree index in an "
+              + "inconsistent state, throwing exception", e);
+          throw e;

Review Comment:
   Do we really need this? We're already logging the error in the builder's 
close method. Feels a bit odd to have an additional try-catch + throw in the 
finally block for a runtime exception.



##########
pinot-segment-local/src/test/java/org/apache/pinot/segment/local/startree/v2/builder/MultipleTreesBuilderCloseTest.java:
##########
@@ -0,0 +1,207 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.startree.v2.builder;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.commons.configuration2.PropertiesConfiguration;
+import org.apache.commons.io.FileUtils;
+import 
org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader;
+import 
org.apache.pinot.segment.local.segment.creator.impl.SegmentIndexCreationDriverImpl;
+import org.apache.pinot.segment.local.segment.readers.GenericRowRecordReader;
+import org.apache.pinot.segment.local.startree.StarTreeBuilderUtils;
+import org.apache.pinot.segment.spi.ImmutableSegment;
+import org.apache.pinot.segment.spi.creator.SegmentGeneratorConfig;
+import org.apache.pinot.spi.config.table.StarTreeIndexConfig;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.env.CommonsConfigurationUtils;
+import org.apache.pinot.spi.utils.ReadMode;
+import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.testng.Assert.*;
+
+/**
+ * Unit test for MultipleTreesBuilder.close() method to verify exception 
handling
+ * when cleanup operations fail.
+ */
+public class MultipleTreesBuilderCloseTest {
+  private static final File TEMP_DIR = new File(FileUtils.getTempDirectory(), 
"MultipleTreesBuilderCloseTest");
+  private static final File INDEX_DIR = new File(TEMP_DIR, "testSegment");
+
+  @BeforeMethod
+  public void setUp() throws Exception {
+    FileUtils.deleteQuietly(TEMP_DIR);
+    FileUtils.forceMkdir(TEMP_DIR);
+  }
+
+  @AfterMethod
+  public void tearDown() {
+    FileUtils.deleteQuietly(TEMP_DIR);
+  }
+
+  @Test
+  public void testBuildFailureThenCloseFailureWithSuppressedException() throws 
Exception {
+    // This test verifies that when build() fails and close() also fails,
+
+    // Build a test segment with star-tree
+    buildTestSegment();
+
+    Exception buildException = null;
+    Exception closeException = null;
+
+    // Build the star-tree index with a good configuration and ensure it 
passes. This will ensure that the correct
+    // close clean-up path is called
+    List<StarTreeV2BuilderConfig> builderConfigsValid = createBuilderConfigs();
+    MultipleTreesBuilder builder = new 
MultipleTreesBuilder(builderConfigsValid, INDEX_DIR,
+        MultipleTreesBuilder.BuildMode.OFF_HEAP);
+
+    try {
+      builder.build();
+    } catch (Exception e) {
+      fail("Building the first time with valid configs should pass", e);
+    } finally {
+      builder.close();
+    }
+
+    // Create a MultipleTreesBuilder with invalid config to force build() to 
fail
+    List<StarTreeV2BuilderConfig> builderConfigsInvalid = 
createInvalidBuilderConfigs();
+    builder = new MultipleTreesBuilder(builderConfigsInvalid, INDEX_DIR, 
MultipleTreesBuilder.BuildMode.OFF_HEAP);
+
+    // Mock the CommonsConfigurationUtils to emulate failure during close
+    try (MockedStatic<CommonsConfigurationUtils> mockedStatic = 
Mockito.mockStatic(CommonsConfigurationUtils.class)) {
+      try {
+        // This should fail due to invalid config
+        builder.build();
+        fail("Expected build() to throw an exception due to invalid config");
+      } catch (Exception e) {
+        buildException = e;
+      } finally {
+        try {
+          // Mock the static method to always throw RuntimeException on any 
input to force a close() failure
+          mockedStatic.when(() -> 
CommonsConfigurationUtils.saveToFile(any(PropertiesConfiguration.class),
+              any(File.class))).thenThrow(new RuntimeException("Simulated 
failure"));
+          builder.close();
+          fail("Closing the builder should fail since the build should have 
failed");
+        } catch (Exception e) {
+          closeException = e;
+        }
+      }
+    }
+
+    // Verify that the build exception occurred
+    assertNotNull(buildException, "Expected an exception from try-catch 
(build)");
+
+    // Verify that the close exception occurred
+    assertNotNull(closeException, "Expected an exception from 
try-catch-finally (close in finally)");

Review Comment:
   nit: I think it might be more readable to use the canonical `assertThrows` 
pattern instead of try-catch-fail-assert?



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/startree/v2/builder/MultipleTreesBuilder.java:
##########
@@ -240,8 +266,33 @@ private static SingleTreeBuilder 
getSingleTreeBuilder(StarTreeV2BuilderConfig bu
   }
 
   @Override
-  public void close() {
+  public void close()
+      throws IOException {
     if (_separatorTempDir != null) {
+      if (_starTreeCreationFailed) {
+        try {
+          LOGGER.info("Star-tree index creation failed, trying to reset the 
older star-tree index and metadata");
+          FileUtils.moveFileToDirectory(new File(_separatorTempDir, 
StarTreeV2Constants.INDEX_FILE_NAME),
+              _segmentDirectory,
+              false);
+          FileUtils.moveFileToDirectory(new File(_separatorTempDir, 
StarTreeV2Constants.INDEX_MAP_FILE_NAME),
+              _segmentDirectory, false);
+
+          // Copy back the older star-tree related metadata
+          Iterator<String> keys = _existingStarTreeMetadata.getKeys();
+          while (keys.hasNext()) {
+            String key = keys.next();
+            Object value = _existingStarTreeMetadata.getProperty(key);
+            _metadataProperties.addProperty(MetadataKey.STAR_TREE_PREFIX + 
key, value);
+          }
+          CommonsConfigurationUtils.saveToFile(_metadataProperties,
+              new File(_segmentDirectory, 
V1Constants.MetadataKeys.METADATA_FILE_NAME));
+        } catch (Exception e) {
+          LOGGER.error("Could not reset the star-tree index state to the 
previous one", e);
+          throw e;

Review Comment:
   Do we not need to delete the separator temp dir and call 
`IndexSegment::destroy` here?



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/SegmentIndexCreationDriverImpl.java:
##########
@@ -578,10 +578,26 @@ private void buildStarTreeV2IfNecessary(File indexDir)
     if (CollectionUtils.isNotEmpty(starTreeIndexConfigs) || 
enableDefaultStarTree) {
       MultipleTreesBuilder.BuildMode buildMode =
           _config.isOnHeap() ? MultipleTreesBuilder.BuildMode.ON_HEAP : 
MultipleTreesBuilder.BuildMode.OFF_HEAP;
-      try (
-          MultipleTreesBuilder builder = new 
MultipleTreesBuilder(starTreeIndexConfigs, enableDefaultStarTree, indexDir,
-              buildMode)) {
+      MultipleTreesBuilder builder = new 
MultipleTreesBuilder(starTreeIndexConfigs, enableDefaultStarTree, indexDir,
+          buildMode);
+      try {
         builder.build();
+      } catch (Exception e) {
+        String tableNameWithType = _config.getTableConfig().getTableName();
+        LOGGER.error("Failed to build star-tree index for table: {}, 
skipping", tableNameWithType, e);
+        if (_instanceType == InstanceType.MINION) {
+          MinionMetrics.get().addMeteredTableValue(tableNameWithType, 
MinionMeter.STAR_TREE_INDEX_BUILD_FAILURES, 1);
+        } else {
+          ServerMetrics.get().addMeteredTableValue(tableNameWithType, 
ServerMeter.STAR_TREE_INDEX_BUILD_FAILURES, 1);
+        }
+      } finally {
+        try {
+          builder.close();

Review Comment:
   Might be worth adding a one liner comment on why we aren't using the 
try-with-resources pattern, because some IDEs flag this as a problem.



##########
pinot-segment-local/src/test/java/org/apache/pinot/segment/local/startree/v2/builder/MultipleTreesBuilderCloseTest.java:
##########
@@ -0,0 +1,207 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.startree.v2.builder;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.commons.configuration2.PropertiesConfiguration;
+import org.apache.commons.io.FileUtils;
+import 
org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader;
+import 
org.apache.pinot.segment.local.segment.creator.impl.SegmentIndexCreationDriverImpl;
+import org.apache.pinot.segment.local.segment.readers.GenericRowRecordReader;
+import org.apache.pinot.segment.local.startree.StarTreeBuilderUtils;
+import org.apache.pinot.segment.spi.ImmutableSegment;
+import org.apache.pinot.segment.spi.creator.SegmentGeneratorConfig;
+import org.apache.pinot.spi.config.table.StarTreeIndexConfig;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.env.CommonsConfigurationUtils;
+import org.apache.pinot.spi.utils.ReadMode;
+import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.testng.Assert.*;
+
+/**
+ * Unit test for MultipleTreesBuilder.close() method to verify exception 
handling
+ * when cleanup operations fail.
+ */
+public class MultipleTreesBuilderCloseTest {
+  private static final File TEMP_DIR = new File(FileUtils.getTempDirectory(), 
"MultipleTreesBuilderCloseTest");
+  private static final File INDEX_DIR = new File(TEMP_DIR, "testSegment");
+
+  @BeforeMethod
+  public void setUp() throws Exception {
+    FileUtils.deleteQuietly(TEMP_DIR);
+    FileUtils.forceMkdir(TEMP_DIR);
+  }
+
+  @AfterMethod
+  public void tearDown() {
+    FileUtils.deleteQuietly(TEMP_DIR);
+  }
+
+  @Test
+  public void testBuildFailureThenCloseFailureWithSuppressedException() throws 
Exception {

Review Comment:
   nit: there's no suppressed exceptions anymore I suppose?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to