You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by GitBox <gi...@apache.org> on 2020/11/03 13:58:18 UTC

[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6094: Implement the segment merge task generator

Jackie-Jiang commented on a change in pull request #6094:
URL: https://github.com/apache/incubator-pinot/pull/6094#discussion_r516241034



##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/TaskGeneratorUtils.java
##########
@@ -104,4 +106,33 @@ private static boolean isTaskOlderThanOneDay(String taskName) {
         Long.parseLong(taskName.substring(taskName.lastIndexOf(PinotHelixTaskResourceManager.TASK_NAME_SEPARATOR) + 1));
     return System.currentTimeMillis() - scheduleTimeMs > ONE_DAY_IN_MILLIS;
   }
+
+  /**
+   * Get all the segments that are scheduled for all existing tables.
+   *
+   * @param taskType Task type
+   * @param clusterInfoAccessor Cluster info accessor
+   * @return a map of table name as a key and the list of scheduled segments as the value.
+   */
+  public static Map<String, Set<String>> getScheduledSegmentsMap(@Nonnull String taskType,
+      @Nonnull ClusterInfoAccessor clusterInfoAccessor) {
+    Map<String, Set<String>> scheduledSegments = new HashMap<>();
+    Map<String, TaskState> taskStates = clusterInfoAccessor.getTaskStates(taskType);
+    for (Map.Entry<String, TaskState> entry : taskStates.entrySet()) {
+      // Skip COMPLETED tasks
+      if (entry.getValue() == TaskState.COMPLETED) {
+        continue;
+      }
+      for (PinotTaskConfig pinotTaskConfig : clusterInfoAccessor.getTaskConfigs(entry.getKey())) {
+        Map<String, String> configs = pinotTaskConfig.getConfigs();
+        Set<String> scheduledSegmentsForTable =
+            scheduledSegments.computeIfAbsent(configs.get(MinionConstants.TABLE_NAME_KEY), v -> new HashSet<>());

Review comment:
       ```suggestion
               scheduledSegments.computeIfAbsent(configs.get(MinionConstants.TABLE_NAME_KEY), k -> new HashSet<>());
   ```

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/TaskGeneratorUtils.java
##########
@@ -104,4 +106,33 @@ private static boolean isTaskOlderThanOneDay(String taskName) {
         Long.parseLong(taskName.substring(taskName.lastIndexOf(PinotHelixTaskResourceManager.TASK_NAME_SEPARATOR) + 1));
     return System.currentTimeMillis() - scheduleTimeMs > ONE_DAY_IN_MILLIS;
   }
+
+  /**
+   * Get all the segments that are scheduled for all existing tables.
+   *
+   * @param taskType Task type
+   * @param clusterInfoAccessor Cluster info accessor
+   * @return a map of table name as a key and the list of scheduled segments as the value.
+   */
+  public static Map<String, Set<String>> getScheduledSegmentsMap(@Nonnull String taskType,
+      @Nonnull ClusterInfoAccessor clusterInfoAccessor) {
+    Map<String, Set<String>> scheduledSegments = new HashMap<>();
+    Map<String, TaskState> taskStates = clusterInfoAccessor.getTaskStates(taskType);
+    for (Map.Entry<String, TaskState> entry : taskStates.entrySet()) {
+      // Skip COMPLETED tasks
+      if (entry.getValue() == TaskState.COMPLETED) {
+        continue;
+      }
+      for (PinotTaskConfig pinotTaskConfig : clusterInfoAccessor.getTaskConfigs(entry.getKey())) {
+        Map<String, String> configs = pinotTaskConfig.getConfigs();
+        Set<String> scheduledSegmentsForTable =
+            scheduledSegments.computeIfAbsent(configs.get(MinionConstants.TABLE_NAME_KEY), v -> new HashSet<>());
+        String segmentName = configs.get(MinionConstants.SEGMENT_NAME_KEY);
+        Set<String> segmentNames =

Review comment:
       (Your choice as this is not in the performance critical path) Avoid using stream API as it performs much worth than the traditional for loop. Use `StringUtils.split(segmentName, ',')` to avoid regex matching.

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/TaskGeneratorUtils.java
##########
@@ -104,4 +106,33 @@ private static boolean isTaskOlderThanOneDay(String taskName) {
         Long.parseLong(taskName.substring(taskName.lastIndexOf(PinotHelixTaskResourceManager.TASK_NAME_SEPARATOR) + 1));
     return System.currentTimeMillis() - scheduleTimeMs > ONE_DAY_IN_MILLIS;
   }
+
+  /**
+   * Get all the segments that are scheduled for all existing tables.
+   *
+   * @param taskType Task type
+   * @param clusterInfoAccessor Cluster info accessor
+   * @return a map of table name as a key and the list of scheduled segments as the value.
+   */
+  public static Map<String, Set<String>> getScheduledSegmentsMap(@Nonnull String taskType,

Review comment:
       (nit) Do not use nonnull annotation

##########
File path: pinot-common/src/main/java/org/apache/pinot/common/utils/FileUploadDownloadClient.java
##########
@@ -148,6 +153,23 @@ public static URI getRetrieveAllSegmentWithTableTypeHttpUri(String host, int por
         rawTableName + TYPE_DELIMITER + tableType));
   }
 
+  public static URI getStartReplaceSegmentsURI(URI controllerURI, String rawTableName, String tableType)
+      throws URISyntaxException {
+    return new URI(StringUtil.join("/", StringUtils

Review comment:
       ```suggestion
       return getURI(controllerURI.getScheme(), controllerURI.getHost(), controllerURI.getPort(), OLD_SEGMENT_PATH + '/' + rawTableName + START_REPLACE_SEGMENTS_PATH + TYPE_DELIMITER + tableType);
   ```

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      Set<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptySet());
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : segmentsForOfflineTable) {
+        String segmentName = offlineSegmentZKMetadata.getSegmentName();
+
+        // The segment should not be merged if it's already scheduled or in progress
+        if (scheduledSegments.contains(segmentName) || segmentsNotToMerge.contains(segmentName)) {
+          continue;
+        }
+
+        // The segments that are newer than the buffer time period should not be be merged
+        if (System.currentTimeMillis() - offlineSegmentZKMetadata.getEndTime() < bufferTimePeriodMs) {
+          continue;
+        }
+        segmentsToMergeForTable.add(offlineSegmentZKMetadata);
+      }
+
+      // Compute Merge Strategy
+      List<List<SegmentZKMetadata>> segmentsToSchedule = MergeStrategyFactory.getMergeStrategy(taskConfigs)
+          .generateMergeTaskCandidates(segmentsToMergeForTable, maxNumSegmentsPerTask);
+
+      // Generate tasks
+      for (List<SegmentZKMetadata> segments : segmentsToSchedule) {
+        // TODO: wire the max num tasks to the cluster config to make it configurable.
+        if (numTasks >= DEFAULT_MAX_NUM_TASKS) {
+          break;
+        }
+        if (segments.size() >= 1) {
+          Map<String, String> configs = new HashMap<>();
+          configs.put(MinionConstants.TABLE_NAME_KEY, offlineTableName);
+          configs.put(MinionConstants.SEGMENT_NAME_KEY,
+              segments.stream().map(s -> s.getSegmentName()).collect(Collectors.joining(",")));
+          configs.put(MinionConstants.DOWNLOAD_URL_KEY,
+              segments.stream().map(s -> ((OfflineSegmentZKMetadata) s).getDownloadUrl())
+                  .collect(Collectors.joining(",")));
+          configs.put(MinionConstants.VIP_URL_KEY, _clusterInfoAccessor.getVipUrl());
+          configs.put(MinionConstants.REPLACE_SEGMENTS_KEY, Boolean.TRUE.toString());
+          configs.put(MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              Integer.toString(maxNumRecordsPerSegment));
+
+          // TODO: support ROLLUP type
+          configs.put(MinionConstants.MergeRollupTask.COLLECTOR_TYPE_KEY,
+              CollectorFactory.CollectorType.CONCAT.toString());
+          pinotTaskConfigs.add(new PinotTaskConfig(MinionConstants.MergeRollupTask.TASK_TYPE, configs));
+          numTasks++;
+        }
+      }
+    }
+    return pinotTaskConfigs;
+  }
+
+  private int readIntConfigWithDefaultValue(Map<String, String> configs, String key, int defaultValue) {
+    int intConfigValue;
+    String intConfigStrValue = configs.get(key);
+    if (intConfigStrValue != null) {
+      try {
+        intConfigValue = Integer.parseInt(intConfigStrValue);
+      } catch (Exception e) {
+        intConfigValue = defaultValue;

Review comment:
       Log a warning for the invalid value?

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      Set<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptySet());
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : segmentsForOfflineTable) {
+        String segmentName = offlineSegmentZKMetadata.getSegmentName();
+
+        // The segment should not be merged if it's already scheduled or in progress
+        if (scheduledSegments.contains(segmentName) || segmentsNotToMerge.contains(segmentName)) {
+          continue;
+        }
+
+        // The segments that are newer than the buffer time period should not be be merged
+        if (System.currentTimeMillis() - offlineSegmentZKMetadata.getEndTime() < bufferTimePeriodMs) {
+          continue;
+        }
+        segmentsToMergeForTable.add(offlineSegmentZKMetadata);
+      }
+
+      // Compute Merge Strategy
+      List<List<SegmentZKMetadata>> segmentsToSchedule = MergeStrategyFactory.getMergeStrategy(taskConfigs)
+          .generateMergeTaskCandidates(segmentsToMergeForTable, maxNumSegmentsPerTask);

Review comment:
       Should we also add a parameter for `maxNumTasksPerTable` to limit the number of tasks returned by the merge strategy?

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;

Review comment:
       Log an error and skip generating task for this table instead of throwing exception and aborting the entire job

##########
File path: pinot-common/src/main/java/org/apache/pinot/common/utils/FileUploadDownloadClient.java
##########
@@ -148,6 +153,23 @@ public static URI getRetrieveAllSegmentWithTableTypeHttpUri(String host, int por
         rawTableName + TYPE_DELIMITER + tableType));
   }
 
+  public static URI getStartReplaceSegmentsURI(URI controllerURI, String rawTableName, String tableType)
+      throws URISyntaxException {
+    return new URI(StringUtil.join("/", StringUtils
+            .chomp(controllerURI.getScheme() + "://" + controllerURI.getHost() + ":" + controllerURI.getPort(), "/"),
+        OLD_SEGMENT_PATH, rawTableName + START_REPLACE_SEGMENTS_PATH + TYPE_DELIMITER + tableType));
+  }
+
+  public static URI getEndReplaceSegmentsURI(URI controllerURI, String rawTableName, String tableType,
+      String segmentLineageEntryId)
+      throws URISyntaxException {
+    return new URI(StringUtil.join("/", StringUtils

Review comment:
       Same here

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      Set<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptySet());
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : segmentsForOfflineTable) {
+        String segmentName = offlineSegmentZKMetadata.getSegmentName();
+
+        // The segment should not be merged if it's already scheduled or in progress
+        if (scheduledSegments.contains(segmentName) || segmentsNotToMerge.contains(segmentName)) {
+          continue;
+        }
+
+        // The segments that are newer than the buffer time period should not be be merged
+        if (System.currentTimeMillis() - offlineSegmentZKMetadata.getEndTime() < bufferTimePeriodMs) {

Review comment:
       (Critical) Please double-check if the `endTime` in the ZK metadata is in millis. I don't think it's always the case

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      Set<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptySet());

Review comment:
       Directly add `scheduledSegments` into `segmentsNotToMerge` for readability?

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      Set<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptySet());
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : segmentsForOfflineTable) {
+        String segmentName = offlineSegmentZKMetadata.getSegmentName();
+
+        // The segment should not be merged if it's already scheduled or in progress
+        if (scheduledSegments.contains(segmentName) || segmentsNotToMerge.contains(segmentName)) {
+          continue;
+        }
+
+        // The segments that are newer than the buffer time period should not be be merged
+        if (System.currentTimeMillis() - offlineSegmentZKMetadata.getEndTime() < bufferTimePeriodMs) {
+          continue;
+        }
+        segmentsToMergeForTable.add(offlineSegmentZKMetadata);
+      }
+
+      // Compute Merge Strategy
+      List<List<SegmentZKMetadata>> segmentsToSchedule = MergeStrategyFactory.getMergeStrategy(taskConfigs)
+          .generateMergeTaskCandidates(segmentsToMergeForTable, maxNumSegmentsPerTask);
+
+      // Generate tasks
+      for (List<SegmentZKMetadata> segments : segmentsToSchedule) {
+        // TODO: wire the max num tasks to the cluster config to make it configurable.
+        if (numTasks >= DEFAULT_MAX_NUM_TASKS) {
+          break;
+        }
+        if (segments.size() >= 1) {
+          Map<String, String> configs = new HashMap<>();
+          configs.put(MinionConstants.TABLE_NAME_KEY, offlineTableName);
+          configs.put(MinionConstants.SEGMENT_NAME_KEY,
+              segments.stream().map(s -> s.getSegmentName()).collect(Collectors.joining(",")));

Review comment:
       (nit) Avoid using stream for performance concern

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();

Review comment:
       Rename it to `candidateSegments`? The merge strategy should choose from the candidate segments and return the `segmentsToMerge`

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      Set<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptySet());
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : segmentsForOfflineTable) {
+        String segmentName = offlineSegmentZKMetadata.getSegmentName();
+
+        // The segment should not be merged if it's already scheduled or in progress
+        if (scheduledSegments.contains(segmentName) || segmentsNotToMerge.contains(segmentName)) {
+          continue;
+        }
+
+        // The segments that are newer than the buffer time period should not be be merged
+        if (System.currentTimeMillis() - offlineSegmentZKMetadata.getEndTime() < bufferTimePeriodMs) {
+          continue;
+        }
+        segmentsToMergeForTable.add(offlineSegmentZKMetadata);
+      }
+
+      // Compute Merge Strategy
+      List<List<SegmentZKMetadata>> segmentsToSchedule = MergeStrategyFactory.getMergeStrategy(taskConfigs)
+          .generateMergeTaskCandidates(segmentsToMergeForTable, maxNumSegmentsPerTask);
+
+      // Generate tasks
+      for (List<SegmentZKMetadata> segments : segmentsToSchedule) {
+        // TODO: wire the max num tasks to the cluster config to make it configurable.
+        if (numTasks >= DEFAULT_MAX_NUM_TASKS) {
+          break;
+        }
+        if (segments.size() >= 1) {
+          Map<String, String> configs = new HashMap<>();
+          configs.put(MinionConstants.TABLE_NAME_KEY, offlineTableName);
+          configs.put(MinionConstants.SEGMENT_NAME_KEY,
+              segments.stream().map(s -> s.getSegmentName()).collect(Collectors.joining(",")));
+          configs.put(MinionConstants.DOWNLOAD_URL_KEY,
+              segments.stream().map(s -> ((OfflineSegmentZKMetadata) s).getDownloadUrl())
+                  .collect(Collectors.joining(",")));
+          configs.put(MinionConstants.VIP_URL_KEY, _clusterInfoAccessor.getVipUrl());

Review comment:
       Out of the scope of this PR, but we should also support the metadata-only push

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/mergestrategy/MergeStrategyFactory.java
##########
@@ -0,0 +1,54 @@
+/**
+ * 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.minion.mergestrategy;
+
+import java.util.Map;
+import org.apache.pinot.core.common.MinionConstants;
+
+
+public class MergeStrategyFactory {
+  public enum MergeStrategyType {
+    /**
+     * Time based merge strategy
+     */
+    TIME
+  }
+
+  private MergeStrategyFactory() {
+  }
+
+  public static MergeStrategy getMergeStrategy(Map<String, String> taskConfigs) {
+    String mergeStrategyTypeStr =
+        taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.MERGE_STRATEGY_TYPE, MergeStrategyType.TIME.name());
+
+    MergeStrategyType mergeStrategyType;
+    try {
+      mergeStrategyType = MergeStrategyType.valueOf(mergeStrategyTypeStr.toUpperCase());
+    } catch (IllegalArgumentException e) {
+      mergeStrategyType = MergeStrategyType.TIME;

Review comment:
       Should we abort for invalid value?

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,196 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoAccessor _clusterInfoAccessor;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, Set<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoAccessor);
+
+    // Generate tasks
+    int numTasks = 0;
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      Set<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptySet());
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : segmentsForOfflineTable) {
+        String segmentName = offlineSegmentZKMetadata.getSegmentName();
+
+        // The segment should not be merged if it's already scheduled or in progress
+        if (scheduledSegments.contains(segmentName) || segmentsNotToMerge.contains(segmentName)) {
+          continue;
+        }
+
+        // The segments that are newer than the buffer time period should not be be merged
+        if (System.currentTimeMillis() - offlineSegmentZKMetadata.getEndTime() < bufferTimePeriodMs) {
+          continue;
+        }
+        segmentsToMergeForTable.add(offlineSegmentZKMetadata);
+      }
+
+      // Compute Merge Strategy
+      List<List<SegmentZKMetadata>> segmentsToSchedule = MergeStrategyFactory.getMergeStrategy(taskConfigs)
+          .generateMergeTaskCandidates(segmentsToMergeForTable, maxNumSegmentsPerTask);
+
+      // Generate tasks
+      for (List<SegmentZKMetadata> segments : segmentsToSchedule) {
+        // TODO: wire the max num tasks to the cluster config to make it configurable.
+        if (numTasks >= DEFAULT_MAX_NUM_TASKS) {

Review comment:
       An easier way might be just check the `pinotTaskConfigs.size()`

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/TaskGeneratorUtils.java
##########
@@ -68,4 +73,30 @@
     }
     return runningSegments;
   }
+
+  public static Map<String, List<String>> getScheduledSegmentsMap(@Nonnull String taskType,
+      @Nonnull ClusterInfoProvider clusterInfoProvider) {
+    Map<String, List<String>> scheduledSegments = new HashMap<>();
+    Map<String, TaskState> taskStates = clusterInfoProvider.getTaskStates(taskType);
+    for (Map.Entry<String, TaskState> entry : taskStates.entrySet()) {
+      // Skip COMPLETED tasks
+      if (entry.getValue() == TaskState.COMPLETED) {
+        continue;
+      }

Review comment:
       If the task got stuck, even after the lineage is cleaned, we still won't reschedule the old task because the segments  are shown in the scheduled task. In order to reschedule the the old task, we need to skip the stuck tasks and also clean the lineage

##########
File path: pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/generator/SegmentMergeRollupTaskGenerator.java
##########
@@ -0,0 +1,199 @@
+/**
+ * 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.minion.generator;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.pinot.common.lineage.LineageEntry;
+import org.apache.pinot.common.lineage.LineageEntryState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoProvider;
+import org.apache.pinot.controller.helix.core.minion.mergestrategy.MergeStrategyFactory;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.core.segment.processing.collector.CollectorFactory;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class SegmentMergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentMergeRollupTaskGenerator.class);
+
+  private static final int DEFAULT_MAX_NUM_SEGMENTS_PER_TASK = 20; // 20 segments
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT = 5_000_000; // 5 million rows
+  private static final int DEFAULT_MAX_NUM_TASKS = 200; // schedule at most 200 tasks at a time
+  private static final String DEFAULT_BUFFER_TIME_PERIOD = "14d"; // 2 weeks
+
+  private final ClusterInfoProvider _clusterInfoProvider;
+
+  public SegmentMergeRollupTaskGenerator(ClusterInfoProvider clusterInfoProvider) {
+    _clusterInfoProvider = clusterInfoProvider;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MinionConstants.MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    // Get the segments that are being converted so that we don't submit them again
+    Map<String, List<String>> scheduledSegmentsMap =
+        TaskGeneratorUtils.getScheduledSegmentsMap(MinionConstants.MergeRollupTask.TASK_TYPE, _clusterInfoProvider);
+
+    for (TableConfig tableConfig : tableConfigs) {
+      // Only generate tasks for OFFLINE tables
+      String offlineTableName = tableConfig.getTableName();
+      if (tableConfig.getTableType() != TableType.OFFLINE) {
+        LOGGER.warn("Skip generating MergeRollupTask for non-OFFLINE table: {}", offlineTableName);
+        continue;
+      }
+
+      TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig();
+      Preconditions.checkNotNull(tableTaskConfig);
+      Map<String, String> taskConfigs =
+          tableTaskConfig.getConfigsForTaskType(MinionConstants.MergeRollupTask.TASK_TYPE);
+      Preconditions.checkNotNull(taskConfigs, "Task config shouldn't be null for Table: {}", offlineTableName);
+
+      int tableMaxNumTasks =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.TABLE_MAX_NUM_TASKS_KEY, DEFAULT_MAX_NUM_TASKS);
+
+      int maxNumSegmentsPerTask =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_SEGMENTS_PER_TASK_KEY,
+              DEFAULT_MAX_NUM_SEGMENTS_PER_TASK);
+
+      int maxNumRecordsPerSegment =
+          readIntConfigWithDefaultValue(taskConfigs, MinionConstants.MergeRollupTask.MAX_NUM_RECORDS_PER_SEGMENT_KEY,
+              DEFAULT_MAX_NUM_RECORDS_PER_SEGMENT);
+
+      String bufferTimePeriod =
+          taskConfigs.getOrDefault(MinionConstants.MergeRollupTask.BUFFER_TIME_PERIOD_KEY, DEFAULT_BUFFER_TIME_PERIOD);
+      long bufferTimePeriodMs;
+      try {
+        bufferTimePeriodMs= TimeUtils.convertPeriodToMillis(bufferTimePeriod);
+      } catch (IllegalArgumentException e) {
+        LOGGER.error("Buffer time period ('{}') for table '{}' is not configured correctly.", bufferTimePeriod,
+            offlineTableName, e);
+        throw e;
+      }
+
+      // Generate tasks
+      int tableNumTasks = 0;
+
+      List<OfflineSegmentZKMetadata> segmentsForOfflineTable =
+          _clusterInfoProvider.getOfflineSegmentsMetadata(offlineTableName);
+
+      // Fetch the segment lineage for the table and compute the segments that should not be scheduled for merge
+      // based on the segment lineage.
+      SegmentLineage segmentLineageForTable = _clusterInfoProvider.getSegmentLineage(offlineTableName);
+      Set<String> segmentsNotToMerge = new HashSet<>();
+      if (segmentLineageForTable != null) {
+        for (String segmentLineageEntryId : segmentLineageForTable.getLineageEntryIds()) {
+          LineageEntry lineageEntry = segmentLineageForTable.getLineageEntry(segmentLineageEntryId);
+          // Segments shows up on "segmentFrom" field in the lineage entry should not be scheduled again.
+          segmentsNotToMerge.addAll(lineageEntry.getSegmentsFrom());
+
+          // Segments shows up on "segmentsTo" field in the lineage entry with "IN_PROGRESS" state cannot be merged.
+          if (lineageEntry.getState() == LineageEntryState.IN_PROGRESS) {
+            segmentsNotToMerge.addAll(lineageEntry.getSegmentsTo());
+          }
+        }
+      }
+
+      // Filter out the segments that cannot be merged
+      List<SegmentZKMetadata> segmentsToMergeForTable = new ArrayList<>();
+      List<String> scheduledSegments = scheduledSegmentsMap.getOrDefault(offlineTableName, Collections.emptyList());
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : segmentsForOfflineTable) {
+        String segmentName = offlineSegmentZKMetadata.getSegmentName();
+
+        // The segment should not be merged if it's already scheduled or in progress
+        if (scheduledSegments.contains(segmentName) || segmentsNotToMerge.contains(segmentName)) {
+          continue;
+        }
+
+        // The segments that are newer than the buffer time period should not be be merged
+        if (System.currentTimeMillis() - offlineSegmentZKMetadata.getEndTime() < bufferTimePeriodMs) {
+          continue;
+        }
+        segmentsToMergeForTable.add(offlineSegmentZKMetadata);
+      }
+
+      // Compute Merge Strategy
+      List<List<SegmentZKMetadata>> segmentsToSchedule = MergeStrategyFactory.getMergeStrategy(taskConfigs)
+          .generateMergeTaskCandidates(segmentsToMergeForTable, maxNumSegmentsPerTask);
+
+      // Generate tasks
+      for (List<SegmentZKMetadata> segments : segmentsToSchedule) {
+        if (tableNumTasks == tableMaxNumTasks) {
+          break;
+        }
+        if (segments.size() >= 1) {
+          Map<String, String> configs = new HashMap<>();
+          configs.put(MinionConstants.TABLE_NAME_KEY, offlineTableName);
+          configs.put(MinionConstants.SEGMENT_NAME_KEY,
+              segments.stream().map(s -> s.getSegmentName()).collect(Collectors.joining(",")));
+          configs.put(MinionConstants.DOWNLOAD_URL_KEY,
+              segments.stream().map(s -> ((OfflineSegmentZKMetadata) s).getDownloadUrl())
+                  .collect(Collectors.joining(",")));
+          configs.put(MinionConstants.VIP_URL_KEY, _clusterInfoProvider.getVipUrl());
+          configs.put(MinionConstants.REPLACE_SEGMENTS_KEY, Boolean.TRUE.toString());

Review comment:
       For this specific job type, I don't think we need this extra config. On the minion side, it should always use the `replaceSegment` API, instead of picking it from the task config.




----------------------------------------------------------------
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.

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