You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by "J-HowHuang (via GitHub)" <gi...@apache.org> on 2025/07/29 22:17:34 UTC

[PR] [WIP] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

J-HowHuang opened a new pull request, #16455:
URL: https://github.com/apache/pinot/pull/16455

   ## Summary
   
   This PR introduces a new  component to improve tenant rebalance monitoring and control in Pinot.
   
   ## Changes
   
   ### New Components
   - **TenantRebalanceChecker**: A new checker component that monitors tenant rebalance operations
   - **TenantRebalanceContext**: Context object to store rebalance job metadata and allow resuming operations
   - **DefaultTenantRebalanceContext**: Implementation of the tenant rebalance context
   
   ### Enhanced Functionality
   - Added parallel and sequential queue management for tenant rebalance operations
   - Integrated  into the controller starter
   - Enhanced REST API with parallel whitelist and blacklist support in Swagger
   - Improved ZK-based tenant rebalance observer with better progress tracking
   
   ### Testing
   - Added comprehensive test coverage with 
   - Enhanced existing  with additional test cases
   - Added tests for  functionality
   
   ## Technical Details
   
   - **Files Modified**: 12 files
   - **Lines Added**: 1,230 insertions
   - **Lines Removed**: 195 deletions
   - **New Classes**: 3 major new classes
   - **Test Coverage**: 495+ lines of new test code
   
   ## Benefits
   
   1. **Better Monitoring**: Real-time checking of tenant rebalance operations
   2. **Resumable Operations**: Context persistence allows resuming interrupted rebalance jobs
   3. **Improved Control**: Parallel and sequential queue management for better resource utilization
   4. **Enhanced API**: Better REST API support with proper Swagger documentation
   
   ## Testing
   
   - All existing tests pass
   - New comprehensive test suite added
   - Manual testing performed for tenant rebalance scenarios


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2294486468


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+
+/**
+ * Abstract class for tracking job configs and attempt numbers as part of the job ZK metadata to retry failed tenant
+ * rebalance.
+ */
+public abstract class TenantRebalanceContext {
+  protected static final int INITIAL_ATTEMPT_ID = 1;
+  @JsonProperty("jobId")
+  private final String _jobId;
+  @JsonProperty("originalJobId")
+  private final String _originalJobId;
+  @JsonProperty("config")
+  private final TenantRebalanceConfig _config;
+  @JsonProperty("attemptId")
+  private final int _attemptId;
+  // Default to true for all user initiated rebalances, so that they can be retried if they fail or get stuck.
+  @JsonProperty("allowRetries")
+  private final boolean _allowRetries;

Review Comment:
   removed. this was copied from `TableRebalanceContext`



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/DefaultTenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+
+/**
+ * Default implementation of TenantRebalanceContext that includes parallel and sequential queues
+ * for managing tenant rebalance operations.
+ */
+public class DefaultTenantRebalanceContext extends TenantRebalanceContext {
+  private final ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> _parallelQueue;
+  private final Queue<TenantRebalancer.TenantTableRebalanceJobContext> _sequentialQueue;
+  private final ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> _ongoingJobsQueue;
+
+  public DefaultTenantRebalanceContext() {
+    super();
+    _parallelQueue = new ConcurrentLinkedDeque<>();
+    _sequentialQueue = new LinkedList<>();
+    _ongoingJobsQueue = new ConcurrentLinkedQueue<>();
+  }
+
+  public DefaultTenantRebalanceContext(String originalJobId, TenantRebalanceConfig config, int attemptId,
+      boolean allowRetries, ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue,

Review Comment:
   removed. this was copied from `TableRebalanceContext`



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2294441827


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;

Review Comment:
   removed



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2294477364


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/DefaultTenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+
+/**
+ * Default implementation of TenantRebalanceContext that includes parallel and sequential queues
+ * for managing tenant rebalance operations.
+ */
+public class DefaultTenantRebalanceContext extends TenantRebalanceContext {
+  private final ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> _parallelQueue;
+  private final Queue<TenantRebalancer.TenantTableRebalanceJobContext> _sequentialQueue;
+  private final ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> _ongoingJobsQueue;
+
+  public DefaultTenantRebalanceContext() {

Review Comment:
   It's needed for JSON deserialization



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "yashmayya (via GitHub)" <gi...@apache.org>.
yashmayya commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2293550323


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/DefaultTenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+
+/**
+ * Default implementation of TenantRebalanceContext that includes parallel and sequential queues
+ * for managing tenant rebalance operations.
+ */
+public class DefaultTenantRebalanceContext extends TenantRebalanceContext {
+  private final ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> _parallelQueue;
+  private final Queue<TenantRebalancer.TenantTableRebalanceJobContext> _sequentialQueue;
+  private final ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> _ongoingJobsQueue;
+
+  public DefaultTenantRebalanceContext() {
+    super();
+    _parallelQueue = new ConcurrentLinkedDeque<>();
+    _sequentialQueue = new LinkedList<>();
+    _ongoingJobsQueue = new ConcurrentLinkedQueue<>();
+  }
+
+  public DefaultTenantRebalanceContext(String originalJobId, TenantRebalanceConfig config, int attemptId,
+      boolean allowRetries, ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue,

Review Comment:
   What's `allowRetries` being used for in this context?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,

Review Comment:
   `ControllerMetrics` is unused here?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/DefaultTenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+
+/**
+ * Default implementation of TenantRebalanceContext that includes parallel and sequential queues
+ * for managing tenant rebalance operations.
+ */
+public class DefaultTenantRebalanceContext extends TenantRebalanceContext {
+  private final ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> _parallelQueue;
+  private final Queue<TenantRebalancer.TenantTableRebalanceJobContext> _sequentialQueue;
+  private final ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> _ongoingJobsQueue;
+
+  public DefaultTenantRebalanceContext() {

Review Comment:
   Unused?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);
+          }
+          // the retry tenant rebalance job id has been created in ZK, we can safely mark the original job as
+          // aborted, so that this original job will not be picked up again in the future.
+          markTenantRebalanceJobAsAborted(jobId, jobZKMetadata, tenantRebalanceContext, progressStats);
+          retryTenantRebalanceJob(retryTenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void retryTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContextForRetry,
+      TenantRebalanceProgressStats progressStats) {
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContextForRetry.getJobId(),
+            tenantRebalanceContextForRetry.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);
+  }
+
+  /**
+   * Check if the tenant rebalance job is stuck, and prepare to retry it if necessary.
+   * A tenant rebalance job is considered stuck if:
+   * 1. There are no ongoing jobs, but there are jobs in the parallel or sequential queue, and the stats have not been
+   *    updated for longer than the heartbeat timeout.
+   * 2. There are ongoing table rebalance jobs, and at least one of them has not updated its status for longer than the
+   *    heartbeat timeout.
+   * The retry is prepared by creating a new tenant rebalance job with an incremented attempt ID, and persisting it to
+   * ZK.
+   *
+   * @param jobZKMetadata The ZK metadata of the tenant rebalance job.
+   * @param tenantRebalanceContext The context of the tenant rebalance job.
+   * @param statsUpdatedAt The timestamp when the stats were last updated.
+   * @return The TenantRebalanceContext for retry if the tenant rebalance job is stuck and should be retried, null if
+   * other controller has prepared the retry first.

Review Comment:
   > null if other controller has prepared the retry first
   
   Or if tenant rebalance is not stuck and no retry is needed?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);
+          }
+          // the retry tenant rebalance job id has been created in ZK, we can safely mark the original job as
+          // aborted, so that this original job will not be picked up again in the future.
+          markTenantRebalanceJobAsAborted(jobId, jobZKMetadata, tenantRebalanceContext, progressStats);
+          retryTenantRebalanceJob(retryTenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void retryTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContextForRetry,
+      TenantRebalanceProgressStats progressStats) {
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContextForRetry.getJobId(),
+            tenantRebalanceContextForRetry.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);
+  }
+
+  /**
+   * Check if the tenant rebalance job is stuck, and prepare to retry it if necessary.
+   * A tenant rebalance job is considered stuck if:
+   * 1. There are no ongoing jobs, but there are jobs in the parallel or sequential queue, and the stats have not been
+   *    updated for longer than the heartbeat timeout.
+   * 2. There are ongoing table rebalance jobs, and at least one of them has not updated its status for longer than the

Review Comment:
   I think these checks make sense but do add one line explaining the logic here (for instance, why we can't simply use heartbeat timeout check on the overall tenant rebalance stats). It's usually more useful to describe _why_ something is being done rather than simply describing _what_ is being done.



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/DefaultTenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+
+/**
+ * Default implementation of TenantRebalanceContext that includes parallel and sequential queues
+ * for managing tenant rebalance operations.
+ */
+public class DefaultTenantRebalanceContext extends TenantRebalanceContext {

Review Comment:
   Why do we need the base abstract `TenantRebalanceContext` class if this is the only implementation?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);
+          }
+          // the retry tenant rebalance job id has been created in ZK, we can safely mark the original job as
+          // aborted, so that this original job will not be picked up again in the future.

Review Comment:
   What happens if the controller crashes after writing the retry job metadata to ZK, but before marking the original as aborted? What if it crashes after writing + aborting, but before retrying (I guess this will simply manifest as a subsequent stuck job + another retry)?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;

Review Comment:
   Unused?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,221 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context.
+ * <p>
+ * Notice that this is not a retry but a resume, since we will not re-do the table rebalance for those tables that have
+ * already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        if (isTenantRebalanceJobStuck(tenantRebalanceContext, statsUpdatedAt)) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = tenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            tenantRebalanceContext.getParallelQueue().addFirst(ctx);
+          }
+          // If the job is stuck, we retry it
+          resumeTenantRebalanceJob(tenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void resumeTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContext,
+      TenantRebalanceProgressStats progressStats) {
+    DefaultTenantRebalanceContext tenantRebalanceContextForRetry =
+        DefaultTenantRebalanceContext.forRetry(tenantRebalanceContext.getOriginalJobId(),
+            tenantRebalanceContext.getConfig(), tenantRebalanceContext.getAttemptId() + 1,
+            tenantRebalanceContext.getParallelQueue(),
+            tenantRebalanceContext.getSequentialQueue(), tenantRebalanceContext.getOngoingJobsQueue());
+
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContext.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);

Review Comment:
   Yes, +1 on consolidating - I made a similar comment elsewhere.



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);

Review Comment:
   Why is this always added to the parallel queue?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/DefaultTenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+
+/**
+ * Default implementation of TenantRebalanceContext that includes parallel and sequential queues
+ * for managing tenant rebalance operations.
+ */
+public class DefaultTenantRebalanceContext extends TenantRebalanceContext {
+  private final ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> _parallelQueue;
+  private final Queue<TenantRebalancer.TenantTableRebalanceJobContext> _sequentialQueue;
+  private final ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> _ongoingJobsQueue;

Review Comment:
   Can you add some comments here explaining how `_parallelQueue` and `_ongoingJobsQueue` are being used and why they need to be concurrent / thread-safe data structures?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceContext.java:
##########
@@ -0,0 +1,87 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+
+/**
+ * Abstract class for tracking job configs and attempt numbers as part of the job ZK metadata to retry failed tenant
+ * rebalance.
+ */
+public abstract class TenantRebalanceContext {
+  protected static final int INITIAL_ATTEMPT_ID = 1;
+  @JsonProperty("jobId")
+  private final String _jobId;
+  @JsonProperty("originalJobId")
+  private final String _originalJobId;
+  @JsonProperty("config")
+  private final TenantRebalanceConfig _config;
+  @JsonProperty("attemptId")
+  private final int _attemptId;
+  // Default to true for all user initiated rebalances, so that they can be retried if they fail or get stuck.
+  @JsonProperty("allowRetries")
+  private final boolean _allowRetries;

Review Comment:
   Aren't tenant rebalances always user initiated?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);
+          }
+          // the retry tenant rebalance job id has been created in ZK, we can safely mark the original job as
+          // aborted, so that this original job will not be picked up again in the future.
+          markTenantRebalanceJobAsAborted(jobId, jobZKMetadata, tenantRebalanceContext, progressStats);
+          retryTenantRebalanceJob(retryTenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void retryTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContextForRetry,
+      TenantRebalanceProgressStats progressStats) {
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContextForRetry.getJobId(),
+            tenantRebalanceContextForRetry.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);
+  }
+
+  /**
+   * Check if the tenant rebalance job is stuck, and prepare to retry it if necessary.
+   * A tenant rebalance job is considered stuck if:
+   * 1. There are no ongoing jobs, but there are jobs in the parallel or sequential queue, and the stats have not been
+   *    updated for longer than the heartbeat timeout.
+   * 2. There are ongoing table rebalance jobs, and at least one of them has not updated its status for longer than the

Review Comment:
   nit: either use `///` style for a markdown style comment (https://openjdk.org/jeps/467) or else use formatting tags like `<ol>`, `<li>`, `<p>` etc.



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {

Review Comment:
   I think a while loop would be more readable here.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2302228066


##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;
+  @Mock
+  private ControllerConf _mockControllerConf;
+
+  private TenantRebalanceChecker _tenantRebalanceChecker;
+  private ExecutorService _executorService;
+
+  @BeforeMethod
+  public void setUp() {
+    MockitoAnnotations.openMocks(this);
+    _executorService = Executors.newFixedThreadPool(2);
+
+    // Setup default mock behaviors
+    when(_mockControllerConf.getTenantRebalanceCheckerFrequencyInSeconds()).thenReturn(300);
+    when(_mockControllerConf.getTenantRebalanceCheckerInitialDelayInSeconds()).thenReturn(300L);
+    // mock ZK update success
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE));
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    _tenantRebalanceChecker = new TenantRebalanceChecker(
+        _mockControllerConf,
+        _mockPinotHelixResourceManager,
+        _mockTenantRebalancer
+    );
+  }
+
+  @AfterMethod
+  public void tearDown() {
+    if (_executorService != null) {
+      _executorService.shutdown();
+    }
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called to resume the job
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+
+    // Verify the resumed context
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertNotNull(resumedContext);
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getOriginalJobId(), ORIGINAL_JOB_ID);
+    assertEquals(resumedContext.getAttemptId(), 2); // Should be incremented from 1
+    assertEquals(resumedContext.getConfig().getTenantName(), TENANT_NAME);
+
+    // Verify that the stuck table job context was moved back to parallel queue
+    TenantRebalancer.TenantTableRebalanceJobContext firstJobContextInParallelQueue =
+        resumedContext.getParallelQueue().poll();
+    assertNotNull(firstJobContextInParallelQueue);
+    // because the stuck job is aborted, a new job ID is generated
+    assertNotEquals(firstJobContextInParallelQueue.getJobId(), STUCK_TABLE_JOB_ID);
+    assertEquals(firstJobContextInParallelQueue.getTableName(), TABLE_NAME_1);
+    assertFalse(firstJobContextInParallelQueue.shouldRebalanceWithDowntime());
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+
+    // Verify the observer was created with correct parameters
+    ZkBasedTenantRebalanceObserver observer = observerCaptor.getValue();
+    assertNotNull(observer);
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJobWithMultipleStuckTables()
+      throws Exception {
+    // Create a context with multiple stuck table jobs
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContextWithMultipleTables();
+    TenantRebalanceProgressStats progressStats = createProgressStatsWithMultipleTables();
+
+    // Mock ZK metadata
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table job metadata for both tables
+    Map<String, String> stuckTableJobMetadata1 = createStuckTableJobMetadata();
+    Map<String, String> stuckTableJobMetadata2 = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata1).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(stuckTableJobMetadata2).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID_2), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), any(ZkBasedTenantRebalanceObserver.class));
+
+    // Verify that both stuck table jobs were moved back to parallel queue
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getParallelQueue().size(), 2);
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithoutOngoing = createNonStuckTenantRebalanceContextWithoutOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithoutOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithoutOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithoutOngoing);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJobWithOngoing()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithOngoing = createNonStuckTenantRebalanceContextWithOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithOngoing);
+
+    // Mock non-stuck table rebalance job metadata
+    Map<String, String> nonStuckTableJobMetadata = createNonStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(nonStuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(NON_STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeTenantRebalanceJobWhileZKUpdateFailed()
+      throws Exception {
+
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(false).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called because ZK update failed
+    verify(_mockTenantRebalancer, times(0)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+  }
+
+  @Test
+  public void testHandleCorruptedZKMetadata()
+      throws Exception {
+    // Create corrupted ZK metadata (missing required fields)
+    Map<String, String> corruptedJobZKMetadata = new HashMap<>();
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_ID, JOB_ID);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.TENANT_NAME, TENANT_NAME);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS,
+        String.valueOf(System.currentTimeMillis()));
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_TYPE, ControllerJobTypes.TENANT_REBALANCE.name());
+    // Provide invalid JSON to trigger JsonProcessingException
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT, "invalid json");
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS, "invalid json");
+
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, corruptedJobZKMetadata);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker - should not throw exception
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testHandleJsonProcessingException()

Review Comment:
   hmm right, removed one



##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;

Review Comment:
   removed



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2302228452


##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;
+  @Mock
+  private ControllerConf _mockControllerConf;
+
+  private TenantRebalanceChecker _tenantRebalanceChecker;
+  private ExecutorService _executorService;
+
+  @BeforeMethod
+  public void setUp() {
+    MockitoAnnotations.openMocks(this);
+    _executorService = Executors.newFixedThreadPool(2);
+
+    // Setup default mock behaviors
+    when(_mockControllerConf.getTenantRebalanceCheckerFrequencyInSeconds()).thenReturn(300);
+    when(_mockControllerConf.getTenantRebalanceCheckerInitialDelayInSeconds()).thenReturn(300L);
+    // mock ZK update success
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE));
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    _tenantRebalanceChecker = new TenantRebalanceChecker(
+        _mockControllerConf,
+        _mockPinotHelixResourceManager,
+        _mockTenantRebalancer
+    );
+  }
+
+  @AfterMethod
+  public void tearDown() {
+    if (_executorService != null) {
+      _executorService.shutdown();
+    }
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called to resume the job
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+
+    // Verify the resumed context
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertNotNull(resumedContext);
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getOriginalJobId(), ORIGINAL_JOB_ID);
+    assertEquals(resumedContext.getAttemptId(), 2); // Should be incremented from 1
+    assertEquals(resumedContext.getConfig().getTenantName(), TENANT_NAME);
+
+    // Verify that the stuck table job context was moved back to parallel queue
+    TenantRebalancer.TenantTableRebalanceJobContext firstJobContextInParallelQueue =
+        resumedContext.getParallelQueue().poll();
+    assertNotNull(firstJobContextInParallelQueue);
+    // because the stuck job is aborted, a new job ID is generated
+    assertNotEquals(firstJobContextInParallelQueue.getJobId(), STUCK_TABLE_JOB_ID);
+    assertEquals(firstJobContextInParallelQueue.getTableName(), TABLE_NAME_1);
+    assertFalse(firstJobContextInParallelQueue.shouldRebalanceWithDowntime());
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+
+    // Verify the observer was created with correct parameters
+    ZkBasedTenantRebalanceObserver observer = observerCaptor.getValue();
+    assertNotNull(observer);
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJobWithMultipleStuckTables()
+      throws Exception {
+    // Create a context with multiple stuck table jobs
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContextWithMultipleTables();
+    TenantRebalanceProgressStats progressStats = createProgressStatsWithMultipleTables();
+
+    // Mock ZK metadata
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table job metadata for both tables
+    Map<String, String> stuckTableJobMetadata1 = createStuckTableJobMetadata();
+    Map<String, String> stuckTableJobMetadata2 = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata1).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(stuckTableJobMetadata2).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID_2), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), any(ZkBasedTenantRebalanceObserver.class));
+
+    // Verify that both stuck table jobs were moved back to parallel queue
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getParallelQueue().size(), 2);
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithoutOngoing = createNonStuckTenantRebalanceContextWithoutOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithoutOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithoutOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithoutOngoing);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJobWithOngoing()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithOngoing = createNonStuckTenantRebalanceContextWithOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithOngoing);
+
+    // Mock non-stuck table rebalance job metadata
+    Map<String, String> nonStuckTableJobMetadata = createNonStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(nonStuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(NON_STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeTenantRebalanceJobWhileZKUpdateFailed()
+      throws Exception {
+
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(false).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called because ZK update failed
+    verify(_mockTenantRebalancer, times(0)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+  }
+
+  @Test
+  public void testHandleCorruptedZKMetadata()
+      throws Exception {
+    // Create corrupted ZK metadata (missing required fields)
+    Map<String, String> corruptedJobZKMetadata = new HashMap<>();
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_ID, JOB_ID);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.TENANT_NAME, TENANT_NAME);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS,
+        String.valueOf(System.currentTimeMillis()));
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_TYPE, ControllerJobTypes.TENANT_REBALANCE.name());
+    // Provide invalid JSON to trigger JsonProcessingException
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT, "invalid json");
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS, "invalid json");
+
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, corruptedJobZKMetadata);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker - should not throw exception
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testHandleJsonProcessingException()
+      throws Exception {
+    // Create ZK metadata with invalid JSON
+    Map<String, String> invalidJsonJobZKMetadata = new HashMap<>();
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.JOB_ID, JOB_ID);
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.TENANT_NAME, TENANT_NAME);
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS,
+        String.valueOf(System.currentTimeMillis()));
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.JOB_TYPE, ControllerJobTypes.TENANT_REBALANCE.name());
+    invalidJsonJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT, "invalid json");
+    invalidJsonJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS, "invalid json");
+
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, invalidJsonJobZKMetadata);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker - should not throw exception
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  // Helper methods to create test data
+
+  private DefaultTenantRebalanceContext createStuckTenantRebalanceContext() {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L); // 5 minutes
+
+    ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue =
+        new ConcurrentLinkedDeque<>();
+    ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> ongoingJobsQueue =
+        new ConcurrentLinkedQueue<>();
+
+    // Add a stuck table job to ongoing queue
+    TenantRebalancer.TenantTableRebalanceJobContext stuckJobContext =
+        new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, STUCK_TABLE_JOB_ID, false);
+    ongoingJobsQueue.add(stuckJobContext);
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, parallelQueue,
+        new ConcurrentLinkedQueue<>(), ongoingJobsQueue);
+  }
+
+  private DefaultTenantRebalanceContext createStuckTenantRebalanceContextWithMultipleTables()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue =
+        new ConcurrentLinkedDeque<>();
+    ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> ongoingJobsQueue =
+        new ConcurrentLinkedQueue<>();
+
+    // Add multiple stuck table jobs to ongoing queue
+    ongoingJobsQueue.add(new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, STUCK_TABLE_JOB_ID, false));
+    ongoingJobsQueue.add(
+        new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_2, STUCK_TABLE_JOB_ID_2, false));
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, parallelQueue,
+        new ConcurrentLinkedQueue<>(), ongoingJobsQueue);
+  }
+
+  private DefaultTenantRebalanceContext createNonStuckTenantRebalanceContextWithoutOngoing()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue =
+        new ConcurrentLinkedDeque<>();
+    // Add some jobs to parallel queue but none to ongoing queue
+    parallelQueue.add(new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, NON_STUCK_TABLE_JOB_ID, false));
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, parallelQueue,
+        new ConcurrentLinkedQueue<>(), new ConcurrentLinkedQueue<>());
+  }
+
+  private DefaultTenantRebalanceContext createNonStuckTenantRebalanceContextWithOngoing()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> ongoing =
+        new ConcurrentLinkedQueue<>();
+    // Add some jobs to parallel queue but none to ongoing queue
+    ongoing.add(new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, NON_STUCK_TABLE_JOB_ID, false));
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, new ConcurrentLinkedDeque<>(),
+        new ConcurrentLinkedQueue<>(), ongoing);
+  }
+
+  private DefaultTenantRebalanceContext createRecentTenantRebalanceContext()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1,
+        new ConcurrentLinkedDeque<>(), new ConcurrentLinkedQueue<>(), new ConcurrentLinkedQueue<>());
+  }
+
+  private DefaultTenantRebalanceContext createOldTenantRebalanceContext()

Review Comment:
   removed



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "yashmayya (via GitHub)" <gi...@apache.org>.
yashmayya commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2306839290


##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;

Review Comment:
   I still see them, did you forget to push a commit?



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] [WIP] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2244467978


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,221 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context.
+ * <p>
+ * Notice that this is not a retry but a resume, since we will not re-do the table rebalance for those tables that have
+ * already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        if (isTenantRebalanceJobStuck(tenantRebalanceContext, statsUpdatedAt)) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = tenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            tenantRebalanceContext.getParallelQueue().addFirst(ctx);
+          }
+          // If the job is stuck, we retry it
+          resumeTenantRebalanceJob(tenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void resumeTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContext,
+      TenantRebalanceProgressStats progressStats) {
+    DefaultTenantRebalanceContext tenantRebalanceContextForRetry =
+        DefaultTenantRebalanceContext.forRetry(tenantRebalanceContext.getOriginalJobId(),
+            tenantRebalanceContext.getConfig(), tenantRebalanceContext.getAttemptId() + 1,
+            tenantRebalanceContext.getParallelQueue(),
+            tenantRebalanceContext.getSequentialQueue(), tenantRebalanceContext.getOngoingJobsQueue());
+
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContext.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);

Review Comment:
   The cast to DefaultTenantRebalancer indicates a potential design issue. Consider adding the rebalanceWithContext method to the TenantRebalancer interface to avoid casting and improve type safety.



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalancer.java:
##########
@@ -35,7 +39,9 @@ class TenantTableRebalanceJobContext {
      * @param withDowntime Whether the rebalance should be done with downtime or minAvailableReplicas=0.
      * @return The result of the rebalance operation.
      */

Review Comment:
   The @JsonCreator annotation should include a comment explaining why this constructor needs explicit JSON mapping, especially since it's part of a serialization chain for ZooKeeper persistence.
   ```suggestion
        */
       /**
        * The @JsonCreator annotation is required to explicitly define how this constructor maps JSON properties
        * to the class fields. This is necessary because this class is part of a serialization chain for
        * ZooKeeper persistence, and explicit mapping ensures correct deserialization of JSON objects.
        */
   ```



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/DefaultTenantRebalancer.java:
##########
@@ -142,20 +129,92 @@ public TenantRebalanceResult rebalance(TenantRebalanceConfig config) {
     return new TenantRebalanceResult(tenantRebalanceJobId, rebalanceResults, config.isVerboseResult());
   }
 
-  private void doConsumeTablesFromQueue(Queue<TenantTableRebalanceJobContext> queue, RebalanceConfig config,
-      TenantRebalanceObserver observer) {
+  /**
+   * Spins up threads to rebalance the tenant with the given context and observer.
+   * The rebalance operation is performed in parallel for the tables in the parallel queue, then, sequentially for the
+   * tables in the sequential queue.
+   * The observer should be initiated with the tenantRebalanceContext in order to track the progress properly.
+   *
+   * @param tenantRebalanceContext The context containing the configuration and queues for the rebalance operation.
+   * @param observer The observer to notify about the rebalance progress and results.
+   */
+  public void rebalanceWithContext(DefaultTenantRebalanceContext tenantRebalanceContext,
+      ZkBasedTenantRebalanceObserver observer) {
+    TenantRebalanceConfig config = tenantRebalanceContext.getConfig();
+    ConcurrentLinkedDeque<TenantTableRebalanceJobContext> parallelQueue = tenantRebalanceContext.getParallelQueue();
+    Queue<TenantTableRebalanceJobContext> sequentialQueue = tenantRebalanceContext.getSequentialQueue();
+    ConcurrentLinkedQueue<TenantTableRebalanceJobContext> ongoingJobs = tenantRebalanceContext.getOngoingJobsQueue();
+
+    observer.onTrigger(TenantRebalanceObserver.Trigger.START_TRIGGER, null, null);
+
+    // ensure atleast 1 thread is created to run the sequential table rebalance operations
+    int parallelism = Math.max(config.getDegreeOfParallelism(), 1);
+    AtomicInteger activeThreads = new AtomicInteger(parallelism);
+    try {
+      for (int i = 0; i < parallelism; i++) {
+        _executorService.submit(() -> {
+          doConsumeTablesFromQueueAndRebalance(parallelQueue, ongoingJobs, config, observer);
+          if (activeThreads.decrementAndGet() == 0) {
+            doConsumeTablesFromQueueAndRebalance(sequentialQueue, ongoingJobs, config, observer);
+            observer.onSuccess(String.format("Successfully rebalanced tenant %s.", config.getTenantName()));
+          }
+        });
+      }
+    } catch (Exception exception) {
+      observer.onError(String.format("Failed to rebalance the tenant %s. Cause: %s", config.getTenantName(),
+          exception.getMessage()));
+    }
+  }
+
+  /**
+   * Consumes tables from the given queue from the DefaultTenantRebalanceContext that is being monitored by the
+   * observer and rebalances them using the provided config.
+   * The ongoing jobs are tracked in the ongoingJobs queue, which is also from the monitored
+   * DefaultTenantRebalanceContext.
+   *
+   * @param queue The queue of TenantTableRebalanceJobContext to consume tables from.
+   * @param ongoingJobs The queue to track ongoing rebalance jobs.
+   * @param config The rebalance configuration to use for the rebalancing.
+   * @param observer The observer to notify about the rebalance progress and results, should be initiated with the
+   *                 DefaultTenantRebalanceContext that contains `queue` and `ongoingJobs`.
+   */
+  private void doConsumeTablesFromQueueAndRebalance(Queue<TenantTableRebalanceJobContext> queue,
+      Queue<TenantTableRebalanceJobContext> ongoingJobs, RebalanceConfig config,
+      ZkBasedTenantRebalanceObserver observer) {
     while (true) {
       TenantTableRebalanceJobContext jobContext = queue.poll();
       if (jobContext == null) {
         break;
       }
-      String table = jobContext.getTableName();
+      ongoingJobs.add(jobContext);
+      String tableName = jobContext.getTableName();
+      String rebalanceJobId = jobContext.getJobId();
       RebalanceConfig rebalanceConfig = RebalanceConfig.copy(config);
       rebalanceConfig.setDryRun(false);
       if (jobContext.shouldRebalanceWithDowntime()) {
         rebalanceConfig.setMinAvailableReplicas(0);
       }
-      rebalanceTable(table, rebalanceConfig, jobContext.getJobId(), observer);
+      try {
+        observer.onTrigger(TenantRebalanceObserver.Trigger.REBALANCE_STARTED_TRIGGER, tableName, rebalanceJobId);
+        // Disallow TABLE rebalance checker to retry the rebalance job here, since we want TENANT rebalance checker
+        // to do so

Review Comment:
   The comment mentions coordination between TABLE and TENANT rebalance checkers but doesn't explain the specific behavior or potential race conditions. This coordination logic should be better documented.
   ```suggestion
           // Disallow TABLE rebalance checker to retry the rebalance job here. This is because the TENANT rebalance
           // checker is responsible for managing the overall rebalancing process across multiple tables within a tenant.
           // Allowing the TABLE rebalance checker to retry could lead to conflicts or redundant operations, as it does
           // not have visibility into the broader tenant-level context. By centralizing retry logic in the TENANT
           // rebalance checker, we ensure that retries are coordinated and aligned with the tenant's rebalancing strategy.
           // This approach also helps prevent potential race conditions where both checkers might attempt to retry the
           // same job simultaneously, leading to inconsistent states or errors.
   ```



##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,513 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;

Review Comment:
   This import appears to be unused since the code uses ConcurrentLinkedDeque in the actual implementation. Consider removing unused imports.
   ```suggestion
   
   ```



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,221 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context.
+ * <p>
+ * Notice that this is not a retry but a resume, since we will not re-do the table rebalance for those tables that have
+ * already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        if (isTenantRebalanceJobStuck(tenantRebalanceContext, statsUpdatedAt)) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = tenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            tenantRebalanceContext.getParallelQueue().addFirst(ctx);
+          }
+          // If the job is stuck, we retry it
+          resumeTenantRebalanceJob(tenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void resumeTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContext,
+      TenantRebalanceProgressStats progressStats) {
+    DefaultTenantRebalanceContext tenantRebalanceContextForRetry =
+        DefaultTenantRebalanceContext.forRetry(tenantRebalanceContext.getOriginalJobId(),
+            tenantRebalanceContext.getConfig(), tenantRebalanceContext.getAttemptId() + 1,
+            tenantRebalanceContext.getParallelQueue(),
+            tenantRebalanceContext.getSequentialQueue(), tenantRebalanceContext.getOngoingJobsQueue());
+
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContext.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);
+  }
+
+  private boolean isTenantRebalanceJobStuck(
+      DefaultTenantRebalanceContext tenantRebalanceContext, long statsUpdatedAt) {
+    if (tenantRebalanceContext.getOngoingJobsQueue().isEmpty()) {
+      if (tenantRebalanceContext.getParallelQueue().isEmpty() && tenantRebalanceContext.getSequentialQueue()
+          .isEmpty()) {
+        return false;
+      }
+      // If there are no ongoing jobs but in parallel or sequential queue, it could be because the tenant rebalancer
+      // is in the interval of the previous done job and consumption of the next job. We need to check the heartbeat
+      // timeout to be sure that it's actually stuck at this state for a long while.
+      long heartbeatTimeoutMs = tenantRebalanceContext.getConfig().getHeartbeatTimeoutInMs();
+      return (System.currentTimeMillis() - statsUpdatedAt >= heartbeatTimeoutMs);
+    }
+
+    // Check if there's any stuck ongoing table rebalance jobs
+    for (TenantRebalancer.TenantTableRebalanceJobContext ctx : new ArrayList<>(
+        tenantRebalanceContext.getOngoingJobsQueue())) {
+      if (isTableRebalanceJobStuck(ctx.getJobId())) {
+        // If any of the table rebalance jobs is stuck, we consider the tenant rebalance job as stuck.
+        LOGGER.info("Found stuck table rebalance job: {} for tenant: {}", ctx.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName());
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private boolean isTableRebalanceJobStuck(String jobId) {
+    Map<String, String> jobMetadata =
+        _pinotHelixResourceManager.getControllerJobZKMetadata(jobId, ControllerJobTypes.TABLE_REBALANCE);
+    if (jobMetadata == null) {
+      return false;
+    }
+    long statsUpdatedAt = Long.parseLong(jobMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+    String jobStatsInStr = jobMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+    if (StringUtils.isEmpty(jobStatsInStr)) {
+      // Skip rebalance job as it has no job progress stats
+      return false;
+    }
+    String jobCtxInStr = jobMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+    if (StringUtils.isEmpty(jobCtxInStr)) {
+      // Skip rebalance job: {} as it has no job context
+      return false;
+    }
+
+    try {
+      TableRebalanceProgressStats jobStats = JsonUtils.stringToObject(jobStatsInStr, TableRebalanceProgressStats.class);
+      TableRebalanceContext jobCtx = JsonUtils.stringToObject(jobCtxInStr, TableRebalanceContext.class);
+      if (jobStats.getStatus() == RebalanceResult.Status.IN_PROGRESS) {
+        long heartbeatTimeoutMs = jobCtx.getConfig().getHeartbeatTimeoutInMs();
+        if (System.currentTimeMillis() - statsUpdatedAt >= heartbeatTimeoutMs) {
+          LOGGER.info("Found stuck rebalance job: {} that has not updated its status in ZK within "
+              + "heartbeat timeout: {}", jobId, heartbeatTimeoutMs);
+          return true;
+        }
+      }
+    } catch (JsonProcessingException e) {
+      throw new ControllerApplicationException(LOGGER, "Failed to parse table rebalance context for job: " + jobId,
+          Response.Status.INTERNAL_SERVER_ERROR, e);
+    }
+    return false;
+  }
+
+  private void abortTableRebalanceJob(String tableNameWithType) {
+    // TODO: This is a duplicate of a private method in RebalanceChecker, we should refactor it to a common place.

Review Comment:
   The TODO comment indicates code duplication that should be addressed. Consider extracting the abortTableRebalanceJob method to a shared utility class to reduce duplication and improve maintainability.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on PR #16455:
URL: https://github.com/apache/pinot/pull/16455#issuecomment-3215372011

   @yashmayya Thanks for going through these code. 
   > This sounds like a good solution to me, did you have any concerns or misgivings about this approach? Or was https://github.com/apache/pinot/pull/16455#issuecomment-3141200274 made before you implemented the ZK metadata based solution here?
   
   Yes that was before I implemented the ZK method. I don't have concerns here.
   
   I added a change in `isTableRebalanceJobStuck` to cover one corner case mentioned in [this comment](https://github.com/apache/pinot/pull/16455#discussion_r2294440247), please see if it makes sense.
   As for the removal of the abstract classes, let's see if @shounakmk219 has any concerns, otherwise I can remove it.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "yashmayya (via GitHub)" <gi...@apache.org>.
yashmayya commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2310159286


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -57,6 +57,8 @@ public class TenantRebalanceChecker extends BasePeriodicTask {
   private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
   private final TenantRebalancer _tenantRebalancer;
   private final PinotHelixResourceManager _pinotHelixResourceManager;
+  // To avoid multiple retries of the same tenant rebalance job, we only allow one ongoing retry job at a time.

Review Comment:
   Why would there be multiple retries of the same tenant rebalance job?



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "yashmayya (via GitHub)" <gi...@apache.org>.
yashmayya merged PR #16455:
URL: https://github.com/apache/pinot/pull/16455


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on PR #16455:
URL: https://github.com/apache/pinot/pull/16455#issuecomment-3193127162

   @yashmayya Right now I'll have every controller run the check on each tenant rebalance job, but only one controller can get to retry that job if stuck. This is done by compare and swap using `ControllerZkHelixUtils::addControllerJobToZK`. 
   
   For example if two controllers both detect `jobID_123` is stuck and want to retry it, only the one who creates the job ZK metadata for `jobID_123_2`(the job ID with the new attempt ID) will actually retry the job.
   https://github.com/apache/pinot/blob/d01cb710100b8601574bd92d73c1c16092ece01e/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java#L191-L193


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2294309311


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);

Review Comment:
   Because when resume a tenant rebalance job, the ongoing jobs of the previous stuck tenant rebalance job will need to be processed first after resuming (to follow the original queue order, also to process them first because they were aborted and now they're in a partial-balanced state). 
   
   If these aborted ongoing jobs are added to the sequential queue, there might still be some jobs in parallel queue, the rebalancer won't pick these aborted jobs first.
   
   It's also fine to assume they're all parallel-allowed tables because otherwise they will not be in the ongoing queue at the same time. On the other hand, if there's only one table in the ongoing job queue and it is a parallel-disallowed table, it's fine to add it to parallel queue since it should be the only one job there.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2302229676


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,221 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context.
+ * <p>
+ * Notice that this is not a retry but a resume, since we will not re-do the table rebalance for those tables that have
+ * already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        if (isTenantRebalanceJobStuck(tenantRebalanceContext, statsUpdatedAt)) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = tenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            tenantRebalanceContext.getParallelQueue().addFirst(ctx);
+          }
+          // If the job is stuck, we retry it
+          resumeTenantRebalanceJob(tenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void resumeTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContext,
+      TenantRebalanceProgressStats progressStats) {
+    DefaultTenantRebalanceContext tenantRebalanceContextForRetry =
+        DefaultTenantRebalanceContext.forRetry(tenantRebalanceContext.getOriginalJobId(),
+            tenantRebalanceContext.getConfig(), tenantRebalanceContext.getAttemptId() + 1,
+            tenantRebalanceContext.getParallelQueue(),
+            tenantRebalanceContext.getSequentialQueue(), tenantRebalanceContext.getOngoingJobsQueue());
+
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContext.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);

Review Comment:
   Consolidated `DefaultTenantRebalancer` to `TenantRebalancer`, `DefaultTenantRebalanceContext` to `TenantRebalanceContext`



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "yashmayya (via GitHub)" <gi...@apache.org>.
yashmayya commented on PR #16455:
URL: https://github.com/apache/pinot/pull/16455#issuecomment-3237033860

   > One thing I'm concerning is the load of this periodic task. I added a rate limit set on each controller, for now only one tenant rebalance job allowed to retry at a time.
   For manual triggered tenant rebalance users are responsible to not schedule multiple tenant rebalances at the same time, but for this periodic task I think some protection is needed here to avoid unexpected huge load when multiple tenant rebalance jobs need retries.
   >
   > Wdyt? Also some loggers are added for observability.
   
   Logs are (almost) always good, thanks for adding them. Are you worried about the load on a particular controller or the load on the servers / cluster overall (due to rebalances)? I wouldn't overthink this part too much tbh, if there are multiple failed tenant rebalances being retried at the same time, it's likely that they were issued within the same time period by the user so it's okay for us to retry them together. Also, just to clarify, we shouldn't be retrying the same tenant rebalance job anyway right (across controllers as well as on the same controller)?


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2294440897


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);
+          }
+          // the retry tenant rebalance job id has been created in ZK, we can safely mark the original job as
+          // aborted, so that this original job will not be picked up again in the future.
+          markTenantRebalanceJobAsAborted(jobId, jobZKMetadata, tenantRebalanceContext, progressStats);
+          retryTenantRebalanceJob(retryTenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void retryTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContextForRetry,
+      TenantRebalanceProgressStats progressStats) {
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContextForRetry.getJobId(),
+            tenantRebalanceContextForRetry.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);
+  }
+
+  /**
+   * Check if the tenant rebalance job is stuck, and prepare to retry it if necessary.
+   * A tenant rebalance job is considered stuck if:
+   * 1. There are no ongoing jobs, but there are jobs in the parallel or sequential queue, and the stats have not been
+   *    updated for longer than the heartbeat timeout.
+   * 2. There are ongoing table rebalance jobs, and at least one of them has not updated its status for longer than the
+   *    heartbeat timeout.
+   * The retry is prepared by creating a new tenant rebalance job with an incremented attempt ID, and persisting it to
+   * ZK.
+   *
+   * @param jobZKMetadata The ZK metadata of the tenant rebalance job.
+   * @param tenantRebalanceContext The context of the tenant rebalance job.
+   * @param statsUpdatedAt The timestamp when the stats were last updated.
+   * @return The TenantRebalanceContext for retry if the tenant rebalance job is stuck and should be retried, null if
+   * other controller has prepared the retry first.

Review Comment:
   good catch, thanks



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "shounakmk219 (via GitHub)" <gi...@apache.org>.
shounakmk219 commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2301405889


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,221 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context.
+ * <p>
+ * Notice that this is not a retry but a resume, since we will not re-do the table rebalance for those tables that have
+ * already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        if (isTenantRebalanceJobStuck(tenantRebalanceContext, statsUpdatedAt)) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = tenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            tenantRebalanceContext.getParallelQueue().addFirst(ctx);
+          }
+          // If the job is stuck, we retry it
+          resumeTenantRebalanceJob(tenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void resumeTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContext,
+      TenantRebalanceProgressStats progressStats) {
+    DefaultTenantRebalanceContext tenantRebalanceContextForRetry =
+        DefaultTenantRebalanceContext.forRetry(tenantRebalanceContext.getOriginalJobId(),
+            tenantRebalanceContext.getConfig(), tenantRebalanceContext.getAttemptId() + 1,
+            tenantRebalanceContext.getParallelQueue(),
+            tenantRebalanceContext.getSequentialQueue(), tenantRebalanceContext.getOngoingJobsQueue());
+
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContext.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);

Review Comment:
   The earlier idea was to have different implementations/strategy to rebalance a tenant but now that we have consolidated all the possible cases under the `DefaultTenantRebalancer` we can consolidate. I don't see any concern



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2307932910


##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;

Review Comment:
   Indeed :(



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "yashmayya (via GitHub)" <gi...@apache.org>.
yashmayya commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2300987905


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);
+          }
+          // the retry tenant rebalance job id has been created in ZK, we can safely mark the original job as
+          // aborted, so that this original job will not be picked up again in the future.

Review Comment:
   Thanks for the thorough analysis and the bugfix, the sandbox simulation looks good to me :)



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "yashmayya (via GitHub)" <gi...@apache.org>.
yashmayya commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2301001828


##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;

Review Comment:
   Unused mocks?



##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;
+  @Mock
+  private ControllerConf _mockControllerConf;
+
+  private TenantRebalanceChecker _tenantRebalanceChecker;
+  private ExecutorService _executorService;
+
+  @BeforeMethod
+  public void setUp() {
+    MockitoAnnotations.openMocks(this);
+    _executorService = Executors.newFixedThreadPool(2);
+
+    // Setup default mock behaviors
+    when(_mockControllerConf.getTenantRebalanceCheckerFrequencyInSeconds()).thenReturn(300);
+    when(_mockControllerConf.getTenantRebalanceCheckerInitialDelayInSeconds()).thenReturn(300L);
+    // mock ZK update success
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE));
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    _tenantRebalanceChecker = new TenantRebalanceChecker(
+        _mockControllerConf,
+        _mockPinotHelixResourceManager,
+        _mockTenantRebalancer
+    );
+  }
+
+  @AfterMethod
+  public void tearDown() {
+    if (_executorService != null) {
+      _executorService.shutdown();
+    }
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called to resume the job
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+
+    // Verify the resumed context
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertNotNull(resumedContext);
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getOriginalJobId(), ORIGINAL_JOB_ID);
+    assertEquals(resumedContext.getAttemptId(), 2); // Should be incremented from 1
+    assertEquals(resumedContext.getConfig().getTenantName(), TENANT_NAME);
+
+    // Verify that the stuck table job context was moved back to parallel queue
+    TenantRebalancer.TenantTableRebalanceJobContext firstJobContextInParallelQueue =
+        resumedContext.getParallelQueue().poll();
+    assertNotNull(firstJobContextInParallelQueue);
+    // because the stuck job is aborted, a new job ID is generated
+    assertNotEquals(firstJobContextInParallelQueue.getJobId(), STUCK_TABLE_JOB_ID);
+    assertEquals(firstJobContextInParallelQueue.getTableName(), TABLE_NAME_1);
+    assertFalse(firstJobContextInParallelQueue.shouldRebalanceWithDowntime());
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+
+    // Verify the observer was created with correct parameters
+    ZkBasedTenantRebalanceObserver observer = observerCaptor.getValue();
+    assertNotNull(observer);
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJobWithMultipleStuckTables()
+      throws Exception {
+    // Create a context with multiple stuck table jobs
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContextWithMultipleTables();
+    TenantRebalanceProgressStats progressStats = createProgressStatsWithMultipleTables();
+
+    // Mock ZK metadata
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table job metadata for both tables
+    Map<String, String> stuckTableJobMetadata1 = createStuckTableJobMetadata();
+    Map<String, String> stuckTableJobMetadata2 = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata1).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(stuckTableJobMetadata2).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID_2), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), any(ZkBasedTenantRebalanceObserver.class));
+
+    // Verify that both stuck table jobs were moved back to parallel queue
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getParallelQueue().size(), 2);
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithoutOngoing = createNonStuckTenantRebalanceContextWithoutOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithoutOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithoutOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithoutOngoing);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJobWithOngoing()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithOngoing = createNonStuckTenantRebalanceContextWithOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithOngoing);
+
+    // Mock non-stuck table rebalance job metadata
+    Map<String, String> nonStuckTableJobMetadata = createNonStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(nonStuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(NON_STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeTenantRebalanceJobWhileZKUpdateFailed()
+      throws Exception {
+
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(false).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called because ZK update failed
+    verify(_mockTenantRebalancer, times(0)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+  }
+
+  @Test
+  public void testHandleCorruptedZKMetadata()
+      throws Exception {
+    // Create corrupted ZK metadata (missing required fields)
+    Map<String, String> corruptedJobZKMetadata = new HashMap<>();
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_ID, JOB_ID);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.TENANT_NAME, TENANT_NAME);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS,
+        String.valueOf(System.currentTimeMillis()));
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_TYPE, ControllerJobTypes.TENANT_REBALANCE.name());
+    // Provide invalid JSON to trigger JsonProcessingException
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT, "invalid json");
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS, "invalid json");
+
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, corruptedJobZKMetadata);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker - should not throw exception
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testHandleJsonProcessingException()

Review Comment:
   How are these two tests different?



##########
pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceCheckerTest.java:
##########
@@ -0,0 +1,552 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.helix.ControllerTest;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceConfig;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.*;
+
+
+public class TenantRebalanceCheckerTest extends ControllerTest {
+  private static final String TENANT_NAME = "TestTenant";
+  private static final String JOB_ID = "test-tenant-rebalance-job-123";
+  private static final String ORIGINAL_JOB_ID = "original-tenant-rebalance-job-123";
+  private static final String TABLE_NAME_1 = "testTable1_OFFLINE";
+  private static final String TABLE_NAME_2 = "testTable2_OFFLINE";
+  private static final String NON_STUCK_TABLE_JOB_ID = "non-stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID = "stuck-table-job-456";
+  private static final String STUCK_TABLE_JOB_ID_2 = "stuck-table-job-789";
+
+  @Mock
+  private PinotHelixResourceManager _mockPinotHelixResourceManager;
+  @Mock
+  private DefaultTenantRebalancer _mockTenantRebalancer;
+  @Mock
+  private ControllerMetrics _mockControllerMetrics;
+  @Mock
+  private PoolingHttpClientConnectionManager _mockConnectionManager;
+  @Mock
+  private ControllerConf _mockControllerConf;
+
+  private TenantRebalanceChecker _tenantRebalanceChecker;
+  private ExecutorService _executorService;
+
+  @BeforeMethod
+  public void setUp() {
+    MockitoAnnotations.openMocks(this);
+    _executorService = Executors.newFixedThreadPool(2);
+
+    // Setup default mock behaviors
+    when(_mockControllerConf.getTenantRebalanceCheckerFrequencyInSeconds()).thenReturn(300);
+    when(_mockControllerConf.getTenantRebalanceCheckerInitialDelayInSeconds()).thenReturn(300L);
+    // mock ZK update success
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE));
+    doReturn(true).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    _tenantRebalanceChecker = new TenantRebalanceChecker(
+        _mockControllerConf,
+        _mockPinotHelixResourceManager,
+        _mockTenantRebalancer
+    );
+  }
+
+  @AfterMethod
+  public void tearDown() {
+    if (_executorService != null) {
+      _executorService.shutdown();
+    }
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called to resume the job
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+
+    // Verify the resumed context
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertNotNull(resumedContext);
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getOriginalJobId(), ORIGINAL_JOB_ID);
+    assertEquals(resumedContext.getAttemptId(), 2); // Should be incremented from 1
+    assertEquals(resumedContext.getConfig().getTenantName(), TENANT_NAME);
+
+    // Verify that the stuck table job context was moved back to parallel queue
+    TenantRebalancer.TenantTableRebalanceJobContext firstJobContextInParallelQueue =
+        resumedContext.getParallelQueue().poll();
+    assertNotNull(firstJobContextInParallelQueue);
+    // because the stuck job is aborted, a new job ID is generated
+    assertNotEquals(firstJobContextInParallelQueue.getJobId(), STUCK_TABLE_JOB_ID);
+    assertEquals(firstJobContextInParallelQueue.getTableName(), TABLE_NAME_1);
+    assertFalse(firstJobContextInParallelQueue.shouldRebalanceWithDowntime());
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+
+    // Verify the observer was created with correct parameters
+    ZkBasedTenantRebalanceObserver observer = observerCaptor.getValue();
+    assertNotNull(observer);
+  }
+
+  @Test
+  public void testResumeStuckTenantRebalanceJobWithMultipleStuckTables()
+      throws Exception {
+    // Create a context with multiple stuck table jobs
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContextWithMultipleTables();
+    TenantRebalanceProgressStats progressStats = createProgressStatsWithMultipleTables();
+
+    // Mock ZK metadata
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table job metadata for both tables
+    Map<String, String> stuckTableJobMetadata1 = createStuckTableJobMetadata();
+    Map<String, String> stuckTableJobMetadata2 = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata1).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(stuckTableJobMetadata2).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID_2), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was called
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    verify(_mockTenantRebalancer, times(1)).rebalanceWithContext(
+        contextCaptor.capture(), any(ZkBasedTenantRebalanceObserver.class));
+
+    // Verify that both stuck table jobs were moved back to parallel queue
+    DefaultTenantRebalanceContext resumedContext = contextCaptor.getValue();
+    assertEquals(resumedContext.getAttemptId(), DefaultTenantRebalanceContext.INITIAL_ATTEMPT_ID + 1);
+    assertEquals(resumedContext.getParallelQueue().size(), 2);
+    assertTrue(resumedContext.getOngoingJobsQueue().isEmpty());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJob()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithoutOngoing = createNonStuckTenantRebalanceContextWithoutOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithoutOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithoutOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithoutOngoing);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeNonStuckTenantRebalanceJobWithOngoing()
+      throws Exception {
+    // Create a non-stuck tenant rebalance context (no ongoing jobs)
+    DefaultTenantRebalanceContext nonStuckContextWithOngoing = createNonStuckTenantRebalanceContextWithOngoing();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata
+    Map<String, String> tenantJobZKMetadataWithOngoing =
+        createTenantJobZKMetadataWithRecentTimestamp(nonStuckContextWithOngoing, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, tenantJobZKMetadataWithOngoing);
+
+    // Mock non-stuck table rebalance job metadata
+    Map<String, String> nonStuckTableJobMetadata = createNonStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(nonStuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(NON_STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testDoNotResumeTenantRebalanceJobWhileZKUpdateFailed()
+      throws Exception {
+
+    // Create a stuck tenant rebalance context
+    DefaultTenantRebalanceContext stuckContext = createStuckTenantRebalanceContext();
+    TenantRebalanceProgressStats progressStats = createProgressStats();
+
+    // Mock ZK metadata for the stuck job
+    Map<String, String> jobZKMetadata = createTenantJobZKMetadata(stuckContext, progressStats);
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, jobZKMetadata);
+
+    // Mock stuck table rebalance job metadata
+    Map<String, String> stuckTableJobMetadata = createStuckTableJobMetadata();
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+    doReturn(stuckTableJobMetadata).when(_mockPinotHelixResourceManager)
+        .getControllerJobZKMetadata(eq(STUCK_TABLE_JOB_ID), eq(ControllerJobTypes.TABLE_REBALANCE));
+    doReturn(false).when(_mockPinotHelixResourceManager)
+        .addControllerJobToZK(anyString(), anyMap(), eq(ControllerJobTypes.TENANT_REBALANCE), any());
+
+    // Mock the tenant rebalancer to capture the resumed context
+    ArgumentCaptor<DefaultTenantRebalanceContext> contextCaptor =
+        ArgumentCaptor.forClass(DefaultTenantRebalanceContext.class);
+    ArgumentCaptor<ZkBasedTenantRebalanceObserver> observerCaptor =
+        ArgumentCaptor.forClass(ZkBasedTenantRebalanceObserver.class);
+
+    // Execute the checker
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called because ZK update failed
+    verify(_mockTenantRebalancer, times(0)).rebalanceWithContext(
+        contextCaptor.capture(), observerCaptor.capture());
+  }
+
+  @Test
+  public void testHandleCorruptedZKMetadata()
+      throws Exception {
+    // Create corrupted ZK metadata (missing required fields)
+    Map<String, String> corruptedJobZKMetadata = new HashMap<>();
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_ID, JOB_ID);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.TENANT_NAME, TENANT_NAME);
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS,
+        String.valueOf(System.currentTimeMillis()));
+    corruptedJobZKMetadata.put(CommonConstants.ControllerJob.JOB_TYPE, ControllerJobTypes.TENANT_REBALANCE.name());
+    // Provide invalid JSON to trigger JsonProcessingException
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT, "invalid json");
+    corruptedJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS, "invalid json");
+
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, corruptedJobZKMetadata);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker - should not throw exception
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  @Test
+  public void testHandleJsonProcessingException()
+      throws Exception {
+    // Create ZK metadata with invalid JSON
+    Map<String, String> invalidJsonJobZKMetadata = new HashMap<>();
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.JOB_ID, JOB_ID);
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.TENANT_NAME, TENANT_NAME);
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS,
+        String.valueOf(System.currentTimeMillis()));
+    invalidJsonJobZKMetadata.put(CommonConstants.ControllerJob.JOB_TYPE, ControllerJobTypes.TENANT_REBALANCE.name());
+    invalidJsonJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT, "invalid json");
+    invalidJsonJobZKMetadata.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS, "invalid json");
+
+    Map<String, Map<String, String>> allJobMetadata = new HashMap<>();
+    allJobMetadata.put(JOB_ID, invalidJsonJobZKMetadata);
+
+    // Setup mocks
+    doReturn(allJobMetadata).when(_mockPinotHelixResourceManager)
+        .getAllJobs(eq(Set.of(ControllerJobTypes.TENANT_REBALANCE)), any());
+
+    // Execute the checker - should not throw exception
+    _tenantRebalanceChecker.runTask(new Properties());
+
+    // Verify that the tenant rebalancer was NOT called
+    verify(_mockTenantRebalancer, never()).rebalanceWithContext(any(), any());
+  }
+
+  // Helper methods to create test data
+
+  private DefaultTenantRebalanceContext createStuckTenantRebalanceContext() {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L); // 5 minutes
+
+    ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue =
+        new ConcurrentLinkedDeque<>();
+    ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> ongoingJobsQueue =
+        new ConcurrentLinkedQueue<>();
+
+    // Add a stuck table job to ongoing queue
+    TenantRebalancer.TenantTableRebalanceJobContext stuckJobContext =
+        new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, STUCK_TABLE_JOB_ID, false);
+    ongoingJobsQueue.add(stuckJobContext);
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, parallelQueue,
+        new ConcurrentLinkedQueue<>(), ongoingJobsQueue);
+  }
+
+  private DefaultTenantRebalanceContext createStuckTenantRebalanceContextWithMultipleTables()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue =
+        new ConcurrentLinkedDeque<>();
+    ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> ongoingJobsQueue =
+        new ConcurrentLinkedQueue<>();
+
+    // Add multiple stuck table jobs to ongoing queue
+    ongoingJobsQueue.add(new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, STUCK_TABLE_JOB_ID, false));
+    ongoingJobsQueue.add(
+        new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_2, STUCK_TABLE_JOB_ID_2, false));
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, parallelQueue,
+        new ConcurrentLinkedQueue<>(), ongoingJobsQueue);
+  }
+
+  private DefaultTenantRebalanceContext createNonStuckTenantRebalanceContextWithoutOngoing()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    ConcurrentLinkedDeque<TenantRebalancer.TenantTableRebalanceJobContext> parallelQueue =
+        new ConcurrentLinkedDeque<>();
+    // Add some jobs to parallel queue but none to ongoing queue
+    parallelQueue.add(new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, NON_STUCK_TABLE_JOB_ID, false));
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, parallelQueue,
+        new ConcurrentLinkedQueue<>(), new ConcurrentLinkedQueue<>());
+  }
+
+  private DefaultTenantRebalanceContext createNonStuckTenantRebalanceContextWithOngoing()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    ConcurrentLinkedQueue<TenantRebalancer.TenantTableRebalanceJobContext> ongoing =
+        new ConcurrentLinkedQueue<>();
+    // Add some jobs to parallel queue but none to ongoing queue
+    ongoing.add(new TenantRebalancer.TenantTableRebalanceJobContext(TABLE_NAME_1, NON_STUCK_TABLE_JOB_ID, false));
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1, new ConcurrentLinkedDeque<>(),
+        new ConcurrentLinkedQueue<>(), ongoing);
+  }
+
+  private DefaultTenantRebalanceContext createRecentTenantRebalanceContext()
+      throws JsonProcessingException {
+    TenantRebalanceConfig config = new TenantRebalanceConfig();
+    config.setTenantName(TENANT_NAME);
+    config.setHeartbeatTimeoutInMs(300000L);
+
+    return new DefaultTenantRebalanceContext(
+        ORIGINAL_JOB_ID, config, 1,
+        new ConcurrentLinkedDeque<>(), new ConcurrentLinkedQueue<>(), new ConcurrentLinkedQueue<>());
+  }
+
+  private DefaultTenantRebalanceContext createOldTenantRebalanceContext()

Review Comment:
   Unused helper methods?



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on PR #16455:
URL: https://github.com/apache/pinot/pull/16455#issuecomment-3237617108

   @yashmayya 
   > Also, just to clarify, we shouldn't be retrying the same tenant rebalance job anyway right (across controllers as well as on the same controller)?
   
   Right, the mechanics using ZK metadata update prevent this. I wrote that one comment in a wrong way.
   
   IMO to schedule them one by one is safer, plus that if multiple tenant rebalance jobs are to retry, the one retry per controller protection can distribute retries job to different controllers (though some will have to wait if the number of jobs > number of controllers), compared to without the one job limit, one controller could take up every tenant rebalance jobs to retry because we have no leadership in tenant level like tables.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2310593968


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -57,6 +57,8 @@ public class TenantRebalanceChecker extends BasePeriodicTask {
   private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
   private final TenantRebalancer _tenantRebalancer;
   private final PinotHelixResourceManager _pinotHelixResourceManager;
+  // To avoid multiple retries of the same tenant rebalance job, we only allow one ongoing retry job at a time.

Review Comment:
   Made a mistake. I meant to say "avoid multiple tenant rebalance job retries on the same controller"



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2294440247


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,307 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context, with an attempt job ID
+ * <p>
+ * Notice that fundamentally this is not a retry but a resume, since we will not re-do the table rebalance for those
+ * tables that have already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        DefaultTenantRebalanceContext retryTenantRebalanceContext =
+            prepareRetryIfTenantRebalanceJobStuck(jobZKMetadata, tenantRebalanceContext, statsUpdatedAt);
+        if (retryTenantRebalanceContext != null) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = retryTenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            // the existing table rebalance job is aborted, we need to run the rebalance job with a new job ID.
+            TenantRebalancer.TenantTableRebalanceJobContext newCtx =
+                new TenantRebalancer.TenantTableRebalanceJobContext(
+                    ctx.getTableName(), UUID.randomUUID().toString(), ctx.shouldRebalanceWithDowntime());
+            retryTenantRebalanceContext.getParallelQueue().addFirst(newCtx);
+          }
+          // the retry tenant rebalance job id has been created in ZK, we can safely mark the original job as
+          // aborted, so that this original job will not be picked up again in the future.

Review Comment:
   For job `jobId_123`, if it's stuck, the checker(controller) will:
   1. Creates a new retry job metadata `jobId_123_2` in ZK
   2. Abort all ongoing "_table_" rebalance jobs in `jobId_123`
   3. Clear all queues in `jobId_123`'s context, which is what I meant aborting the original tenant rebalance job
   4. Start retry `jobId_123_2`
   
   If the controller crashes happens:
   * Before 1:  the next round of the checker check will pick up `jobId_123` and retry it again.
   * Between 1 & 2: the next round of the checker check will pick up `jobId_123_2` and `jobId_123` as they're both considered stuck, but `jobId_123` will not be retried because `jobId_123_2` already exists on ZK. `jobId_123_3` will be created then that retries `jobId_123_2`
   * Between 2 & 3: I found a bug here, if the controller crashes here, the next round of the checker will see `jobId_123_2` as not stuck and will not retry it because all the jobs in ongoing job queue of `jobId_123_2` is `ABORTED` but an `ABORTED` table was not considered as stuck. I've changed the method `isTableRebalanceJobStuck` to cover this scenario, so now it should be considered stcuk, and `jobId_123_3` will spawn to retry.
   * Between 3 & 4: There's no change of metadata of `jobId_123_2` in step 3, so `jobId_123_2` will be considered stuck as the previous scenario. `jobId_123` will not be pick up because its queues are empty
   * After 4: Falls into the same scenario of a typical stuck tenant rebalance job.
   
   Let me know if this makes sense, these are only tested in my monkey brain sandbox



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2294257589


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,221 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context.
+ * <p>
+ * Notice that this is not a retry but a resume, since we will not re-do the table rebalance for those tables that have
+ * already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        if (isTenantRebalanceJobStuck(tenantRebalanceContext, statsUpdatedAt)) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = tenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            tenantRebalanceContext.getParallelQueue().addFirst(ctx);
+          }
+          // If the job is stuck, we retry it
+          resumeTenantRebalanceJob(tenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void resumeTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContext,
+      TenantRebalanceProgressStats progressStats) {
+    DefaultTenantRebalanceContext tenantRebalanceContextForRetry =
+        DefaultTenantRebalanceContext.forRetry(tenantRebalanceContext.getOriginalJobId(),
+            tenantRebalanceContext.getConfig(), tenantRebalanceContext.getAttemptId() + 1,
+            tenantRebalanceContext.getParallelQueue(),
+            tenantRebalanceContext.getSequentialQueue(), tenantRebalanceContext.getOngoingJobsQueue());
+
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContext.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);

Review Comment:
   @shounakmk219 What's your opinion on this? I think you were the original author of the interface, was there any concern?



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on PR #16455:
URL: https://github.com/apache/pinot/pull/16455#issuecomment-3234324019

   @yashmayya 
   One thing I'm concerning is the load of this periodic task. I added a rate limit set on each controller, for now only one tenant rebalance job allowed at a time.
   For manual triggered tenant rebalance users are responsible to not schedule multiple tenant rebalances at the same time, but for this periodic task I think some protection is needed here to avoid unexpected huge load when multiple tenant rebalance jobs need retries.
   
   Wdyt? Also some loggers are added for observability.
   


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] [WIP] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #16455:
URL: https://github.com/apache/pinot/pull/16455#issuecomment-3137792958

   ## [Codecov](https://app.codecov.io/gh/apache/pinot/pull/16455?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :white_check_mark: All modified and coverable lines are covered by tests.
   :white_check_mark: Project coverage is 56.36%. Comparing base ([`f0e5eed`](https://app.codecov.io/gh/apache/pinot/commit/f0e5eedadcfc3f71dd0fbf2fae172444901b47d2?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`b1a5001`](https://app.codecov.io/gh/apache/pinot/commit/b1a500106f17af8684675d5c9f3745af6d14f4ce?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 2 commits behind head on master.
   > :exclamation:  There is a different number of reports uploaded between BASE (f0e5eed) and HEAD (b1a5001). Click for more details.
   > 
   > <details><summary>HEAD has 28 uploads less than BASE</summary>
   >
   >| Flag | BASE (f0e5eed) | HEAD (b1a5001) |
   >|------|------|------|
   >|unittests|4|2|
   >|java-11|4|1|
   >|temurin|9|2|
   >|unittests2|2|0|
   >|java-21|5|1|
   >|integration|5|0|
   >|integration1|2|0|
   >|custom-integration1|1|0|
   >|integration2|2|0|
   ></details>
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #16455      +/-   ##
   ============================================
   - Coverage     63.22%   56.36%   -6.86%     
   + Complexity     1364      700     -664     
   ============================================
     Files          3005     2350     -655     
     Lines        174066   129492   -44574     
     Branches      26637    20590    -6047     
   ============================================
   - Hits         110050    72986   -37064     
   + Misses        55626    50493    -5133     
   + Partials       8390     6013    -2377     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [custom-integration1](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [integration](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [integration1](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [integration2](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [java-11](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `56.29% <ø> (-6.90%)` | :arrow_down: |
   | [java-21](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `56.33% <ø> (-6.86%)` | :arrow_down: |
   | [temurin](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `56.36% <ø> (-6.86%)` | :arrow_down: |
   | [unittests](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `56.36% <ø> (-6.86%)` | :arrow_down: |
   | [unittests1](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `56.36% <ø> (-0.02%)` | :arrow_down: |
   | [unittests2](https://app.codecov.io/gh/apache/pinot/pull/16455/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/pinot/pull/16455?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] [WIP] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on code in PR #16455:
URL: https://github.com/apache/pinot/pull/16455#discussion_r2246045500


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/tenant/TenantRebalanceChecker.java:
##########
@@ -0,0 +1,221 @@
+/**
+ * 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.controller.helix.core.rebalance.tenant;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.controller.helix.core.controllerjob.ControllerJobTypes;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceJobConstants;
+import org.apache.pinot.controller.helix.core.rebalance.RebalanceResult;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceContext;
+import org.apache.pinot.controller.helix.core.rebalance.TableRebalanceProgressStats;
+import org.apache.pinot.core.periodictask.BasePeriodicTask;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Periodic task to check if tenant rebalance jobs are stuck and retry them. Controller crashes or restarts could
+ * make a tenant rebalance job stuck.
+ * The task checks for each tenant rebalance job's metadata in ZK, look at the TenantTableRebalanceJobContext in
+ * ongoingJobsQueue, which is a list with table rebalance job ids that the controller is currently processing, to see
+ * if any of these table rebalance jobs has not updated their progress stats longer than the configured heartbeat
+ * timeout. If so, the tenant rebalance job is considered stuck, and the task will resume the tenant rebalance job by
+ * aborting all the ongoing table rebalance jobs, move the ongoing TenantTableRebalanceJobContext back to the head of
+ * the parallel queue, and then trigger the tenant rebalance job again with the updated context.
+ * <p>
+ * Notice that this is not a retry but a resume, since we will not re-do the table rebalance for those tables that have
+ * already been processed.
+ */
+public class TenantRebalanceChecker extends BasePeriodicTask {
+  private final static String TASK_NAME = TenantRebalanceChecker.class.getSimpleName();
+  private static final Logger LOGGER = LoggerFactory.getLogger(TenantRebalanceChecker.class);
+  private static final double RETRY_DELAY_SCALE_FACTOR = 2.0;
+  private final TenantRebalancer _tenantRebalancer;
+  private final PinotHelixResourceManager _pinotHelixResourceManager;
+
+  public TenantRebalanceChecker(ControllerConf config,
+      ControllerMetrics controllerMetrics,
+      PinotHelixResourceManager pinotHelixResourceManager, TenantRebalancer tenantRebalancer) {
+    super(TASK_NAME, config.getTenantRebalanceCheckerFrequencyInSeconds(),
+        config.getTenantRebalanceCheckerInitialDelayInSeconds());
+    _pinotHelixResourceManager = pinotHelixResourceManager;
+    _tenantRebalancer = tenantRebalancer;
+  }
+
+  @Override
+  protected void runTask(Properties periodicTaskProperties) {
+    checkAndRetryTenantRebalance();
+  }
+
+  private void checkAndRetryTenantRebalance() {
+    Map<String, Map<String, String>> allJobMetadataByJobId =
+        _pinotHelixResourceManager.getAllJobs(Set.of(ControllerJobTypes.TENANT_REBALANCE), x -> true);
+    for (Map.Entry<String, Map<String, String>> entry : allJobMetadataByJobId.entrySet()) {
+      String jobId = entry.getKey();
+      Map<String, String> jobZKMetadata = entry.getValue();
+
+      try {
+        // Check if the tenant rebalance job is stuck
+        String tenantRebalanceContextStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);
+        String tenantRebalanceProgressStatsStr =
+            jobZKMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);
+        if (StringUtils.isEmpty(tenantRebalanceContextStr) || StringUtils.isEmpty(tenantRebalanceProgressStatsStr)) {
+          // Skip rebalance job: {} as it has no job context or progress stats
+          LOGGER.info("Skip checking tenant rebalance job: {} as it has no job context or progress stats", jobId);
+          continue;
+        }
+        DefaultTenantRebalanceContext tenantRebalanceContext =
+            JsonUtils.stringToObject(tenantRebalanceContextStr, DefaultTenantRebalanceContext.class);
+        TenantRebalanceProgressStats progressStats =
+            JsonUtils.stringToObject(tenantRebalanceProgressStatsStr, TenantRebalanceProgressStats.class);
+        long statsUpdatedAt = Long.parseLong(jobZKMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));
+
+        if (isTenantRebalanceJobStuck(tenantRebalanceContext, statsUpdatedAt)) {
+          for (TenantRebalancer.TenantTableRebalanceJobContext ctx;
+              (ctx = tenantRebalanceContext.getOngoingJobsQueue().poll()) != null; ) {
+            abortTableRebalanceJob(ctx.getTableName());
+            tenantRebalanceContext.getParallelQueue().addFirst(ctx);
+          }
+          // If the job is stuck, we retry it
+          resumeTenantRebalanceJob(tenantRebalanceContext, progressStats);
+        } else {
+          LOGGER.info("Tenant rebalance job: {} is not stuck", jobId);
+        }
+      } catch (JsonProcessingException e) {
+        // If we cannot parse the job metadata, we skip this job
+        LOGGER.warn("Failed to parse tenant rebalance context for job: {}, skipping", jobId);
+      }
+    }
+  }
+
+  private void resumeTenantRebalanceJob(DefaultTenantRebalanceContext tenantRebalanceContext,
+      TenantRebalanceProgressStats progressStats) {
+    DefaultTenantRebalanceContext tenantRebalanceContextForRetry =
+        DefaultTenantRebalanceContext.forRetry(tenantRebalanceContext.getOriginalJobId(),
+            tenantRebalanceContext.getConfig(), tenantRebalanceContext.getAttemptId() + 1,
+            tenantRebalanceContext.getParallelQueue(),
+            tenantRebalanceContext.getSequentialQueue(), tenantRebalanceContext.getOngoingJobsQueue());
+
+    ZkBasedTenantRebalanceObserver observer =
+        new ZkBasedTenantRebalanceObserver(tenantRebalanceContext.getJobId(),
+            tenantRebalanceContext.getConfig().getTenantName(),
+            progressStats, tenantRebalanceContextForRetry, _pinotHelixResourceManager);
+    ((DefaultTenantRebalancer) _tenantRebalancer).rebalanceWithContext(tenantRebalanceContextForRetry, observer);

Review Comment:
   @yashmayya @shounakmk219 Actually I have been wondering do we need the abstraction in `TenantRebalancer`?
   There is no such polymorphism in table rebalancer, though. 
   
   Should we just remove the abstraction layer of `TenantRebalancer`, (also the abstract class `TenantRebalanceContext` I added accordingly). Do you have anything in mind that we might need a different implementation of this rebalancer?



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] [WIP] Add TenantRebalanceChecker for improved tenant rebalance monitoring [pinot]

Posted by "J-HowHuang (via GitHub)" <gi...@apache.org>.
J-HowHuang commented on PR #16455:
URL: https://github.com/apache/pinot/pull/16455#issuecomment-3141200274

   Also, I think one issue is that this periodic task will be run on every controller. Unlike table-wise periodic tasks, which have lead controller for each table, this periodic task causes repeated execution of the same task.
   @yashmayya @shounakmk219 Do you know how can I possibly solve this problem?


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org