This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new ac6606e774a Distribute ingestion Groovy cluster policy to servers and 
minions (#19888)
ac6606e774a is described below

commit ac6606e774abbe01d96a722e09e7123b7efac0e1
Author: Xiang Fu <[email protected]>
AuthorDate: Sat Nov 21 00:23:17 2026 -0800

    Distribute ingestion Groovy cluster policy to servers and minions (#19888)
    
    * Distribute ingestion Groovy cluster policy to servers and minions
    
    * Clean up runtime roles when Groovy policy subscription fails
    
    Reproduce by failing subscription after Helix connects. Disable compilation 
and release initialized resources while preserving the original cause.
    
    * Require the initial cluster config before starting Pinot services
    
    Helix can return before the initial policy has been applied. Fail startup 
in that case and release the resources the role owns.
    
    * Use a role-neutral cluster key for ingestion Groovy
---
 .../config/DefaultClusterConfigChangeHandler.java  |  40 ++++
 .../pinot/common/utils/ServiceStartableUtils.java  |   6 +-
 .../config/IngestionGroovyConfigListener.java      |  52 +++++
 .../config/IngestionGroovyConfigListenerTest.java  | 215 +++++++++++++++++++++
 .../pinot/controller/BaseControllerStarter.java    |  25 +--
 .../api/resources/TableConfigValidationUtils.java  |   4 +-
 .../controller/ControllerStarterStatelessTest.java |  75 ++++++-
 .../pinot/controller/helix/ControllerTest.java     |   9 +-
 .../realtime/RealtimeSegmentDataManager.java       |   2 +-
 .../realtime/SegmentBuildTimeLeaseExtender.java    |  28 ++-
 .../org/apache/pinot/minion/BaseMinionStarter.java |  11 +-
 .../server/starter/helix/BaseServerStarter.java    |  18 +-
 .../starter/helix/HelixInstanceDataManager.java    |  22 ++-
 .../starter/helix/BaseServerStarterTest.java       |  29 +++
 .../helix/HelixInstanceDataManagerTest.java        |  53 +++++
 .../apache/pinot/spi/utils/CommonConstants.java    |   9 +-
 16 files changed, 543 insertions(+), 55 deletions(-)

diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/config/DefaultClusterConfigChangeHandler.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/config/DefaultClusterConfigChangeHandler.java
index d26d86f1308..1c1f719d1b7 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/config/DefaultClusterConfigChangeHandler.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/config/DefaultClusterConfigChangeHandler.java
@@ -18,14 +18,17 @@
  */
 package org.apache.pinot.common.config;
 
+import com.google.common.base.Preconditions;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import org.apache.helix.HelixManager;
 import org.apache.helix.NotificationContext;
 import org.apache.helix.api.listeners.BatchMode;
 import org.apache.helix.api.listeners.ClusterConfigChangeListener;
 import org.apache.helix.model.ClusterConfig;
+import org.apache.pinot.common.utils.ExceptionUtils;
 import org.apache.pinot.spi.config.provider.PinotClusterConfigChangeListener;
 import org.apache.pinot.spi.config.provider.PinotClusterConfigProvider;
 import org.slf4j.Logger;
@@ -41,8 +44,42 @@ public class DefaultClusterConfigChangeHandler implements 
ClusterConfigChangeLis
   private final List<PinotClusterConfigChangeListener> _listeners = new 
ArrayList<>();
   private Map<String, String> _clusterConfigs = Map.of();
 
+  private volatile boolean _initialSnapshotApplied;
+  private boolean _subscriptionFailed;
+
+  /// Registers this fresh handler at startup. Helix delivers INIT 
synchronously but can swallow initialization errors.
+  /// On failure, runs the policy cleanup before disconnecting, then releases 
resources in the given order.
+  public void subscribe(HelixManager manager, Runnable beforeDisconnect, 
Runnable... failureCleanup) {
+    try {
+      manager.addClusterfigChangeListener(this);
+      Preconditions.checkState(_initialSnapshotApplied, "Helix did not deliver 
the initial cluster config");
+    } catch (Exception e) {
+      synchronized (this) {
+        // Prevent late callbacks, including FINALIZE during disconnect, from 
overwriting fail-closed cleanup.
+        _subscriptionFailed = true;
+      }
+      runCleanup(beforeDisconnect, e);
+      runCleanup(manager::disconnect, e);
+      for (Runnable cleanup : failureCleanup) {
+        runCleanup(cleanup, e);
+      }
+      throw new IllegalStateException("Failed to subscribe to cluster config", 
e);
+    }
+  }
+
+  private static void runCleanup(Runnable cleanup, Exception cause) {
+    try {
+      cleanup.run();
+    } catch (RuntimeException e) {
+      ExceptionUtils.suppress(e, cause);
+    }
+  }
+
   @Override
   public synchronized void onClusterConfigChange(ClusterConfig clusterConfig, 
NotificationContext context) {
+    if (_subscriptionFailed) {
+      return;
+    }
     Map<String, String> clusterConfigs = 
copyWithoutNullValues(clusterConfig.getRecord().getSimpleFields());
     Set<String> changedConfigs = getChangedProperties(_clusterConfigs, 
clusterConfigs);
     LOGGER.info("Cluster configs changed: {}", changedConfigs);
@@ -50,6 +87,9 @@ public class DefaultClusterConfigChangeHandler implements 
ClusterConfigChangeLis
     for (PinotClusterConfigChangeListener listener : _listeners) {
       listener.onChange(changedConfigs, clusterConfigs);
     }
+    if (context != null && context.getType() == NotificationContext.Type.INIT) 
{
+      _initialSnapshotApplied = true;
+    }
   }
 
   @Override
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/ServiceStartableUtils.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/ServiceStartableUtils.java
index c7c85cc852c..119bee703e4 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/ServiceStartableUtils.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/ServiceStartableUtils.java
@@ -26,6 +26,7 @@ import java.util.concurrent.TimeUnit;
 import org.apache.helix.zookeeper.datamodel.ZNRecord;
 import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
 import org.apache.helix.zookeeper.impl.client.ZkClient;
+import org.apache.pinot.common.utils.config.IngestionGroovyConfigListener;
 import org.apache.pinot.common.utils.request.RequestUtils;
 import org.apache.pinot.common.utils.tls.ZooKeeperSslContextSupplier;
 import org.apache.pinot.segment.spi.index.ForwardIndexConfig;
@@ -113,8 +114,9 @@ public class ServiceStartableUtils {
       Map<String, String> clusterConfigs) {
     if (serviceRole == ServiceRole.CONTROLLER) {
       
instanceConfig.setProperty(CommonConstants.Groovy.DISABLE_INGESTION_GROOVY,
-          CommonConstants.Groovy.isIngestionGroovyDisabled(
-              
clusterConfigs.get(CommonConstants.Groovy.DISABLE_INGESTION_GROOVY)));
+          
CommonConstants.Groovy.isControllerIngestionGroovyDisabled(clusterConfigs));
+    } else if (serviceRole == ServiceRole.SERVER || serviceRole == 
ServiceRole.MINION) {
+      IngestionGroovyConfigListener.applyClusterConfig(clusterConfigs);
     }
   }
 
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/config/IngestionGroovyConfigListener.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/IngestionGroovyConfigListener.java
new file mode 100644
index 00000000000..3777e64acd1
--- /dev/null
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/config/IngestionGroovyConfigListener.java
@@ -0,0 +1,52 @@
+/**
+ * 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.common.utils.config;
+
+import java.util.Map;
+import java.util.Set;
+import org.apache.helix.HelixManager;
+import org.apache.pinot.common.config.DefaultClusterConfigChangeHandler;
+import org.apache.pinot.common.evaluator.GroovyFunctionEvaluator;
+import org.apache.pinot.spi.config.provider.PinotClusterConfigChangeListener;
+import org.apache.pinot.spi.utils.CommonConstants.Groovy;
+
+
+/// Applies the cluster ingestion Groovy policy in server and minion processes.
+///
+/// Missing, removed, and invalid values disable new ingestion compilation; 
only `false` enables it. Query Groovy
+/// and previously compiled scripts retain their own behavior. Thread-safe: 
updates publish through a volatile flag.
+public class IngestionGroovyConfigListener implements 
PinotClusterConfigChangeListener {
+  @Override
+  public void onChange(Set<String> changedConfigs, Map<String, String> 
clusterConfigs) {
+    applyClusterConfig(clusterConfigs);
+  }
+
+  /// Applies a raw cluster snapshot before a server or minion starts 
ingestion or query processing.
+  public static void applyClusterConfig(Map<String, String> clusterConfigs) {
+    GroovyFunctionEvaluator.setIngestionGroovyDisabled(
+        
Groovy.isIngestionGroovyDisabled(clusterConfigs.get(Groovy.INGESTION_GROOVY_DISABLED)));
+  }
+
+  /// Subscribes a runtime role to cluster updates. On failure, disables 
ingestion compilation, disconnects the
+  /// participant, and releases initialized role resources before failing 
startup with the original cause.
+  public static void subscribeToClusterConfig(HelixManager helixManager, 
DefaultClusterConfigChangeHandler handler,
+      Runnable... failureCleanup) {
+    handler.subscribe(helixManager, () -> applyClusterConfig(Map.of()), 
failureCleanup);
+  }
+}
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/config/IngestionGroovyConfigListenerTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/config/IngestionGroovyConfigListenerTest.java
new file mode 100644
index 00000000000..2df4ba1cb90
--- /dev/null
+++ 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/config/IngestionGroovyConfigListenerTest.java
@@ -0,0 +1,215 @@
+/**
+ * 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.common.utils.config;
+
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import org.apache.helix.HelixManager;
+import org.apache.helix.NotificationContext;
+import org.apache.helix.model.ClusterConfig;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
+import org.apache.helix.zookeeper.impl.client.ZkClient;
+import org.apache.pinot.common.config.DefaultClusterConfigChangeHandler;
+import org.apache.pinot.common.evaluator.GroovyFunctionEvaluator;
+import org.apache.pinot.common.utils.ServiceStartableUtils;
+import org.apache.pinot.common.utils.ZkStarter;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.services.ServiceRole;
+import org.apache.pinot.spi.utils.CommonConstants.Groovy;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.expectThrows;
+
+
+/// Verifies startup and live cluster snapshots against the actual Groovy 
compiler gate.
+/// Not thread-safe because the compiler switch is process-wide.
+@Test(singleThreaded = true)
+public class IngestionGroovyConfigListenerTest {
+  private static final String KEY = Groovy.INGESTION_GROOVY_DISABLED;
+  private static final String EXPRESSION = "Groovy({value + 1}, value)";
+
+  @AfterMethod(alwaysRun = true)
+  public void restoreCompilation() {
+    GroovyFunctionEvaluator.setIngestionGroovyDisabled(false);
+  }
+
+  @Test
+  public void testLiveUpdatesAndRemoval() {
+    DefaultClusterConfigChangeHandler handler = new 
DefaultClusterConfigChangeHandler();
+    handler.registerClusterConfigChangeListener(new 
IngestionGroovyConfigListener());
+    expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+    assertEquals(GroovyFunctionEvaluator.forQuery(EXPRESSION).evaluate(new 
Object[]{1}), 2);
+
+    ClusterConfig config = new ClusterConfig("test");
+    config.getRecord().setSimpleField(Groovy.DISABLE_INGESTION_GROOVY, "true");
+    config.getRecord().setSimpleField(KEY, " false ");
+    handler.onClusterConfigChange(config, null);
+    assertEquals(new GroovyFunctionEvaluator(EXPRESSION).evaluate(new 
Object[]{1}), 2);
+
+    config.getRecord().setSimpleField(Groovy.DISABLE_INGESTION_GROOVY, 
"false");
+    config.getRecord().setSimpleField(KEY, "true");
+    handler.onClusterConfigChange(config, null);
+    expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+
+    config.getRecord().setSimpleField(KEY, "false");
+    handler.onClusterConfigChange(config, null);
+    config.getRecord().getSimpleFields().remove(KEY);
+    handler.onClusterConfigChange(config, null);
+    expectThrows(IllegalStateException.class, () -> 
GroovyFunctionEvaluator.parseGroovyScript(EXPRESSION));
+  }
+
+  @Test
+  public void testFirstEmptySnapshotAndInvalidValueDisableCompilation() {
+    DefaultClusterConfigChangeHandler handler = new 
DefaultClusterConfigChangeHandler();
+    handler.registerClusterConfigChangeListener(new 
IngestionGroovyConfigListener());
+    // The startup read enabled compilation, but the key was deleted before 
the first Helix callback.
+    IngestionGroovyConfigListener.applyClusterConfig(Map.of(KEY, "false"));
+    handler.onClusterConfigChange(new ClusterConfig("test"), null);
+    expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+
+    IngestionGroovyConfigListener.applyClusterConfig(Map.of(KEY, "false"));
+    IngestionGroovyConfigListener.applyClusterConfig(Map.of(KEY, "invalid", 
Groovy.DISABLE_INGESTION_GROOVY, "false"));
+    expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+  }
+
+  @Test
+  public void 
testSubscriptionFailureDisablesCompilationAndCleansUpRuntimeRoles()
+      throws Exception {
+    for (boolean server : new boolean[]{false, true}) {
+      HelixManager manager = mock(HelixManager.class);
+      DefaultClusterConfigChangeHandler handler = new 
DefaultClusterConfigChangeHandler();
+      Exception registrationFailure = new Exception("Subscription failed");
+      
doThrow(registrationFailure).when(manager).addClusterfigChangeListener(handler);
+      ExecutorService executor = mock(ExecutorService.class);
+      RuntimeException cleanupFailure = new RuntimeException("Executor cleanup 
failed");
+      doThrow(cleanupFailure).when(executor).shutdownNow();
+      Runnable serverCleanup = mock(Runnable.class);
+      Runnable[] cleanup = server
+          ? new Runnable[]{executor::shutdownNow, serverCleanup}
+          : new Runnable[]{executor::shutdownNow};
+      GroovyFunctionEvaluator.setIngestionGroovyDisabled(false);
+
+      IllegalStateException failure = expectThrows(IllegalStateException.class,
+          () -> 
IngestionGroovyConfigListener.subscribeToClusterConfig(manager, handler, 
cleanup));
+      assertSame(failure.getCause(), registrationFailure);
+      assertEquals(registrationFailure.getSuppressed().length, 1);
+      assertSame(registrationFailure.getSuppressed()[0], cleanupFailure);
+      expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+      verify(manager).disconnect();
+      verify(executor).shutdownNow();
+      if (server) {
+        verify(serverCleanup).run();
+      } else {
+        verifyNoInteractions(serverCleanup);
+      }
+    }
+  }
+
+  @Test
+  public void testSuccessfulSubscriptionAppliesInitialPolicy()
+      throws Exception {
+    HelixManager manager = mock(HelixManager.class);
+    DefaultClusterConfigChangeHandler handler = new 
DefaultClusterConfigChangeHandler();
+    handler.registerClusterConfigChangeListener(new 
IngestionGroovyConfigListener());
+    // An empty initial snapshot must replace an enabled startup snapshot.
+    IngestionGroovyConfigListener.applyClusterConfig(Map.of(KEY, "false"));
+    NotificationContext context = new NotificationContext(manager);
+    context.setType(NotificationContext.Type.INIT);
+    doAnswer(invocation -> {
+      handler.onClusterConfigChange(new ClusterConfig("test"), context);
+      return null;
+    }).when(manager).addClusterfigChangeListener(handler);
+    Runnable cleanup = mock(Runnable.class);
+
+    IngestionGroovyConfigListener.subscribeToClusterConfig(manager, handler, 
cleanup);
+
+    expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+    verify(manager, never()).disconnect();
+    verifyNoInteractions(cleanup);
+  }
+
+  @Test
+  public void testSubscriptionWithoutInitialCallbackFailsClosed() {
+    HelixManager manager = mock(HelixManager.class);
+    DefaultClusterConfigChangeHandler handler = new 
DefaultClusterConfigChangeHandler();
+    handler.registerClusterConfigChangeListener(new 
IngestionGroovyConfigListener());
+    IngestionGroovyConfigListener.applyClusterConfig(Map.of(KEY, "false"));
+    ClusterConfig enabled = new ClusterConfig("test");
+    enabled.getRecord().setSimpleField(KEY, "false");
+    NotificationContext context = new NotificationContext(manager);
+    context.setType(NotificationContext.Type.FINALIZE);
+    doAnswer(invocation -> {
+      handler.onClusterConfigChange(enabled, context);
+      return null;
+    }).when(manager).disconnect();
+    Runnable cleanup = mock(Runnable.class);
+
+    IllegalStateException failure = expectThrows(IllegalStateException.class,
+        () -> IngestionGroovyConfigListener.subscribeToClusterConfig(manager, 
handler, cleanup));
+
+    assertEquals(failure.getCause().getMessage(), "Helix did not deliver the 
initial cluster config");
+    expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+    verify(manager).disconnect();
+    verify(cleanup).run();
+  }
+
+  @Test
+  public void testStartupUsesRawClusterConfigOnlyForRuntimeRoles() {
+    ZkStarter.ZookeeperInstance zk = ZkStarter.startLocalZkServer();
+    ZkClient client = new ZkClient.Builder().setZkServer(zk.getZkUrl())
+        .setZkSerializer(new ZNRecordSerializer()).build();
+    try {
+      String cluster = "groovy-policy-test";
+      String path = "/" + cluster + "/CONFIGS/CLUSTER/" + cluster;
+      client.createPersistent(path, true);
+      ZNRecord record = new ZNRecord(cluster);
+      record.setSimpleField(KEY, "false");
+      client.writeData(path, record);
+      PinotConfiguration instance = new PinotConfiguration(Map.of(KEY, 
"true"));
+      ServiceStartableUtils.applyClusterConfig(instance, zk.getZkUrl(), 
cluster, ServiceRole.SERVER);
+      assertEquals(new GroovyFunctionEvaluator(EXPRESSION).evaluate(new 
Object[]{1}), 2);
+
+      record.getSimpleFields().remove(KEY);
+      record.setSimpleField(Groovy.DISABLE_INGESTION_GROOVY, "false");
+      client.writeData(path, record);
+      instance.setProperty(KEY, "false");
+      ServiceStartableUtils.applyClusterConfig(instance, zk.getZkUrl(), 
cluster, ServiceRole.MINION);
+      expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+
+      GroovyFunctionEvaluator.setIngestionGroovyDisabled(false);
+      ServiceStartableUtils.applyClusterConfig(instance, zk.getZkUrl(), 
cluster, ServiceRole.CONTROLLER);
+      assertEquals(new GroovyFunctionEvaluator(EXPRESSION).evaluate(new 
Object[]{1}), 2);
+      ServiceStartableUtils.applyClusterConfig(instance, zk.getZkUrl(), 
"missing-cluster", ServiceRole.SERVER);
+      expectThrows(IllegalStateException.class, () -> new 
GroovyFunctionEvaluator(EXPRESSION));
+    } finally {
+      client.close();
+      ZkStarter.stopLocalZkServer(zk);
+    }
+  }
+}
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
index 8ef3f8976a4..c9a4e16744f 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
@@ -249,8 +249,7 @@ public abstract class BaseControllerStarter implements 
ServiceStartable {
     _config = new ControllerConf(pinotConfiguration.toMap());
     _clusterConfigChangeHandler = new DefaultClusterConfigChangeHandler();
     
_clusterConfigChangeHandler.registerClusterConfigChangeListener((changedConfigs,
 clusterConfigs) -> {
-      boolean disabled =
-          
CommonConstants.Groovy.isIngestionGroovyDisabled(clusterConfigs.get(ControllerConf.DISABLE_GROOVY));
+      boolean disabled = 
CommonConstants.Groovy.isControllerIngestionGroovyDisabled(clusterConfigs);
       TableConfigUtils.setDisableGroovy(disabled);
       _config.setClusterIngestionGroovyDisabled(disabled);
     });
@@ -604,6 +603,7 @@ public abstract class BaseControllerStarter implements 
ServiceStartable {
 
     LOGGER.info("Registering and connecting Helix participant manager as Helix 
Participant role");
     registerAndConnectAsHelixParticipant();
+    subscribeToClusterConfig();
 
     // LeadControllerManager needs to be started after the connection
     // as it can check Helix leadership and resource config only after 
connecting to Helix cluster.
@@ -665,15 +665,6 @@ public abstract class BaseControllerStarter implements 
ServiceStartable {
     // TODO: Need to put this inside HelixResourceManager when 
HelixControllerLeadershipManager is removed.
     
_helixResourceManager.registerPinotLLCRealtimeSegmentManager(_pinotLLCRealtimeSegmentManager);
 
-    try {
-      // Register cluster config change handler with Helix
-      
_helixParticipantManager.addClusterfigChangeListener(_clusterConfigChangeHandler);
-    } catch (Exception e) {
-      TableConfigUtils.setDisableGroovy(true);
-      _config.setClusterIngestionGroovyDisabled(true);
-      throw new IllegalStateException("Failed to register cluster config 
change handler", e);
-    }
-
     SegmentCompletionConfig segmentCompletionConfig = new 
SegmentCompletionConfig(_config);
 
     _segmentCompletionManager =
@@ -1052,6 +1043,18 @@ public abstract class BaseControllerStarter implements 
ServiceStartable {
     }
   }
 
+  @VisibleForTesting
+  void subscribeToClusterConfig() {
+    _clusterConfigChangeHandler.subscribe(_helixParticipantManager, () -> {
+      TableConfigUtils.setDisableGroovy(true);
+      _config.setClusterIngestionGroovyDisabled(true);
+    }, () -> {
+      if (_helixControllerManager != null) {
+        stopHelixController();
+      }
+    }, _executorService::shutdownNow);
+  }
+
   private void updateInstanceConfigIfNeeded() {
     InstanceConfig instanceConfig =
         HelixHelper.getInstanceConfig(_helixParticipantManager, 
_helixParticipantInstanceId);
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/TableConfigValidationUtils.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/TableConfigValidationUtils.java
index 9ecb31e871c..233f7090740 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/TableConfigValidationUtils.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/TableConfigValidationUtils.java
@@ -46,6 +46,7 @@ import org.apache.pinot.spi.config.table.TableType;
 import org.apache.pinot.spi.config.table.assignment.InstancePartitionsType;
 import org.apache.pinot.spi.data.FieldSpec;
 import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.utils.CommonConstants.Groovy;
 import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -93,7 +94,8 @@ public final class TableConfigValidationUtils {
             && transformFunction.regionMatches(true, 0, groovyPrefix, 0, 
groovyPrefix.length())) {
           throw new IllegalStateException(
               "Groovy transform functions are disabled for schema. Found '" + 
transformFunction + "' for column '"
-                  + fieldSpec.getName() + "'. Set " + 
ControllerConf.DISABLE_GROOVY + "=false to enable them");
+                  + fieldSpec.getName() + "'. Set " + 
Groovy.INGESTION_GROOVY_DISABLED
+                  + "=false in cluster config to enable them");
         }
       }
     }
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerStarterStatelessTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerStarterStatelessTest.java
index bd3abddb436..eabcd95d00d 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerStarterStatelessTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/ControllerStarterStatelessTest.java
@@ -22,19 +22,30 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import org.apache.helix.HelixManager;
+import org.apache.helix.model.ClusterConfig;
 import org.apache.helix.model.InstanceConfig;
+import org.apache.pinot.common.config.DefaultClusterConfigChangeHandler;
 import org.apache.pinot.common.utils.helix.HelixHelper;
 import org.apache.pinot.controller.helix.ControllerTest;
 import org.apache.pinot.segment.local.utils.TableConfigUtils;
 import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.metrics.PinotMetricsRegistry;
 import org.testng.annotations.Test;
 
 import static org.apache.pinot.controller.ControllerConf.CONTROLLER_HOST;
 import static org.apache.pinot.controller.ControllerConf.CONTROLLER_PORT;
 import static org.apache.pinot.controller.ControllerConf.DISABLE_GROOVY;
 import static 
org.apache.pinot.spi.utils.CommonConstants.Controller.CONFIG_OF_INSTANCE_ID;
+import static 
org.apache.pinot.spi.utils.CommonConstants.Groovy.INGESTION_GROOVY_DISABLED;
 import static 
org.apache.pinot.spi.utils.CommonConstants.Helix.CONTROLLER_INSTANCE;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
 import static org.testng.Assert.fail;
 
 
@@ -49,35 +60,57 @@ public class ControllerStarterStatelessTest extends 
ControllerTest {
 
   @Test
   public void testClusterIngestionGroovyPolicyAtStartup() {
-    List<Map<String, String>> clusterPolicies = List.of(Map.of(), 
Map.of(DISABLE_GROOVY, " FaLsE "),
-        Map.of(DISABLE_GROOVY, "true"), Map.of(DISABLE_GROOVY, "invalid"),
-        Map.of(DISABLE_GROOVY, "${other.flag}"), 
Map.of("CONTROLLER.DISABLE.INGESTION.GROOVY", "false"));
+    record Policy(Map<String, String> settings, boolean disabled) {
+    }
+
+    List<Policy> policies = List.of(
+        new Policy(Map.of(), true),
+        new Policy(Map.of(DISABLE_GROOVY, " FaLsE "), false),
+        new Policy(Map.of(DISABLE_GROOVY, "true"), true),
+        new Policy(Map.of(DISABLE_GROOVY, "invalid"), true),
+        new Policy(Map.of(DISABLE_GROOVY, "${other.flag}"), true),
+        new Policy(Map.of("CONTROLLER.DISABLE.INGESTION.GROOVY", "false"), 
true),
+        new Policy(Map.of(INGESTION_GROOVY_DISABLED, "false"), false),
+        new Policy(Map.of(INGESTION_GROOVY_DISABLED, "false", DISABLE_GROOVY, 
"true"), false),
+        new Policy(Map.of(INGESTION_GROOVY_DISABLED, "true", DISABLE_GROOVY, 
"false"), true),
+        new Policy(Map.of(INGESTION_GROOVY_DISABLED, "invalid", 
DISABLE_GROOVY, "false"), true),
+        new Policy(Map.of(INGESTION_GROOVY_DISABLED, "", DISABLE_GROOVY, 
"false"), true));
     _configOverride.clear();
     startZk();
     try {
-      for (int i = 0; i < clusterPolicies.size(); i++) {
-        Map<String, String> clusterPolicy = clusterPolicies.get(i);
-        boolean expectedDisabled = i != 1;
+      for (int i = 0; i < policies.size(); i++) {
+        Policy policy = policies.get(i);
         ControllerStarter starter = new ControllerStarter() {
           @Override
           protected Map<String, String> getDefaultClusterConfigs() {
             Map<String, String> configs = super.getDefaultClusterConfigs();
-            configs.putAll(clusterPolicy);
+            configs.putAll(policy.settings());
             return configs;
           }
 
           @Override
           protected void applyCustomConfigs(ControllerConf config) {
-            config.setProperty(DISABLE_GROOVY, !expectedDisabled);
+            config.setProperty(DISABLE_GROOVY, !policy.disabled());
+            config.setProperty(INGESTION_GROOVY_DISABLED, !policy.disabled());
           }
         };
         Map<String, Object> config = getDefaultControllerConfiguration();
         config.put(ControllerConf.HELIX_CLUSTER_NAME, getHelixClusterName() + 
"Groovy" + i);
         config.put(ControllerConf.CONTROLLER_MODE, 
ControllerConf.ControllerMode.HELIX_ONLY.name());
-        config.put(DISABLE_GROOVY, !expectedDisabled);
+        config.put(DISABLE_GROOVY, !policy.disabled());
+        config.put(INGESTION_GROOVY_DISABLED, !policy.disabled());
         config.put("other.flag", "false");
         runWithHelixMock(() -> starter.init(new PinotConfiguration(config)));
-        assertEquals(starter.getConfig().isDisableIngestionGroovy(), 
expectedDisabled, clusterPolicy.toString());
+        assertEquals(starter.getConfig().isDisableIngestionGroovy(), 
policy.disabled(), policy.toString());
+
+        // Replacing a previous snapshot may remove either or both keys.
+        ClusterConfig snapshot = new ClusterConfig(getHelixClusterName());
+        snapshot.getRecord().setSimpleField(INGESTION_GROOVY_DISABLED, 
Boolean.toString(!policy.disabled()));
+        starter._clusterConfigChangeHandler.onClusterConfigChange(snapshot, 
null);
+        assertEquals(starter.getConfig().isDisableIngestionGroovy(), 
!policy.disabled(), policy.toString());
+        snapshot.getRecord().setSimpleFields(new HashMap<>(policy.settings()));
+        starter._clusterConfigChangeHandler.onClusterConfigChange(snapshot, 
null);
+        assertEquals(starter.getConfig().isDisableIngestionGroovy(), 
policy.disabled(), policy.toString());
       }
     } finally {
       TableConfigUtils.setDisableGroovy(false);
@@ -86,6 +119,28 @@ public class ControllerStarterStatelessTest extends 
ControllerTest {
     }
   }
 
+  @Test
+  public void testMissingClusterConfigCallbackCleansUpController() {
+    ControllerStarter starter = new ControllerStarter();
+    starter._config = new ControllerConf();
+    starter._config.setClusterIngestionGroovyDisabled(false);
+    starter._clusterConfigChangeHandler = new 
DefaultClusterConfigChangeHandler();
+    starter._helixParticipantManager = mock(HelixManager.class);
+    starter._helixControllerManager = mock(HelixManager.class);
+    starter._executorService = mock(ExecutorService.class);
+    starter._metricsRegistry = mock(PinotMetricsRegistry.class);
+    try {
+      expectThrows(IllegalStateException.class, 
starter::subscribeToClusterConfig);
+      assertTrue(starter.getConfig().isDisableIngestionGroovy());
+      verify(starter._helixParticipantManager).disconnect();
+      verify(starter._helixControllerManager).disconnect();
+      verify(starter._executorService).shutdownNow();
+      verifyNoInteractions(starter._metricsRegistry);
+    } finally {
+      TableConfigUtils.setDisableGroovy(false);
+    }
+  }
+
   @Test
   public void testHostnamePortOverride()
       throws Exception {
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java
index 574185c126b..396a2520c3f 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java
@@ -350,7 +350,7 @@ public class ControllerTest {
       @Override
       protected Map<String, String> getDefaultClusterConfigs() {
         Map<String, String> configs = super.getDefaultClusterConfigs();
-        configs.put(ControllerConf.DISABLE_GROOVY, "false");
+        configs.put(CommonConstants.Groovy.INGESTION_GROOVY_DISABLED, "false");
         return configs;
       }
     };
@@ -1593,12 +1593,13 @@ public class ControllerTest {
     ConfigAccessor configAccessor = _helixManager.getConfigAccessor();
     ClusterConfig clusterConfig = 
configAccessor.getClusterConfig(getHelixClusterName());
     if (value == null) {
-      
clusterConfig.getRecord().getSimpleFields().remove(ControllerConf.DISABLE_GROOVY);
+      
clusterConfig.getRecord().getSimpleFields().remove(CommonConstants.Groovy.INGESTION_GROOVY_DISABLED);
     } else {
-      clusterConfig.getRecord().setSimpleField(ControllerConf.DISABLE_GROOVY, 
value);
+      
clusterConfig.getRecord().setSimpleField(CommonConstants.Groovy.INGESTION_GROOVY_DISABLED,
 value);
     }
     configAccessor.setClusterConfig(getHelixClusterName(), clusterConfig);
-    boolean disabled = CommonConstants.Groovy.isIngestionGroovyDisabled(value);
+    boolean disabled =
+        
CommonConstants.Groovy.isControllerIngestionGroovyDisabled(clusterConfig.getRecord().getSimpleFields());
     TestUtils.waitForCondition(aVoid -> 
_controllerConfig.isDisableIngestionGroovy() == disabled, 10_000L,
         "Controller did not apply the cluster ingestion Groovy policy");
   }
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
index d6621592e1a..2d34bd77c14 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
@@ -2253,7 +2253,7 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
     _serverIngestionOomProtectionManager = 
realtimeTableDataManager.getServerIngestionOomProtectionManager();
     _segmentVersion = indexLoadingConfig.getSegmentVersion();
     _instanceId = _realtimeTableDataManager.getInstanceId();
-    _leaseExtender = 
SegmentBuildTimeLeaseExtender.getLeaseExtender(_tableNameWithType);
+    _leaseExtender = 
SegmentBuildTimeLeaseExtender.getLeaseExtender(_instanceId, _tableNameWithType);
     _protocolHandler = new 
ServerSegmentCompletionProtocolHandler(_serverMetrics, _tableNameWithType);
     CompletionConfig completionConfig = 
_tableConfig.getValidationConfig().getCompletionConfig();
     _segmentCompletionMode = completionConfig != null
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/SegmentBuildTimeLeaseExtender.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/SegmentBuildTimeLeaseExtender.java
index e57d32de871..40b997b81c2 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/SegmentBuildTimeLeaseExtender.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/SegmentBuildTimeLeaseExtender.java
@@ -26,6 +26,7 @@ import java.util.concurrent.Future;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
+import org.apache.commons.lang3.tuple.Pair;
 import org.apache.pinot.common.metrics.ServerMetrics;
 import org.apache.pinot.common.protocols.SegmentCompletionProtocol;
 import org.apache.pinot.server.realtime.ServerSegmentCompletionProtocolHandler;
@@ -44,20 +45,23 @@ public class SegmentBuildTimeLeaseExtender {
   // Retransmit lease request 10% before lease expires.
   private static final int REPEAT_REQUEST_PERIOD_SEC = (EXTRA_TIME_SECONDS * 9 
/ 10);
   private static final Logger LOGGER = 
LoggerFactory.getLogger(SegmentBuildTimeLeaseExtender.class);
-  private static final Map<String, SegmentBuildTimeLeaseExtender> 
TABLE_TO_LEASE_EXTENDER = new ConcurrentHashMap<>();
-  private static ScheduledExecutorService _executor;
+  private static final Map<Pair<String, String>, 
SegmentBuildTimeLeaseExtender> LEASE_EXTENDERS =
+      new ConcurrentHashMap<>();
+  private static volatile ScheduledExecutorService _executor;
 
   private final Map<String, Future> _segmentToFutureMap = new 
ConcurrentHashMap<>();
   private final String _instanceId;
   private final String _tableNameWithType;
   private final ServerSegmentCompletionProtocolHandler _protocolHandler;
 
-  public static void initExecutor() {
-    _executor = new ScheduledThreadPoolExecutor(1);
-    LOGGER.info("Initialized segment build time lease extender executor");
+  public static synchronized void initExecutor() {
+    if (_executor == null) {
+      _executor = new ScheduledThreadPoolExecutor(1);
+      LOGGER.info("Initialized segment build time lease extender executor");
+    }
   }
 
-  public static void shutdownExecutor() {
+  public static synchronized void shutdownExecutor() {
     if (_executor != null) {
       _executor.shutdownNow();
       _executor = null;
@@ -70,13 +74,19 @@ public class SegmentBuildTimeLeaseExtender {
     return _executor == null;
   }
 
+  /// Legacy lookup for callers running one server per JVM.
   public static SegmentBuildTimeLeaseExtender getLeaseExtender(final String 
tableNameWithType) {
-    return TABLE_TO_LEASE_EXTENDER.get(tableNameWithType);
+    return LEASE_EXTENDERS.values().stream().filter(extender -> 
extender._tableNameWithType.equals(tableNameWithType))
+        .findFirst().orElse(null);
+  }
+
+  public static SegmentBuildTimeLeaseExtender getLeaseExtender(String 
instanceId, String tableNameWithType) {
+    return LEASE_EXTENDERS.get(Pair.of(instanceId, tableNameWithType));
   }
 
   public static SegmentBuildTimeLeaseExtender getOrCreate(final String 
instanceId, ServerMetrics serverMetrics,
       String tableNameWithType) {
-    return TABLE_TO_LEASE_EXTENDER.compute(tableNameWithType, (k, v) -> {
+    return LEASE_EXTENDERS.compute(Pair.of(instanceId, tableNameWithType), (k, 
v) -> {
       if (v == null) {
         SegmentBuildTimeLeaseExtender leaseExtender =
             new SegmentBuildTimeLeaseExtender(instanceId, serverMetrics, 
tableNameWithType);
@@ -104,7 +114,7 @@ public class SegmentBuildTimeLeaseExtender {
       }
     }
     _segmentToFutureMap.clear();
-    TABLE_TO_LEASE_EXTENDER.remove(_tableNameWithType);
+    LEASE_EXTENDERS.remove(Pair.of(_instanceId, _tableNameWithType), this);
   }
 
   /// Adds a segment for periodic lease request.
diff --git 
a/pinot-minion/src/main/java/org/apache/pinot/minion/BaseMinionStarter.java 
b/pinot-minion/src/main/java/org/apache/pinot/minion/BaseMinionStarter.java
index 10868ad8cf6..332e1f579a1 100644
--- a/pinot-minion/src/main/java/org/apache/pinot/minion/BaseMinionStarter.java
+++ b/pinot-minion/src/main/java/org/apache/pinot/minion/BaseMinionStarter.java
@@ -48,6 +48,7 @@ import 
org.apache.pinot.common.utils.ClientSSLContextGenerator;
 import org.apache.pinot.common.utils.PinotAppConfigs;
 import org.apache.pinot.common.utils.ServiceStartableUtils;
 import org.apache.pinot.common.utils.ServiceStatus;
+import org.apache.pinot.common.utils.config.IngestionGroovyConfigListener;
 import org.apache.pinot.common.utils.fetcher.SegmentFetcherFactory;
 import org.apache.pinot.common.utils.helix.HelixHelper;
 import org.apache.pinot.common.utils.tls.PinotInsecureMode;
@@ -105,6 +106,8 @@ public abstract class BaseMinionStarter implements 
ServiceStartable {
   public void init(PinotConfiguration config)
       throws Exception {
     _config = new MinionConf(config.toMap());
+    _clusterConfigChangeHandler = new DefaultClusterConfigChangeHandler();
+    _clusterConfigChangeHandler.registerClusterConfigChangeListener(new 
IngestionGroovyConfigListener());
     String zkAddress = _config.getZkAddress();
     String helixClusterName = _config.getHelixClusterName();
     ServiceStartableUtils.applyClusterConfig(_config, zkAddress, 
helixClusterName, ServiceRole.MINION);
@@ -127,7 +130,6 @@ public abstract class BaseMinionStarter implements 
ServiceStartable {
     }
     _listenerConfigs = ListenerConfigUtil.buildMinionConfigs(_config);
     _tlsPort = ListenerConfigUtil.findLastTlsPort(_listenerConfigs, -1);
-    _clusterConfigChangeHandler = new DefaultClusterConfigChangeHandler();
     // Register cluster-level override for table configs
     _clusterConfigChangeHandler.registerClusterConfigChangeListener(
         new ClusterConfigForTable.ConfigChangeListener());
@@ -305,11 +307,8 @@ public abstract class BaseMinionStarter implements 
ServiceStartable {
     minionContext.setHelixPropertyStore(_helixManager.getHelixPropertyStore());
     minionContext.setHelixManager(_helixManager);
     LOGGER.info("Initializing and registering the 
DefaultClusterConfigChangeHandler");
-    try {
-      _helixManager.addClusterfigChangeListener(_clusterConfigChangeHandler);
-    } catch (Exception e) {
-      LOGGER.error("Failed to register DefaultClusterConfigChangeHandler as 
the Helix ClusterConfigChangeListener", e);
-    }
+    IngestionGroovyConfigListener.subscribeToClusterConfig(_helixManager, 
_clusterConfigChangeHandler,
+        _executorService::shutdownNow);
     LOGGER.info("Starting minion admin application on: {}", 
ListenerConfigUtil.toString(_listenerConfigs));
     _minionAdminApplication = createMinionAdminApp();
     _minionAdminApplication.start(_listenerConfigs);
diff --git 
a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
 
b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
index 7d4512ae4d4..370ca851b8a 100644
--- 
a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
+++ 
b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
@@ -74,6 +74,7 @@ import org.apache.pinot.common.utils.ServiceStartableUtils;
 import org.apache.pinot.common.utils.ServiceStatus;
 import org.apache.pinot.common.utils.ServiceStatus.Status;
 import org.apache.pinot.common.utils.TarCompressionUtils;
+import org.apache.pinot.common.utils.config.IngestionGroovyConfigListener;
 import org.apache.pinot.common.utils.config.QueryWorkloadConfigUtils;
 import org.apache.pinot.common.utils.config.TagNameUtils;
 import org.apache.pinot.common.utils.fetcher.SegmentFetcherFactory;
@@ -200,6 +201,8 @@ public abstract class BaseServerStarter implements 
ServiceStartable {
       throws Exception {
     // Make a clone so that changes to the config won't propagate to the caller
     _serverConf = serverConf.clone();
+    _clusterConfigChangeHandler = new DefaultClusterConfigChangeHandler();
+    _clusterConfigChangeHandler.registerClusterConfigChangeListener(new 
IngestionGroovyConfigListener());
     _zkAddress = 
_serverConf.getProperty(CommonConstants.Helix.CONFIG_OF_ZOOKEEPER_SERVER);
     _helixClusterName = 
_serverConf.getProperty(CommonConstants.Helix.CONFIG_OF_CLUSTER_NAME);
     ServiceStartableUtils.applyClusterConfig(_serverConf, _zkAddress, 
_helixClusterName, ServiceRole.SERVER);
@@ -276,8 +279,6 @@ public abstract class BaseServerStarter implements 
ServiceStartable {
     }
     DataTableBuilderFactory.setDataTableVersion(dataTableVersion);
 
-    _clusterConfigChangeHandler = new DefaultClusterConfigChangeHandler();
-
     // Register configuration change listener for dynamic max clause count 
updates
     _clusterConfigChangeHandler.registerClusterConfigChangeListener(
         new TextIndexUtils.LuceneMaxClauseCountConfigChangeListener());
@@ -842,11 +843,7 @@ public abstract class BaseServerStarter implements 
ServiceStartable {
         TimeUnit.SECONDS);
 
     LOGGER.info("Initializing and registering the 
DefaultClusterConfigChangeHandler");
-    try {
-      _helixManager.addClusterfigChangeListener(_clusterConfigChangeHandler);
-    } catch (Exception e) {
-      LOGGER.error("Failed to register DefaultClusterConfigChangeHandler as 
the Helix ClusterConfigChangeListener", e);
-    }
+    subscribeToClusterConfig(instanceDataManager);
     
_clusterConfigChangeHandler.registerClusterConfigChangeListener(_segmentOperationsThrottlerSet);
     
_clusterConfigChangeHandler.registerClusterConfigChangeListener(keepPipelineBreakerStatsPredicate);
     ResourceManager resourceManager = 
_serverInstance.getQueryScheduler().getResourceManager();
@@ -1053,6 +1050,13 @@ public abstract class BaseServerStarter implements 
ServiceStartable {
         false, ServerGauge.SEGMENT_DOWNLOAD_THROTTLE_THRESHOLD, 
ServerGauge.SEGMENT_DOWNLOAD_COUNT, "SegmentDownload");
   }
 
+  @VisibleForTesting
+  void subscribeToClusterConfig(InstanceDataManager instanceDataManager) {
+    // Only the data manager has started. Full server shutdown would also stop 
the process-wide metrics registry.
+    IngestionGroovyConfigListener.subscribeToClusterConfig(_helixManager, 
_clusterConfigChangeHandler,
+        _helixMessageCountScheduler::shutdownNow, 
instanceDataManager::shutDown);
+  }
+
   /// Can be overridden to perform operations before server starts serving 
queries.
   protected void preServeQueries() {
     triggerPageCacheWarmup();
diff --git 
a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java
 
b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java
index df673ce8655..be395294ddf 100644
--- 
a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java
+++ 
b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManager.java
@@ -90,6 +90,10 @@ import static java.util.Objects.requireNonNull;
 public class HelixInstanceDataManager implements InstanceDataManager {
   private static final Logger LOGGER = 
LoggerFactory.getLogger(HelixInstanceDataManager.class);
 
+  // Under the class lock, co-located servers share the lease executor until 
the last manager shuts down.
+  private static int _leaseExecutorUsers;
+  private boolean _ownsLeaseExecutor;
+
   private final Map<String, TableDataManager> _tableDataManagerMap = new 
ConcurrentHashMap<>();
   /// Serializes table creation with the previous owner's entire shutdown, 
including table-scoped resource cleanup
   /// such as the segment build time lease extender. Acquire it before 
changing [#_tableDataManagerMap], and release
@@ -169,8 +173,6 @@ public class HelixInstanceDataManager implements 
InstanceDataManager {
     initInstanceDataDir();
     initInstanceSegmentTarDir();
 
-    // Initialize segment build time lease extender executor
-    SegmentBuildTimeLeaseExtender.initExecutor();
     // Initialize a semaphore and a fixed thread pool to reload/refresh 
segments in parallel.
     int maxParallelRefreshThreads = getMaxParallelRefreshThreads();
     Preconditions.checkArgument(maxParallelRefreshThreads > 0,
@@ -195,6 +197,13 @@ public class HelixInstanceDataManager implements 
InstanceDataManager {
     _errorCache = 
CacheBuilder.newBuilder().maximumSize(_instanceDataManagerConfig.getErrorCacheSize()).build();
     _recentlyDeletedTables = CacheBuilder.newBuilder()
         
.expireAfterWrite(_instanceDataManagerConfig.getDeletedTablesCacheTtlMinutes(), 
TimeUnit.MINUTES).build();
+    synchronized (HelixInstanceDataManager.class) {
+      if (!_ownsLeaseExecutor) {
+        SegmentBuildTimeLeaseExtender.initExecutor();
+        _leaseExecutorUsers++;
+        _ownsLeaseExecutor = true;
+      }
+    }
   }
 
   ServerIngestionOomProtectionManager.ServerThrottleState 
getServerIngestionOomProtectionThrottleState() {
@@ -314,7 +323,14 @@ public class HelixInstanceDataManager implements 
InstanceDataManager {
         Thread.currentThread().interrupt();
       }
     }
-    SegmentBuildTimeLeaseExtender.shutdownExecutor();
+    synchronized (HelixInstanceDataManager.class) {
+      if (_ownsLeaseExecutor) {
+        _ownsLeaseExecutor = false;
+        if (--_leaseExecutorUsers == 0) {
+          SegmentBuildTimeLeaseExtender.shutdownExecutor();
+        }
+      }
+    }
     // shutdown logical table metadata cache
     _logicalTableMetadataCache.shutdown();
     LOGGER.info("Helix instance data manager shut down");
diff --git 
a/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/BaseServerStarterTest.java
 
b/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/BaseServerStarterTest.java
index 2bc7645522b..d884f8d200a 100644
--- 
a/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/BaseServerStarterTest.java
+++ 
b/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/BaseServerStarterTest.java
@@ -18,17 +18,46 @@
  */
 package org.apache.pinot.server.starter.helix;
 
+import java.util.concurrent.ScheduledExecutorService;
+import org.apache.helix.HelixManager;
+import org.apache.pinot.common.config.DefaultClusterConfigChangeHandler;
+import org.apache.pinot.common.evaluator.GroovyFunctionEvaluator;
+import org.apache.pinot.core.data.manager.InstanceDataManager;
+import org.apache.pinot.server.starter.ServerInstance;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.utils.CommonConstants.Helix;
 import org.apache.pinot.spi.utils.NetUtils;
 import org.mockito.MockedStatic;
 import org.testng.annotations.Test;
 
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mockStatic;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.expectThrows;
 
 public class BaseServerStarterTest {
+  @Test
+  public void testMissingClusterConfigCallbackCleansUpStartedServerResources() 
{
+    HelixServerStarter starter = new HelixServerStarter();
+    starter._helixManager = mock(HelixManager.class);
+    starter._clusterConfigChangeHandler = new 
DefaultClusterConfigChangeHandler();
+    starter._helixMessageCountScheduler = mock(ScheduledExecutorService.class);
+    starter._serverInstance = mock(ServerInstance.class);
+    InstanceDataManager dataManager = mock(InstanceDataManager.class);
+    try {
+      expectThrows(IllegalStateException.class, () -> 
starter.subscribeToClusterConfig(dataManager));
+      verify(starter._helixManager).disconnect();
+      verify(starter._helixMessageCountScheduler).shutdownNow();
+      verify(dataManager).shutDown();
+      verifyNoInteractions(starter._serverInstance);
+    } finally {
+      GroovyFunctionEvaluator.setIngestionGroovyDisabled(false);
+    }
+  }
+
   @Test
   public void testConfiguredServerHostDoesNotResolveDefaultHost()
       throws Exception {
diff --git 
a/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManagerTest.java
 
b/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManagerTest.java
index 1cedf716222..f31cba5bf70 100644
--- 
a/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManagerTest.java
+++ 
b/pinot-server/src/test/java/org/apache/pinot/server/starter/helix/HelixInstanceDataManagerTest.java
@@ -22,9 +22,16 @@ import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.util.Map;
+import java.util.concurrent.Future;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.helix.HelixManager;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import 
org.apache.pinot.core.data.manager.realtime.SegmentBuildTimeLeaseExtender;
+import org.apache.pinot.segment.local.utils.ServerReloadJobStatusCache;
 import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.stream.LongMsgOffset;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
@@ -33,9 +40,12 @@ import static 
org.apache.pinot.spi.utils.CommonConstants.Server.INSTANCE_DATA_DI
 import static 
org.apache.pinot.spi.utils.CommonConstants.Server.INSTANCE_DATA_DIR_FAIL_ON_MISSING;
 import static org.apache.pinot.spi.utils.CommonConstants.Server.INSTANCE_ID;
 import static 
org.apache.pinot.spi.utils.CommonConstants.Server.INSTANCE_SEGMENT_TAR_DIR;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertSame;
 import static org.testng.Assert.assertTrue;
 import static org.testng.Assert.expectThrows;
 import static org.testng.Assert.fail;
@@ -71,6 +81,49 @@ public class HelixInstanceDataManagerTest {
     return manager;
   }
 
+  @Test
+  public void testShuttingDownOneServerPreservesLeaseRenewalForAnother()
+      throws Exception {
+    HelixInstanceDataManager survivor = startDataManager("survivor");
+    try {
+      String table = "leaseOwnerTest_REALTIME";
+      SegmentBuildTimeLeaseExtender extender = 
SegmentBuildTimeLeaseExtender.getOrCreate(survivor.getInstanceId(),
+          mock(ServerMetrics.class), table);
+      try {
+        extender.addSegment("segment", 120_000L, new LongMsgOffset(0L));
+        Map<?, ?> leases = (Map<?, ?>) FieldUtils.readField(extender, 
"_segmentToFutureMap", true);
+        Future<?> lease = (Future<?>) leases.get("segment");
+        HelixInstanceDataManager other = startDataManager("other");
+        try {
+          SegmentBuildTimeLeaseExtender.getOrCreate(other.getInstanceId(), 
mock(ServerMetrics.class), table).shutDown();
+        } finally {
+          other.shutDown();
+        }
+        assertFalse(lease.isCancelled());
+        
assertSame(SegmentBuildTimeLeaseExtender.getLeaseExtender(survivor.getInstanceId(),
 table), extender);
+        extender.addSegment("nextSegment", 120_000L, new LongMsgOffset(1L));
+      } finally {
+        extender.shutDown();
+      }
+    } finally {
+      survivor.shutDown();
+    }
+    assertTrue(SegmentBuildTimeLeaseExtender.isExecutorShutdown());
+  }
+
+  private HelixInstanceDataManager startDataManager(String instanceId)
+      throws Exception {
+    HelixManager helixManager = mock(HelixManager.class);
+    
doReturn(mock(ZkHelixPropertyStore.class)).when(helixManager).getHelixPropertyStore();
+    PinotConfiguration config = new PinotConfiguration(Map.of(INSTANCE_ID, 
instanceId,
+        INSTANCE_DATA_DIR, new File(_testDir, instanceId + "/data").toString(),
+        INSTANCE_SEGMENT_TAR_DIR, new File(_testDir, instanceId + 
"/tar").toString()));
+    HelixInstanceDataManager manager = new HelixInstanceDataManager();
+    manager.init(config, helixManager, mock(ServerMetrics.class), null, new 
ServerReloadJobStatusCache(instanceId));
+    manager.start();
+    return manager;
+  }
+
   @Test
   public void testInitInstanceDataDirCreatesDirectory() {
     if (_testInstanceDataDir.exists()) {
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
index 5e5ff488881..5e4ca875113 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
@@ -3330,13 +3330,20 @@ public class CommonConstants {
   /// User can config different configuration for query and ingestion (table 
creation and update) static analyzer.
   /// The all configuration is the default configuration for both query and 
ingestion static analyzer.
   public static class Groovy {
-    /// Cluster-only switch for ingestion Groovy. Query Groovy remains 
independently controlled.
+    /// Cluster-wide ingestion policy for controllers, servers and minions.
+    public static final String INGESTION_GROOVY_DISABLED = 
"pinot.groovy.ingestion.disabled";
+    /// Legacy cluster key used by controllers when the role-neutral key is 
absent.
     public static final String DISABLE_INGESTION_GROOVY = 
"controller.disable.ingestion.groovy";
     public static final boolean DEFAULT_DISABLE_INGESTION_GROOVY = true;
     public static final String GROOVY_ALL_STATIC_ANALYZER_CONFIG = 
"pinot.groovy.all.static.analyzer";
     public static final String GROOVY_QUERY_STATIC_ANALYZER_CONFIG = 
"pinot.groovy.query.static.analyzer";
     public static final String GROOVY_INGESTION_STATIC_ANALYZER_CONFIG = 
"pinot.groovy.ingestion.static.analyzer";
 
+    public static boolean isControllerIngestionGroovyDisabled(Map<String, 
String> clusterConfigs) {
+      String value = clusterConfigs.get(INGESTION_GROOVY_DISABLED);
+      return isIngestionGroovyDisabled(value != null ? value : 
clusterConfigs.get(DISABLE_INGESTION_GROOVY));
+    }
+
     /// Only an explicit false enables ingestion Groovy; absent or malformed 
values fail closed.
     public static boolean isIngestionGroovyDisabled(@Nullable String value) {
       return value == null || !value.trim().equalsIgnoreCase("false");


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

Reply via email to