xiangfu0 commented on code in PR #20220: URL: https://github.com/apache/pinot/pull/20220#discussion_r4633183960
########## pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/ReplicateModeFailoverManager.java: ########## @@ -0,0 +1,417 @@ +/** + * 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.realtime; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Suppliers; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import org.apache.helix.PropertyPathBuilder; +import org.apache.helix.model.ExternalView; +import org.apache.helix.model.IdealState; +import org.apache.helix.model.InstanceConfig; +import org.apache.pinot.common.assignment.ReplicateModeAssignmentUtils; +import org.apache.pinot.common.metadata.segment.SegmentZKMetadata; +import org.apache.pinot.common.metrics.ControllerGauge; +import org.apache.pinot.common.metrics.ControllerMetrics; +import org.apache.pinot.common.utils.LLCSegmentName; +import org.apache.pinot.controller.ControllerConf; +import org.apache.pinot.controller.LeadControllerManager; +import org.apache.pinot.controller.helix.core.PinotHelixResourceManager; +import org.apache.pinot.controller.helix.core.periodictask.ControllerPeriodicTask; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeCandidateSelector.CandidateContext; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeRecoveryPlanner.FailureReason; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeRecoveryPlanner.PartitionRecoveryPlan; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeRecoveryPlanner.SegmentSnapshot; +import org.apache.pinot.controller.helix.core.realtime.SegmentCompletionFSM.RecoveryStatus; +import org.apache.pinot.core.periodictask.PeriodicTask; +import org.apache.pinot.spi.config.table.TableConfig; +import org.apache.pinot.spi.utils.CommonConstants.Helix.StateModel.SegmentStateModel; +import org.apache.pinot.spi.utils.CommonConstants.Segment.Realtime.Status; +import org.apache.pinot.spi.utils.builder.TableNameBuilder; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/// Observes replicate-mode failures and reconciles partition recovery on the table's lead Controller. +/// +/// Planning selects eligible recovery hosts; the executor revalidates each action before changing assignment intent. +/// Segment metadata is authoritative for mode and completion. Only current consumption candidates and the native +/// pending-completion list are checked. Discovery does not probe Servers over HTTP; +/// explicit fixed-range recovery submissions are bounded separately by the executor. +/// +/// Periodic and on-demand executions are serialized by the parent task. Consumption-stop notifications only mark a +/// table dirty for priority processing on the next periodic pass. Pending failures are immutable, reconstructible +/// observations, not recovery authorization; the executor validates current state again before every action. +/// Concurrent notifications and snapshot reads are supported. The existing scheduler owns the task lifecycle. +public class ReplicateModeFailoverManager extends ControllerPeriodicTask<ReplicateModeFailoverManager.Context> { + public static final String TASK_NAME = "ReplicateModeFailoverManager"; + private static final Logger LOGGER = LoggerFactory.getLogger(ReplicateModeFailoverManager.class); + + private final PinotLLCRealtimeSegmentManager _segmentManager; + private final SegmentCompletionManager _completionManager; + private final ReplicateModeRecoveryPlanner _recoveryPlanner; + private final ReplicateModeRecoveryExecutor _recoveryExecutor; + private final int _maxRepairActionsPerTable; + private final Clock _clock; + private final Set<String> _dirtyTables = ConcurrentHashMap.newKeySet(); + private final Map<String, TableObservation> _tableObservations = new ConcurrentHashMap<>(); + private final Map<String, IdealStateVersion> _tablesWithoutRoles = new ConcurrentHashMap<>(); + + public ReplicateModeFailoverManager(ControllerConf config, PinotHelixResourceManager resourceManager, + LeadControllerManager leadControllerManager, ControllerMetrics controllerMetrics, + PinotLLCRealtimeSegmentManager segmentManager, SegmentCompletionManager completionManager) { + this(config, resourceManager, leadControllerManager, controllerMetrics, segmentManager, completionManager, + Clock.systemUTC()); + } + + @VisibleForTesting + ReplicateModeFailoverManager(ControllerConf config, PinotHelixResourceManager resourceManager, + LeadControllerManager leadControllerManager, ControllerMetrics controllerMetrics, + PinotLLCRealtimeSegmentManager segmentManager, SegmentCompletionManager completionManager, Clock clock) { + this(config, resourceManager, leadControllerManager, controllerMetrics, segmentManager, completionManager, clock, + new ReplicateModeRecoveryExecutor(config, resourceManager, leadControllerManager, segmentManager, + completionManager, controllerMetrics, clock)); + } + + @VisibleForTesting + ReplicateModeFailoverManager(ControllerConf config, PinotHelixResourceManager resourceManager, + LeadControllerManager leadControllerManager, ControllerMetrics controllerMetrics, + PinotLLCRealtimeSegmentManager segmentManager, SegmentCompletionManager completionManager, Clock clock, + ReplicateModeRecoveryExecutor recoveryExecutor) { + super(TASK_NAME, config.getReplicateModeFailoverFrequencyInSeconds(), + config.getReplicateModeFailoverInitialDelayInSeconds(), config.getReplicateModeFailoverCronExpression(), + resourceManager, leadControllerManager, controllerMetrics); + _segmentManager = segmentManager; + _completionManager = completionManager; + _recoveryPlanner = new ReplicateModeRecoveryPlanner(config); + _recoveryExecutor = recoveryExecutor; + _maxRepairActionsPerTable = config.getReplicateModeRecoveryMaxActionsPerTable(); + _clock = clock; + } + + /// Marks a table for priority inspection. This callback performs no metadata reads or recovery work. + public void requestReconciliation(String tableNameWithType) { + if (isStarted() && TableNameBuilder.isRealtimeTableResource(tableNameWithType)) { + _dirtyTables.add(tableNameWithType); + } + } + + /// Returns an immutable observation snapshot. These observations must not be used without revalidation to recover. + @VisibleForTesting + Map<String, PendingFailure> getPendingFailures(String tableNameWithType) { + TableObservation observation = _tableObservations.get(tableNameWithType); + return observation != null ? observation.failures() : Map.of(); + } + + /// Returns the latest observed plans. Execution may already have advanced; plans are not recovery authorization. + @VisibleForTesting + Map<Integer, PartitionRecoveryPlan> getRecoveryPlans(String tableNameWithType) { + TableObservation observation = _tableObservations.get(tableNameWithType); + return observation != null ? observation.plans() : Map.of(); + } + + @Override + protected void setUpTask() { + _segmentManager.setConsumptionStoppedListener(this::requestReconciliation); + } + + @Override + protected void cleanUpTask() { + _segmentManager.setConsumptionStoppedListener(null); + _dirtyTables.clear(); + _tableObservations.clear(); + _tablesWithoutRoles.clear(); + _recoveryExecutor.clear(); + } + + @Override + protected List<String> getTablesToProcess(Properties properties) { + // The parent does not call postprocess when this Controller leads no tables, including before the first run. + clearNonLeaderObservations(); + List<String> tables = super.getTablesToProcess(properties); + if (properties.getProperty(PeriodicTask.PROPERTY_KEY_TABLE_NAME) != null) { + return tables; + } + Set<String> orderedTables = new LinkedHashSet<>(new TreeSet<>(_dirtyTables)); + orderedTables.addAll(tables); + // Revisit observations of deleted tables so their state is removed even if they left the table catalog. + orderedTables.addAll(new TreeSet<>(_tableObservations.keySet())); + orderedTables.addAll(new TreeSet<>(_tablesWithoutRoles.keySet())); + return List.copyOf(orderedTables); + } + + @Override + protected boolean shouldProcessTable(String tableNameWithType) { + return TableNameBuilder.isRealtimeTableResource(tableNameWithType) && super.shouldProcessTable(tableNameWithType); + } + + @Override + protected Context preprocess(Properties properties) { + // Most clusters have no replicate-mode tables. Read liveness at most once, and only when a candidate needs it. + Supplier<Set<String>> liveInstances = Suppliers.memoize( + () -> Set.copyOf(_pinotHelixResourceManager.getAllLiveInstances())); + Supplier<Map<String, InstanceConfig>> instanceConfigs = Suppliers.memoize( + () -> _pinotHelixResourceManager.getAllHelixInstanceConfigs().stream() + .collect(Collectors.toUnmodifiableMap(InstanceConfig::getInstanceName, config -> config))); + return new Context(_clock.millis(), liveInstances, instanceConfigs); + } + + @Override + protected void processTables(List<String> tableNamesWithType, Properties properties) { + // The parent filters the catalog through a Set, so prioritize after leadership filtering as well. + Set<String> dirtyTables = Set.copyOf(_dirtyTables); + List<String> orderedTables = new ArrayList<>(tableNamesWithType); + orderedTables.sort(Comparator.comparing((String table) -> !dirtyTables.contains(table)) + .thenComparing(Comparator.naturalOrder())); + super.processTables(orderedTables, properties); + } + + @Override + protected void processTable(String tableNameWithType, Context context) { + // Notifications arriving during inspection remain dirty for the next pass. + boolean dirty = _dirtyTables.remove(tableNameWithType); + // Ordinary tables can have very large assignments. Probe only the znode stat while a negative role observation + // is unchanged. Read the stat BEFORE the full IS, so a concurrent role addition cannot be cached as absent. + String path = PropertyPathBuilder.idealState(_pinotHelixResourceManager.getHelixClusterName(), tableNameWithType); + Stat stat = _pinotHelixResourceManager.getZKStat(path); + IdealStateVersion version = stat != null ? new IdealStateVersion(stat.getCzxid(), stat.getVersion()) : null; + if (!dirty && version != null && version.equals(_tablesWithoutRoles.get(tableNameWithType))) { + return; + } + _tablesWithoutRoles.remove(tableNameWithType); + IdealState idealState = _pinotHelixResourceManager.getTableIdealState(tableNameWithType); + if (idealState == null || !idealState.isEnabled() || PinotLLCRealtimeSegmentManager.isTablePaused(idealState)) { + clearTableRecovery(tableNameWithType); + return; + } + int repairs = 0; + for (Map.Entry<String, String> restart : ReplicateModeAssignmentUtils.getPendingRestarts(idealState).entrySet()) { + if (!isStarted() || !_leadControllerManager.isLeaderForTable(tableNameWithType) + || repairs++ >= _maxRepairActionsPerTable) { + break; + } + try { + _segmentManager.restartReplicateModeConsumer(tableNameWithType, restart.getKey(), restart.getValue()); + } catch (Exception e) { + LOGGER.warn("Will retry manual-rebalance consumer repair for {} in table {}", restart.getKey(), + tableNameWithType, e); + } + } + Map<Integer, String> leaders = ReplicateModeAssignmentUtils.getLeaders(idealState); + if (leaders.isEmpty()) { + clearTableRecovery(tableNameWithType); + if (version != null && isStarted() && _leadControllerManager.isLeaderForTable(tableNameWithType)) { + _tablesWithoutRoles.put(tableNameWithType, version); + } + return; + } + + Set<String> candidates = getSegmentsToInspect(idealState, leaders); + Set<String> pendingCompletions = new HashSet<>(_segmentManager.getPendingSegmentCompletions(tableNameWithType)); + candidates.addAll(pendingCompletions); + Map<Integer, PartitionRecoveryPlan> previousPlans = getRecoveryPlans(tableNameWithType); + // Keep following a known completion window even if its Server becomes healthy again in the meantime. + previousPlans.values().forEach(plan -> candidates.addAll(plan.segments().keySet())); + ExternalView externalView = _pinotHelixResourceManager.getTableExternalView(tableNameWithType); + Map<String, PendingFailure> previous = getPendingFailures(tableNameWithType); + Set<String> plannedSegments = new HashSet<>(); + previousPlans.values().forEach(plan -> plannedSegments.addAll(plan.segments().keySet())); + Map<String, PendingFailure> observed = new HashMap<>(); + List<SegmentSnapshot> snapshots = new ArrayList<>(); + for (String segmentName : candidates) { + if (!isStarted()) { + return; + } + LLCSegmentName llcSegmentName = LLCSegmentName.of(segmentName); + if (llcSegmentName == null || !leaders.containsKey(llcSegmentName.getPartitionGroupId()) + || PinotLLCRealtimeSegmentManager.isTopicPaused(idealState, segmentName)) { + continue; + } + Map<String, String> assignment = idealState.getInstanceStateMap(segmentName); + Map<String, String> states = assignment != null ? assignment : Map.of(); + FailureReason reason = ReplicateModeRecoveryPlanner.getFailureReason(states, externalView, segmentName, + context._liveInstances); + if (reason == null && !plannedSegments.contains(segmentName) && !pendingCompletions.contains(segmentName)) { + continue; + } + + Stat metadataStat = new Stat(); + SegmentZKMetadata metadata = + _segmentManager.getSegmentZKMetadataIfExists(tableNameWithType, segmentName, metadataStat); + if (metadata == null || !metadata.isReplicateMode()) { + continue; + } + Status status = metadata.getStatus(); + int partitionId = llcSegmentName.getPartitionGroupId(); + RecoveryStatus completionStatus = _completionManager.getRecoveryStatus(segmentName); + boolean completionTimedOut = (status == Status.COMMITTING || status == Status.DONE) + && _segmentManager.isExceededMaxSegmentCompletionTime(segmentName, metadataStat, context._nowMs); + snapshots.add(new SegmentSnapshot(metadata, states, reason, completionStatus, completionTimedOut, + pendingCompletions.contains(segmentName))); + // Preserve the original failure-observation API: plans may also cover completed or inconsistent assignments. + if (reason == null || states.size() != 1 || status != Status.IN_PROGRESS && status != Status.COMMITTING) { + continue; + } + Map.Entry<String, String> assignedInstance = states.entrySet().iterator().next(); + String server = assignedInstance.getKey(); + if (status == Status.IN_PROGRESS && (!server.equals(leaders.get(partitionId)) + || SegmentStateModel.ONLINE.equals(assignedInstance.getValue()))) { + continue; + } + // An older COMMITTING segment can still belong to A after B leads the newer consuming segment. + PendingFailure oldFailure = previous.get(segmentName); + boolean sameFailure = oldFailure != null && oldFailure.serverName().equals(server) + && oldFailure.status() == status && oldFailure.reason() == reason; + long firstObserved = sameFailure ? oldFailure.firstObservedTimeMs() : context._nowMs; + PendingFailure failure = new PendingFailure(partitionId, segmentName, server, status, reason, firstObserved, + context._nowMs); + observed.put(segmentName, failure); Review Comment: Nothing gates on the `firstObservedTimeMs` carried forward here, so a consuming segment whose leader drops out of LiveInstances is planned for `REASSIGN_CONSUMING` on the first pass that sees it, and passes run every 10 s by default. With no reclaim after recovery (2.6.7), a rolling restart usually hands off the partitions each restarting server leads, and a partition handed to a server that restarts later in the same roll replays again. Could you add a configurable minimum failure age for `INSTANCE_NOT_LIVE` before planning the handoff, long enough to cover a typical restart? In case it helps, a graceful stop leaves `shutdownInProgress=true` in the instance config until the next startup clears it ([BaseServerStarter](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java#L1063-L1064)), which tells a planned stop from a crash. ########## pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/assignment/segment/RealtimeSegmentAssignment.java: ########## @@ -416,7 +526,161 @@ public TableAssignment rebalanceTable(IdealState idealState, _logger.info("Rebalanced table: {}, number of segments to be added/removed for each instance: {}", _tableNameWithType, SegmentAssignmentUtils.getNumSegmentsToMovePerInstance(currentAssignment, newAssignment)); - return new TableAssignment(newAssignment, partitionAssignment, segmentPartitionIds); + Map<Integer, ReplicateModePartitionAssignment> replicateAssignment = rebalanceReplicateModeSegments(idealState, + replicateSegments, newAssignment, consumingInstancePartitions, partitionAssignment, segmentPartitionIds, + includeConsuming); + return new TableAssignment(newAssignment, partitionAssignment, segmentPartitionIds, replicateAssignment, + replicateSegments.keySet()); + } + + /// Snapshot metadata is authoritative even after the current table flags change. Rebalance is infrequent and + /// reads LLC metadata in one strict batch, including old COMMITTING segments missing from the native hint list. + private Map<String, SegmentZKMetadata> getReplicateModeSegments(IdealState idealState) { + if (!IngestionConfigUtils.isReplicateModeEnabled(_tableConfig) + && ReplicateModeAssignmentUtils.getLeaders(idealState).isEmpty()) { + return Map.of(); + } + List<String> segments = idealState.getRecord().getMapFields().keySet().stream() + .filter(segment -> LLCSegmentName.of(segment) != null).sorted().toList(); + if (segments.isEmpty()) { + return Map.of(); + } + List<SegmentZKMetadata> metadataList = ZKMetadataProvider.getSegmentsZKMetadata( + _helixManager.getHelixPropertyStore(), _tableNameWithType, segments, null, true); + Map<String, SegmentZKMetadata> snapshots = new TreeMap<>(); + for (int i = 0; i < segments.size(); i++) { + SegmentZKMetadata metadata = metadataList.get(i); + Preconditions.checkState(metadata != null, "Missing metadata during replicate-mode rebalance: %s", + segments.get(i)); + if (metadata.isReplicateMode()) { + snapshots.put(metadata.getSegmentName(), metadata); + } + } + return snapshots; + } + + private Map<Integer, ReplicateModePartitionAssignment> rebalanceReplicateModeSegments(IdealState idealState, + Map<String, SegmentZKMetadata> segments, Map<String, Map<String, String>> targetAssignment, + InstancePartitions consumingInstancePartitions, Map<Integer, List<String>> partitionAssignment, + Object2IntMap<String> segmentPartitionIds, boolean includeConsuming) { + if (segments.isEmpty()) { + return Map.of(); + } + Map<Integer, List<SegmentZKMetadata>> byPartition = new TreeMap<>(); + segments.values().forEach(metadata -> byPartition.computeIfAbsent( + new LLCSegmentName(metadata.getSegmentName()).getPartitionGroupId(), ignored -> new ArrayList<>()) + .add(metadata)); + Map<String, Integer> leaderCounts = new HashMap<>(); + ReplicateModeAssignmentUtils.getLeaders(idealState).values() + .forEach(server -> leaderCounts.merge(server, 1, Integer::sum)); + Map<Integer, ReplicateModePartitionAssignment> roles = new TreeMap<>(); + Map<Integer, List<String>> eligibleByPartition = new TreeMap<>(); + IdealState candidateState = new IdealState(new ZNRecord(idealState.getRecord())); + Map<String, InstanceConfig> instanceConfigs = null; + Set<String> liveInstances = null; + for (Map.Entry<Integer, List<SegmentZKMetadata>> entry : byPartition.entrySet()) { + int partition = entry.getKey(); + List<SegmentZKMetadata> partitionSegments = entry.getValue(); + String recordedLeader = ReplicateModeAssignmentUtils.getLeader(idealState, partition); + List<String> recordedReplicas = ReplicateModeAssignmentUtils.getReplicas(idealState, partition); + boolean paused = PinotLLCRealtimeSegmentManager.isTablePaused(idealState) + || PinotLLCRealtimeSegmentManager.isTopicPaused(idealState, partitionSegments.get(0).getSegmentName()); + boolean moveConsuming = includeConsuming && !paused; + String representative = partitionSegments.get(0).getSegmentName(); + List<String> replicas = !moveConsuming && !recordedReplicas.isEmpty() + ? recordedReplicas + : getTargetInstances(representative, consumingInstancePartitions, partitionAssignment, segmentPartitionIds); + Preconditions.checkState(!replicas.isEmpty(), "No replica placement for partition: %s", partition); + List<SegmentZKMetadata> consuming = partitionSegments.stream() + .filter(metadata -> metadata.getStatus() == Status.IN_PROGRESS).toList(); + Preconditions.checkState(consuming.size() <= 1, + "Multiple unfinished consuming segments for replicate-mode partition: %s", partition); + String leader = recordedLeader; + if (!consuming.isEmpty() && moveConsuming) { + if (instanceConfigs == null) { + instanceConfigs = HelixHelper.getInstanceConfigs(_helixManager).stream() + .collect(Collectors.toMap(InstanceConfig::getInstanceName, instance -> instance)); + liveInstances = Set.copyOf(_helixManager.getHelixDataAccessor().getChildNames( + _helixManager.getHelixDataAccessor().keyBuilder().liveInstances())); + } + ReplicateModeAssignmentUtils.setAssignment(candidateState, partition, + recordedLeader != null && replicas.contains(recordedLeader) ? recordedLeader : replicas.get(0), replicas); + if (_partitionPinned) { + PartitionAssignmentUtils.setInstances(candidateState, partition, replicas); + } + CandidateContext context = new CandidateContext(_tableConfig, candidateState, consumingInstancePartitions, + instanceConfigs, liveInstances); + List<String> eligible = ReplicateModeCandidateSelector.getEligibleServersForRebalance(context, partition, + consuming.stream().map(SegmentZKMetadata::getSegmentName).toList(), System.currentTimeMillis()); + Preconditions.checkState(!eligible.isEmpty(), "No eligible consumption leader for partition: %s", partition); + eligibleByPartition.put(partition, eligible); + if (recordedLeader != null) { + leaderCounts.computeIfPresent(recordedLeader, (server, count) -> Math.max(0, count - 1)); + } + int minCount = eligible.stream().mapToInt(server -> leaderCounts.getOrDefault(server, 0)).min().orElseThrow(); + if (recordedLeader != null && eligible.contains(recordedLeader) + && leaderCounts.getOrDefault(recordedLeader, 0) == minCount) { + leader = recordedLeader; + } else { + int startIndex = Math.floorMod(partition, eligible.size()); + for (int i = 0; i < eligible.size(); i++) { + String candidate = eligible.get((startIndex + i) % eligible.size()); + if (leaderCounts.getOrDefault(candidate, 0) == minCount) { + leader = candidate; + break; + } + } + } + leaderCounts.merge(leader, 1, Integer::sum); + } else if (!consuming.isEmpty()) { + Map<String, String> current = idealState.getInstanceStateMap(consuming.get(0).getSegmentName()); + leader = recordedLeader != null && current.containsKey(recordedLeader) + ? recordedLeader + : current.keySet().stream().sorted().findFirst() + .orElseThrow(() -> new IllegalStateException("Empty consuming assignment")); + } + if (leader == null || !replicas.contains(leader)) { + leader = replicas.get(0); + } + roles.put(partition, new ReplicateModePartitionAssignment(leader, replicas)); + for (SegmentZKMetadata metadata : partitionSegments) { + String segment = metadata.getSegmentName(); + Map<String, String> current = idealState.getInstanceStateMap(segment); + Preconditions.checkState(current != null && !current.isEmpty(), "Missing assignment for segment: %s", segment); + if (metadata.getStatus() == Status.COMMITTING) { + // The accepted uploader may still be building. Preserve its assignment until the authoritative artifact + // exists; followers must never download a COMMITTING segment as though it were DONE. + String owner = recordedLeader != null && current.containsKey(recordedLeader) ? recordedLeader + : current.keySet().stream().sorted().findFirst().orElseThrow(); + targetAssignment.put(segment, new HashMap<>(Map.of(owner, SegmentStateModel.ONLINE))); + } else { + String state = moveConsuming || current.containsValue(SegmentStateModel.CONSUMING) + ? SegmentStateModel.CONSUMING : current.values().iterator().next(); + targetAssignment.put(segment, new HashMap<>(Map.of(leader, state))); + } + } + } + if (!eligibleByPartition.isEmpty()) { + // Local tie retention can leave a constrained placement stuck even when a chain of leader exchanges would + // improve its spread. Include fixed roles in the load, but move only the unpaused consuming partitions above. + Map<Integer, String> currentLeaders = new HashMap<>(ReplicateModeAssignmentUtils.getLeaders(idealState)); + roles.forEach((partition, role) -> currentLeaders.put(partition, role.leader())); + Map<Integer, String> balanced = ReplicateModeLeaderBalancer.balance(currentLeaders, eligibleByPartition); + for (int partition : eligibleByPartition.keySet()) { + ReplicateModePartitionAssignment role = roles.get(partition); + String leader = balanced.get(partition); + if (!leader.equals(role.leader())) { + roles.put(partition, new ReplicateModePartitionAssignment(leader, role.replicas())); + for (SegmentZKMetadata metadata : byPartition.get(partition)) { + if (metadata.getStatus() == Status.IN_PROGRESS) { + targetAssignment.put(metadata.getSegmentName(), + new HashMap<>(Map.of(leader, SegmentStateModel.CONSUMING))); + } Review Comment: Section 2.6.7 accepts that moving a consuming segment may require a replay, but with the REST defaults ([includeConsuming=true](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotTableRestletResource.java#L902-L903), [forceCommit=false](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotTableRestletResource.java#L957-L959)) a rebalance can also move a leader purely for balance here, rewriting the IN_PROGRESS segment to `{newLeader: CONSUMING}`. The new leader then replays the segment from `startOffset`, and the partition's unsealed rows are missing from queries until it catches up. Could you move leadership at a segment boundary instead, for example by sending these partitions through the [existing forceCommit path](https://github.com/apache/pinot/blob/c9dbb605ea5c0c45944813 0fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/TableRebalancer.java#L721-L763) first? ########## pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java: ########## @@ -1889,14 +2050,103 @@ private void updateInstanceStatesForNewConsumingSegment(IdealState idealState, } } // Assign instances to the new segment and add instances as state CONSUMING + SegmentZKMetadata newSegmentZKMetadata = + getSegmentZKMetadata(idealState.getResourceName(), newSegmentName, null); List<String> instancesAssigned = - segmentAssignment.assignSegment(newSegmentName, idealState, instancePartitionsMap); + segmentAssignment.assignConsumingSegment(newSegmentZKMetadata, idealState, instancePartitionsMap); instanceStatesMap.put(newSegmentName, SegmentAssignmentUtils.getInstanceStateMap(instancesAssigned, SegmentStateModel.CONSUMING)); LOGGER.info("Adding new CONSUMING segment: {} to instances: {}", newSegmentName, instancesAssigned); } } + /// Completes only the first fanout, using current native placement rather than the segment's historical replica + /// count. An old serving host is retained until a replacement is ready; the native committing list keeps this + /// intermediate assignment discoverable across Controller restarts. + private boolean expandCompletedReplicateModeSegment(IdealState idealState, SegmentZKMetadata metadata) { + if (!metadata.isReplicateMode() || metadata.getStatus() != Status.DONE) { + return false; + } + String segmentName = metadata.getSegmentName(); + if (!readCommittingSegmentsList(idealState.getResourceName(), _propertyStore).contains(segmentName)) { + return false; + } + Map<String, String> current = idealState.getInstanceStateMap(segmentName); + if (current == null || current.isEmpty() + || !current.values().stream().allMatch(SegmentStateModel.ONLINE::equals)) { + return false; + } + Map<String, String> target = getReplicateModeTargetAssignment(idealState, segmentName); + ExternalView externalView = _helixResourceManager.getTableExternalView(idealState.getResourceName()); Review Comment: This runs inside the IdealState updater, which group commit (on by default) re-applies for every queued commit of the table after a version conflict. Per replicate-mode completion it reads the committing list, table config, CONSUMING instance partitions (every InstanceConfig if none are persisted) and the whole ExternalView, and the metadata reads added at [L2017](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java#L2017) and [L2053](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java#L2053-L2054) run for every table's commits. The commit path already holds the config and instance partitions and has just written both metadata records, and while the segment is on one host, the ExternalView can't change th e result. Could you resolve these before the update and pass them in, keeping only the committing-list read inside since the rebalance fence relies on it? ########## pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/ReplicateModeRecoveryPlanner.java: ########## @@ -0,0 +1,364 @@ +/** + * 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.realtime; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import org.apache.helix.model.ExternalView; +import org.apache.helix.model.IdealState; +import org.apache.pinot.common.assignment.ReplicateModeAssignmentUtils; +import org.apache.pinot.common.metadata.segment.SegmentZKMetadata; +import org.apache.pinot.common.utils.LLCSegmentName; +import org.apache.pinot.controller.ControllerConf; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeCandidateSelector.CandidateContext; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeCandidateSelector.Selection; +import org.apache.pinot.controller.helix.core.realtime.SegmentCompletionFSM.RecoveryStatus; +import org.apache.pinot.spi.config.table.TableType; +import org.apache.pinot.spi.utils.CommonConstants.Helix.StateModel.SegmentStateModel; +import org.apache.pinot.spi.utils.CommonConstants.Segment.Realtime.Status; + + +/// Builds immutable, advisory recovery plans from current partition observations, without executing recovery. +/// The planner does not mutate assignments, metadata, FSMs, or input snapshots. It can be used concurrently with +/// stable caller-provided inputs. A plan is not authorization: execution must revalidate metadata, leadership, +/// placement and completion state, including any old commit that legitimately finishes after planning. +final class ReplicateModeRecoveryPlanner { + private final ReplicateModeCandidateSelector _candidateSelector; + + ReplicateModeRecoveryPlanner(ControllerConf config) { + _candidateSelector = new ReplicateModeCandidateSelector(config); + } + + /// Native failure facts only; absence from ExternalView alone is not a confirmed consumption failure. + enum FailureReason { + INSTANCE_NOT_LIVE, LEADER_OFFLINE, STATE_TRANSITION_ERROR + } + + /// Shares native failure classification between observation and execution. The caller supplies liveness lazily; + /// unsupported assignment states are validated separately by the planner and do not trigger a liveness read. + @Nullable + static FailureReason getFailureReason(Map<String, String> assignment, @Nullable ExternalView externalView, + String segmentName, Supplier<Set<String>> liveInstances) { + Map<String, String> actualStates = externalView != null ? externalView.getStateMap(segmentName) : null; + for (Map.Entry<String, String> instance : assignment.entrySet()) { + String state = instance.getValue(); + if (!SegmentStateModel.CONSUMING.equals(state) && !SegmentStateModel.ONLINE.equals(state) + && !SegmentStateModel.OFFLINE.equals(state)) { + continue; + } + if (!liveInstances.get().contains(instance.getKey())) { + return FailureReason.INSTANCE_NOT_LIVE; + } + if (SegmentStateModel.OFFLINE.equals(state)) { + return FailureReason.LEADER_OFFLINE; + } + if (actualStates != null && SegmentStateModel.ERROR.equals(actualStates.get(instance.getKey()))) { + return FailureReason.STATE_TRANSITION_ERROR; + } + } + return null; + } + + /// Per-segment observations. The timeout must come from native segment-metadata timing, not failure-observation age. + record SegmentSnapshot(SegmentZKMetadata metadata, Map<String, String> assignment, + @Nullable FailureReason failureReason, RecoveryStatus completionStatus, + boolean completionTimedOut, boolean completionPending) { + SegmentSnapshot { + assignment = Map.copyOf(assignment); + } + } + + /// Internal actions only; these are neither new Helix states nor additional persistent replica roles. + enum RecoveryAction { + REASSIGN_CONSUMING, WAIT_FOR_COMPLETION, REPAIR_COMPLETION, REINGEST_COMMITTING, BLOCKED + } + + /// Reasons why a recovery action cannot currently be planned safely. + enum BlockedReason { + UNSUPPORTED_TABLE, INVALID_ASSIGNMENT, INVALID_ROLE_METADATA, SUPERSEDED_SEGMENT, + MULTIPLE_CONSUMING_SEGMENTS, DUPLICATE_SEGMENT_SEQUENCE, INVALID_OFFSETS, + COMMITTING_ARTIFACT_PRESENT, + NO_ELIGIBLE_REPLICA + } + + /// Immutable segment action retaining its original identity and range. A null target means no host action is ready. + record SegmentRecoveryPlan(String segmentName, Status status, RecoveryAction action, + @Nullable String targetServer, @Nullable BlockedReason blockedReason, + @Nullable String startOffset, @Nullable String endOffset, + RecoveryStatus completionStatus, boolean completionTimedOut) { + } + + /// Immutable partition plan; candidate placement is recorded for review and is never rewritten by planning. + /// Eligible servers are the union across pending host actions; rejected servers cannot run any of those actions. + /// Each segment retains its own target, independently of the targets chosen for other fixed recovery ranges. + record PartitionRecoveryPlan(int partitionId, @Nullable String expectedLeader, List<String> replicaCandidates, + List<String> eligibleServers, Map<String, String> rejectedServers, + Map<String, SegmentRecoveryPlan> segments, long observedTimeMs) { + PartitionRecoveryPlan { + replicaCandidates = List.copyOf(replicaCandidates); + eligibleServers = List.copyOf(eligibleServers); + rejectedServers = Map.copyOf(rejectedServers); + segments = Map.copyOf(segments); + } + } + + Map<Integer, PartitionRecoveryPlan> plan(CandidateContext context, Collection<SegmentSnapshot> snapshots, + @Nullable ExternalView externalView, long nowMs) { + IdealState idealState = context.idealState(); + if (!idealState.isEnabled() || PinotLLCRealtimeSegmentManager.isTablePaused(idealState)) { + return Map.of(); + } + Map<Integer, List<SegmentSnapshot>> byPartition = new TreeMap<>(); + for (SegmentSnapshot snapshot : snapshots) { + LLCSegmentName name = LLCSegmentName.of(snapshot.metadata().getSegmentName()); + if (name != null && snapshot.metadata().isReplicateMode() + && !PinotLLCRealtimeSegmentManager.isTopicPaused(idealState, name.getSegmentName())) { + byPartition.computeIfAbsent(name.getPartitionGroupId(), ignored -> new ArrayList<>()).add(snapshot); + } + } + + Map<String, Integer> leaderCounts = new HashMap<>(); + ReplicateModeAssignmentUtils.getLeaders(idealState).values() + .forEach(server -> leaderCounts.merge(server, 1, Integer::sum)); + Map<Integer, PartitionRecoveryPlan> plans = new TreeMap<>(); + Map<Integer, PartitionProgress> progress = getPartitionProgress(idealState, byPartition); + for (Map.Entry<Integer, List<SegmentSnapshot>> entry : byPartition.entrySet()) { + int partitionId = entry.getKey(); + String leader = ReplicateModeAssignmentUtils.getLeader(idealState, partitionId); + List<String> replicas = ReplicateModeAssignmentUtils.getReplicas(idealState, partitionId); + Map<String, SegmentRecoveryPlan> actions = new TreeMap<>(); + Map<String, Set<String>> excludedServersBySegment = new HashMap<>(); + for (SegmentSnapshot snapshot : entry.getValue()) { + SegmentRecoveryPlan action = classify(context, leader, replicas, snapshot, progress.get(partitionId)); + if (action == null) { + continue; + } + actions.put(action.segmentName(), action); + if (needsTarget(action.action())) { + excludedServersBySegment.put(action.segmentName(), + getExcludedServers(snapshot, action.action(), externalView)); + } + } + if (actions.isEmpty()) { + continue; + } + Set<String> eligibleServers = new TreeSet<>(); + Map<String, List<String>> rejectionReasons = new TreeMap<>(); + boolean multipleHostActions = excludedServersBySegment.size() > 1; + String consumingTarget = null; + for (Map.Entry<String, SegmentRecoveryPlan> actionEntry : actions.entrySet()) { + SegmentRecoveryPlan action = actionEntry.getValue(); + if (!needsTarget(action.action())) { + continue; + } + // Fixed ranges can require different workers, and one range's failure must not exclude another's worker. + Selection selection = _candidateSelector.select(context, partitionId, List.of(action.segmentName()), + excludedServersBySegment.get(action.segmentName()), leaderCounts, leader, nowMs); + eligibleServers.addAll(selection.eligibleServers()); + selection.rejectedServers().forEach((server, reason) -> rejectionReasons + .computeIfAbsent(server, ignored -> new ArrayList<>()) + .add(multipleHostActions ? action.segmentName() + ": " + reason : reason)); + String target = selection.selectedServer(); + if (target == null) { + actionEntry.setValue(withTarget(action, RecoveryAction.BLOCKED, null, BlockedReason.NO_ELIGIBLE_REPLICA)); + } else { + if (action.action() == RecoveryAction.REASSIGN_CONSUMING && !target.equals(leader)) { + consumingTarget = target; + } + actionEntry.setValue(withTarget(action, action.action(), target, null)); + } + } + if (consumingTarget != null) { + // Virtual counts balance this pass without changing the persisted role of any partition. + // Update after selecting every range so a consuming handoff does not affect its sibling replay choices. + leaderCounts.computeIfPresent(leader, (server, count) -> Math.max(0, count - 1)); + leaderCounts.merge(consumingTarget, 1, Integer::sum); + } + Map<String, String> rejectedServers = new TreeMap<>(); + rejectionReasons.forEach((server, reasons) -> { + if (!eligibleServers.contains(server)) { + rejectedServers.put(server, String.join("; ", reasons)); + } + }); + plans.put(partitionId, new PartitionRecoveryPlan(partitionId, leader, replicas, List.copyOf(eligibleServers), + rejectedServers, actions, nowMs)); + } + return Map.copyOf(plans); + } + + private static Set<String> getExcludedServers(SegmentSnapshot snapshot, RecoveryAction action, + @Nullable ExternalView externalView) { + Set<String> excluded = new HashSet<>(); + if (snapshot.failureReason() != null && (snapshot.metadata().getStatus() != Status.COMMITTING + || snapshot.failureReason() == FailureReason.INSTANCE_NOT_LIVE)) { + excluded.addAll(snapshot.assignment().keySet()); + } + if (externalView != null && action != RecoveryAction.REINGEST_COMMITTING) { + Map<String, String> actualStates = externalView.getStateMap(snapshot.metadata().getSegmentName()); + if (actualStates != null) { + actualStates.forEach((server, state) -> { + if (SegmentStateModel.ERROR.equals(state)) { + excluded.add(server); + } + }); + } + } + return excluded; + } + + @Nullable + private static SegmentRecoveryPlan classify(CandidateContext context, @Nullable String leader, + List<String> replicas, SegmentSnapshot snapshot, PartitionProgress progress) { + SegmentZKMetadata metadata = snapshot.metadata(); + String segment = metadata.getSegmentName(); + Status status = metadata.getStatus(); + if (context.tableConfig().getTableType() != TableType.REALTIME || context.tableConfig().isUpsertEnabled() + || context.tableConfig().isDedupEnabled()) { + return action(snapshot, RecoveryAction.BLOCKED, BlockedReason.UNSUPPORTED_TABLE); + } + if (leader == null || replicas.isEmpty() || !replicas.contains(leader) + || new HashSet<>(replicas).size() != replicas.size()) { + return action(snapshot, RecoveryAction.BLOCKED, BlockedReason.INVALID_ROLE_METADATA); + } + if (status == Status.DONE) { + boolean consuming = snapshot.assignment().containsValue(SegmentStateModel.CONSUMING); + if (!snapshot.completionPending() && !consuming) { + // Completed historical placement belongs to rebalance, even when its creation-time RF differs. + return null; + } + if (!consuming) { + // The durable completion entry, not the historical RF, identifies an unfinished fanout or handoff. + return action(snapshot, RecoveryAction.REPAIR_COMPLETION, null); Review Comment: Every tracked DONE segment without a CONSUMING entry gets `REPAIR_COMPLETION` here, whether or not the repair can make progress. 2.4 says tracking ends once the target assignment is durable, but some entries never get there, like a DONE entry left OFFLINE after a late commit, or a fanout away from an old leader whose new hosts never load. Those records stay until a rebalance runs or the segment is deleted. Each attempt reruns the repair plus a whole-table `ensureAllPartitionsConsuming` with its stream metadata fetch ([executor](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/ReplicateModeRecoveryExecutor.java#L129-L137)), and the retries settle at one run per `retryMaxDelayMs`, 5 minutes by default. Could you give a pending fanout a deadline, after which it is planned as BLOCKED with its own reason? ########## pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/ReplicateModeRecoveryPlanner.java: ########## @@ -0,0 +1,364 @@ +/** + * 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.realtime; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import org.apache.helix.model.ExternalView; +import org.apache.helix.model.IdealState; +import org.apache.pinot.common.assignment.ReplicateModeAssignmentUtils; +import org.apache.pinot.common.metadata.segment.SegmentZKMetadata; +import org.apache.pinot.common.utils.LLCSegmentName; +import org.apache.pinot.controller.ControllerConf; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeCandidateSelector.CandidateContext; +import org.apache.pinot.controller.helix.core.realtime.ReplicateModeCandidateSelector.Selection; +import org.apache.pinot.controller.helix.core.realtime.SegmentCompletionFSM.RecoveryStatus; +import org.apache.pinot.spi.config.table.TableType; +import org.apache.pinot.spi.utils.CommonConstants.Helix.StateModel.SegmentStateModel; +import org.apache.pinot.spi.utils.CommonConstants.Segment.Realtime.Status; + + +/// Builds immutable, advisory recovery plans from current partition observations, without executing recovery. +/// The planner does not mutate assignments, metadata, FSMs, or input snapshots. It can be used concurrently with +/// stable caller-provided inputs. A plan is not authorization: execution must revalidate metadata, leadership, +/// placement and completion state, including any old commit that legitimately finishes after planning. +final class ReplicateModeRecoveryPlanner { + private final ReplicateModeCandidateSelector _candidateSelector; + + ReplicateModeRecoveryPlanner(ControllerConf config) { + _candidateSelector = new ReplicateModeCandidateSelector(config); + } + + /// Native failure facts only; absence from ExternalView alone is not a confirmed consumption failure. + enum FailureReason { + INSTANCE_NOT_LIVE, LEADER_OFFLINE, STATE_TRANSITION_ERROR + } + + /// Shares native failure classification between observation and execution. The caller supplies liveness lazily; + /// unsupported assignment states are validated separately by the planner and do not trigger a liveness read. + @Nullable + static FailureReason getFailureReason(Map<String, String> assignment, @Nullable ExternalView externalView, + String segmentName, Supplier<Set<String>> liveInstances) { + Map<String, String> actualStates = externalView != null ? externalView.getStateMap(segmentName) : null; + for (Map.Entry<String, String> instance : assignment.entrySet()) { + String state = instance.getValue(); + if (!SegmentStateModel.CONSUMING.equals(state) && !SegmentStateModel.ONLINE.equals(state) + && !SegmentStateModel.OFFLINE.equals(state)) { + continue; + } + if (!liveInstances.get().contains(instance.getKey())) { + return FailureReason.INSTANCE_NOT_LIVE; + } + if (SegmentStateModel.OFFLINE.equals(state)) { + return FailureReason.LEADER_OFFLINE; + } + if (actualStates != null && SegmentStateModel.ERROR.equals(actualStates.get(instance.getKey()))) { + return FailureReason.STATE_TRANSITION_ERROR; + } Review Comment: A leader that an operator disables in Helix slips past these checks. It stays in LiveInstances and its IdealState entry stays `CONSUMING`, while Helix moves the replica to OFFLINE and the server offloads the consumer without reporting a stop, so the partition stops ingesting until someone re-enables the instance or rebalances. I don't think this is the unreported stall 2.6.2 leaves out of scope, since the disabled flag sits in the instance config the selector already reads. Could you treat an incumbent as failed when the disabled checks in [`getRejection`](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/ReplicateModeCandidateSelector.java#L156-L193) would reject it as a target? ########## pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java: ########## @@ -216,7 +222,24 @@ public StatelessRealtimeSegmentWriter(SegmentZKMetadata segmentZKMetadata, Index _realtimeSegment = new MutableSegmentImpl(realtimeSegmentConfigBuilder.build(), null); - _transformPipeline = new TransformPipeline(_tableConfig, _schema); + _recordProcessor = new RealtimeIngestionRecordProcessor(new TransformPipeline(_tableConfig, _schema), + _realtimeSegment, RealtimeIngestionRecordProcessor.parseStopOnDecodeErrorConfig(_streamConfig, _logger), + new RealtimeIngestionRecordProcessor.Listener() { + @Override + public void onDecodeError(Exception exception, StreamMessageMetadata metadata, boolean fatal) { + _logger.warn("Failed to decode message at offset {}", metadata.getOffset(), exception); + } + + @Override + public void onTransformError(GenericRow row, StreamMessageMetadata metadata, Exception exception) { + _logger.warn("Failed to transform record at offset {}", metadata.getOffset(), exception); + } Review Comment: Section 2.6.5 describes these replay semantics for replicate mode, but the record processor, `setIngestionSemantics` and per-partition stream config aren't gated on it, and native pauseless ERROR repair also re-ingests through this writer ([L3578-L3611](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java#L3578-L3611)). So for any pauseless table that falls back to re-ingestion, a row whose transform or `index()` throws is now skipped with a WARN instead of failing the job, a decode error fails it when `stopOnDecodeError=true`, and table-level null handling and aggregation now apply. Most of that is a real fix, but skipped rows aren't counted and the new replay tests only use replicate-mode metadata. Every realtime table's live consumer now handles rows through the same processor too. Could you split these shared changes into their own PR, so they're reviewed and tested as native ingestion changes? ########## pinot-broker/src/main/java/org/apache/pinot/broker/routing/instanceselector/BaseInstanceSelector.java: ########## @@ -385,24 +404,70 @@ Object2LongOpenHashMap<String> getNewSegmentCreationTimeMapFromExistingStates(Id _newSegmentExpirationTimeInSeconds * 1000)) { creationTimeMs = previousCreationTimeMs; } + } else if (_pendingSegmentMetadata.containsKey(segment)) { + creationTimeMs = _pendingSegmentMetadata.getLong(segment); } else if (segmentGroups._segmentToGroupId.getInt(segment) == SegmentStates.UNKNOWN_SEGMENT) { // This is the first time we see this segment, use the current time as the creation time creationTimeMs = currentTimeMs; } // For recently created segment, check if it is qualified as new segment - if (creationTimeMs > 0) { + boolean potentialNew = false; + if (InstanceSelector.isNewSegment(creationTimeMs, currentTimeMs, _newSegmentExpirationTimeInSeconds * 1000)) { assert idealStateAssignment.containsKey(segment); if (isPotentialNewSegment(idealStateAssignment.get(segment), externalViewAssignment.get(segment))) { - newSegmentCreationTimeMap.put(segment, creationTimeMs); + potentialNew = true; + if (isRealtimeLlcSegment(segment) && (previousCreationTimeMs == 0 + || _pendingSegmentMetadata.containsKey(segment))) { + segmentsToResolve.put(segment, creationTimeMs); + } else { + newSegmentCreationTimeMap.put(segment, creationTimeMs); + } } } + if (!potentialNew) { + _pendingSegmentMetadata.removeLong(segment); + } } + resolveNewSegmentModes(segmentsToResolve, newSegmentCreationTimeMap); LOGGER.info(NEW_SEGMENTS_MARKER, "Got {} new segments: {} for table: {} by processing existing states, current time: {}", newSegmentCreationTimeMap.size(), newSegmentCreationTimeMap, _tableNameWithType, currentTimeMs); return newSegmentCreationTimeMap; } + private boolean isRealtimeLlcSegment(String segment) { + return TableNameBuilder.isRealtimeTableResource(_tableNameWithType) && LLCSegmentName.of(segment) != null; + } + + /// Resolves mode only for first-seen or unresolved realtime segments, not every historical assignment. Explicit + /// false retains native optional routing; true uses ordinary IS/EV candidates. Missing metadata remains ready-only + /// and is retried by later native refreshes, even if no assignment version changes in the meantime. + private void resolveNewSegmentModes(Object2LongOpenHashMap<String> segmentsToResolve, + Object2LongOpenHashMap<String> newSegmentCreationTimeMap) { + if (segmentsToResolve.isEmpty()) { + return; + } + _pendingSegmentMetadata.putAll(segmentsToResolve); + List<String> segmentNames = new ArrayList<>(segmentsToResolve.keySet()); + try { + List<SegmentZKMetadata> metadataList = + ZKMetadataProvider.getSegmentsZKMetadata(_propertyStore, _tableNameWithType, segmentNames, null); + for (SegmentZKMetadata metadata : metadataList) { + if (metadata == null || !segmentsToResolve.containsKey(metadata.getSegmentName())) { + continue; + } + String segment = metadata.getSegmentName(); + _pendingSegmentMetadata.removeLong(segment); + if (!metadata.isReplicateMode()) { + newSegmentCreationTimeMap.put(segment, segmentsToResolve.getLong(segment)); + } + } + } catch (RuntimeException e) { + LOGGER.warn("Failed to resolve new segment modes for table: {}; keeping only ready routing candidates", + _tableNameWithType, e); Review Comment: This path runs for every realtime table, so tables that never enabled the mode now pay a ZooKeeper read per new, not-yet-converged LLC segment, and if the read fails or returns no record, the segment is routed to ready replicas only. That's the ready-only fallback Section 2.5 describes for unresolved metadata, but for an ordinary table it can turn a new consuming segment from optional into unavailable until a later refresh resolves it. In the meantime the pending entry [forces a routing rebuild](https://github.com/apache/pinot/blob/c9dbb605ea5c0c459448130fe69f35c106f9519a/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java#L425-L430) on every assignment callback. Could you skip the lookup and keep the native classification when the IdealState passed to `onAssignmentChange` has no `replicateMode.leader.*` fields? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
