xiangfu0 commented on code in PR #20220:
URL: https://github.com/apache/pinot/pull/20220#discussion_r4625750538
##########
pinot-server/src/main/java/org/apache/pinot/server/api/resources/ReingestionResource.java:
##########
@@ -279,6 +321,19 @@ private void doReingestSegment(String realtimeTableName,
String segmentName)
File segmentTarFile = writer.buildSegment();
+ // A queued/running attempt must not publish into a replaced range,
removed table, or changed ingestion schema.
+ SegmentZKMetadata latestMetadata =
tableDataManager.fetchZKMetadataNullable(segmentName);
+ if (!isReplayStillCurrent(segmentZKMetadata, latestMetadata) ||
tableDataManager.isShutDown()) {
+ LOGGER.info("Skipping obsolete re-ingestion publication for segment:
{}", segmentName);
+ return;
+ }
+ if (segmentZKMetadata.isReplicateMode()) {
+ IndexLoadingConfig latestConfig =
tableDataManager.fetchIndexLoadingConfig();
+
Preconditions.checkState(indexLoadingConfig.getTableConfig().equals(latestConfig.getTableConfig())
Review Comment:
This comparison catches a config change during replay. If the filter changes
after A indexed the rows and before B starts replay, both reads here see the
new filter. B can then publish fewer rows at the original offsets. Can we
persist the effective schema and ingestion-config version at segment creation
and use it for replay, or report the mismatch before publishing? A filter
change before takeover would exercise this.
##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/SegmentCompletionManager.java:
##########
@@ -156,168 +181,311 @@ private SegmentCompletionFSM createFsm(LLCSegmentName
llcSegmentName, String msg
SegmentCompletionFSM fsm =
SegmentCompletionFSMFactory.createFSM(factoryName, this,
_segmentManager, llcSegmentName, segmentMetadata);
fsm.transitionToInitialState(msgType);
+ if (segmentMetadata.isReplicateMode()) {
+ _replicateModeFsms.put(fsm, true);
+ }
LOGGER.info("Created FSM {}", fsm);
return fsm;
}
- /// This method is to be called when a server calls in with the
segmentConsumed() API, reporting an offset in the
- /// stream
- /// that it currently has (i.e. next offset that it will consume, if it
continues to consume).
- public SegmentCompletionProtocol.Response
segmentConsumed(SegmentCompletionProtocol.Request.Params reqParams) {
- final String segmentNameStr = reqParams.getSegmentName();
- final LLCSegmentName segmentName = new LLCSegmentName(segmentNameStr);
- final String tableName = segmentName.getTableName();
- if (!isLeader(tableName) || !_helixManager.isConnected()) {
- return SegmentCompletionProtocol.RESP_NOT_LEADER;
- }
- final String instanceId = reqParams.getInstanceId();
- final String stopReason = reqParams.getReason();
-
- SegmentCompletionProtocol.Response response =
SegmentCompletionProtocol.RESP_FAILED;
- SegmentCompletionFSM fsm = null;
+ /// Serializes local replicate-mode admission and assignment changes.
Recovery performs its final validation and
+ /// CAS inside this operation. Locks are bounded and reentrant; accepted
commitEnd I/O runs outside the gate because
+ /// that exact attempt may legitimately finish after reassignment. This does
not replace ZooKeeper version checks.
+ public <T> T withSegmentCompletionLock(String segmentName, Supplier<T>
operation) {
+ Lock lock = _segmentCompletionLocks.get(segmentName);
+ lock.lock();
try {
- fsm = lookupOrCreateFsm(segmentName,
SegmentCompletionProtocol.MSG_TYPE_CONSUMED);
- StreamPartitionMsgOffset offset = parseOffset(fsm, segmentName,
reqParams.getStreamPartitionMsgOffset());
- response = fsm.segmentConsumed(instanceId, offset, stopReason);
- } catch (Exception e) {
- LOGGER.error("Caught exception in segmentConsumed for segment {}",
segmentNameStr, e);
- }
- if (fsm != null && fsm.isDone()) {
- LOGGER.info("Removing FSM (if present):{}", fsm.toString());
- _fsmMap.remove(segmentNameStr);
+ return operation.get();
+ } finally {
+ lock.unlock();
}
- return response;
}
- /// This method is to be called when a server calls in with the
segmentCommit() API. The server sends in the segment
- /// along with the API, but it is the caller's responsibility to save the
segment after this call (and before the
- /// segmentCommitEnd() call).
- ///
- /// If successful, this method will return Response.COMMIT_CONTINUE, in
which case, the caller should save the
- /// incoming segment and then call segmentCommitEnd().
- ///
- /// Otherwise, this method will return a protocol response to be returned to
the client right away (without saving the
- /// incoming segment).
- public SegmentCompletionProtocol.Response segmentCommitStart(
- final SegmentCompletionProtocol.Request.Params reqParams) {
- final String segmentNameStr = reqParams.getSegmentName();
- final LLCSegmentName segmentName = new LLCSegmentName(segmentNameStr);
- final String tableName = segmentName.getTableName();
- if (!isLeader(tableName) || !_helixManager.isConnected()) {
+ public SegmentCompletionProtocol.Response
segmentConsumed(SegmentCompletionProtocol.Request.Params params) {
+ LLCSegmentName name = new LLCSegmentName(params.getSegmentName());
+ return processRequest(params, RequestKind.CONSUMED, fsm ->
fsm.segmentConsumed(params.getInstanceId(),
+ parseOffset(fsm, name, params.getStreamPartitionMsgOffset()),
params.getReason()));
+ }
+
+ public SegmentCompletionProtocol.Response
segmentCommitStart(SegmentCompletionProtocol.Request.Params params) {
+ return processRequest(params, RequestKind.COMMIT_START, fsm ->
fsm.segmentCommitStart(params));
+ }
+
+ public SegmentCompletionProtocol.Response
extendBuildTime(SegmentCompletionProtocol.Request.Params params) {
+ LLCSegmentName name = new LLCSegmentName(params.getSegmentName());
+ return processRequest(params, RequestKind.EXTEND, fsm ->
fsm.extendBuildTime(params.getInstanceId(),
+ parseOffset(fsm, name, params.getStreamPartitionMsgOffset()),
params.getExtraTimeSec()));
+ }
+
+ public SegmentCompletionProtocol.Response
reduceSegmentSizeAndReset(SegmentCompletionProtocol.Request.Params params) {
+ return processRequest(params, RequestKind.RESET, fsm -> {
+ if (fsm != null && fsm.isImmutableSegmentCreated()) {
+ LOGGER.warn("Segment {} cannot build is a false alert",
params.getSegmentName());
+ return SegmentCompletionProtocol.RESP_DISCARD;
+ }
+ _segmentManager.reduceSegmentSizeAndReset(new
LLCSegmentName(params.getSegmentName()), params.getNumRows());
+ removeFsm(params.getSegmentName(), fsm);
+ return SegmentCompletionProtocol.RESP_PROCESSED;
+ });
+ }
+
+ public SegmentCompletionProtocol.Response
segmentStoppedConsuming(SegmentCompletionProtocol.Request.Params params) {
+ LLCSegmentName name = new LLCSegmentName(params.getSegmentName());
+ return processRequest(params, RequestKind.STOPPED, fsm ->
fsm.stoppedConsuming(params.getInstanceId(),
+ parseOffset(fsm, name, params.getStreamPartitionMsgOffset()),
params.getReason()));
+ }
+
+ /// Completes an existing accepted attempt. A stale server cannot create an
FSM to regain commit authorization.
+ /// Once metadata is DONE, a matching retry succeeds without republishing
files or changing the selected artifact.
+ public SegmentCompletionProtocol.Response
segmentCommitEnd(SegmentCompletionProtocol.Request.Params params,
+ CommittingSegmentDescriptor descriptor) {
+ LLCSegmentName name = new LLCSegmentName(params.getSegmentName());
+ if (!isLeader(name.getTableName()) || !_helixManager.isConnected()) {
return SegmentCompletionProtocol.RESP_NOT_LEADER;
}
- SegmentCompletionFSM fsm = null;
- SegmentCompletionProtocol.Response response =
SegmentCompletionProtocol.RESP_FAILED;
try {
- fsm = lookupOrCreateFsm(segmentName,
SegmentCompletionProtocol.MSG_TYPE_COMMIT);
- response = fsm.segmentCommitStart(reqParams);
+ SegmentCompletionFSM existing = _fsmMap.get(name.getSegmentName());
+ SegmentZKMetadata metadata = existing == null ? getSegmentMetadata(name)
: null;
+ if (!isReplicateMode(existing, metadata)) {
+ return invokeFsm(name, RequestKind.COMMIT_END, metadata, fsm ->
fsm.segmentCommitEnd(params, descriptor));
+ }
+ CommitEndAdmission admission =
withSegmentCompletionLock(name.getSegmentName(), () -> {
+ if (!isLeader(name.getTableName()) || !_helixManager.isConnected()) {
+ return new CommitEndAdmission(null,
SegmentCompletionProtocol.RESP_NOT_LEADER);
+ }
+ SegmentZKMetadata currentMetadata = getSegmentMetadata(name);
+ if (currentMetadata == null || !currentMetadata.isReplicateMode()) {
+ return new CommitEndAdmission(null,
SegmentCompletionProtocol.RESP_FAILED);
+ }
+ if (currentMetadata.getStatus() == Status.DONE) {
+ return new CommitEndAdmission(null,
+ completedResponse(name, currentMetadata, params,
RequestKind.COMMIT_END, descriptor));
+ }
+ SegmentCompletionFSM fsm = _fsmMap.get(name.getSegmentName());
+ if (fsm == null || !fsm.isAcceptedCommitter(params.getInstanceId(),
params.getStreamPartitionMsgOffset())) {
+ return new CommitEndAdmission(null,
SegmentCompletionProtocol.RESP_FAILED);
+ }
+ return new CommitEndAdmission(fsm, null);
+ });
+ if (admission.response() != null) {
+ return admission.response();
+ }
+ SegmentCompletionFSM fsm = admission.fsm();
+ try {
+ return fsm.segmentCommitEnd(params, descriptor);
+ } finally {
+ if (fsm.isDone()) {
+ removeFsm(name.getSegmentName(), fsm);
+ }
+ }
} catch (Exception e) {
- LOGGER.error("Caught exception in segmentCommitStart for segment {}",
segmentNameStr, e);
- }
- if (fsm != null && fsm.isDone()) {
- LOGGER.info("Removing FSM (if present):{}", fsm.toString());
- _fsmMap.remove(segmentNameStr);
+ LOGGER.error("Caught exception in segmentCommitEnd for segment {}",
name.getSegmentName(), e);
+ return SegmentCompletionProtocol.RESP_FAILED;
}
- return response;
}
- public SegmentCompletionProtocol.Response extendBuildTime(final
SegmentCompletionProtocol.Request.Params reqParams) {
- final String segmentNameStr = reqParams.getSegmentName();
- final LLCSegmentName segmentName = new LLCSegmentName(segmentNameStr);
- final String tableName = segmentName.getTableName();
- if (!isLeader(tableName) || !_helixManager.isConnected()) {
+ private SegmentCompletionProtocol.Response
processRequest(SegmentCompletionProtocol.Request.Params params,
+ RequestKind kind, Function<SegmentCompletionFSM,
SegmentCompletionProtocol.Response> operation) {
+ LLCSegmentName name = new LLCSegmentName(params.getSegmentName());
+ // Preserve the ordinary reset endpoint's existing behavior;
replicate-mode resets are checked inside the gate.
+ if (kind != RequestKind.RESET && (!isLeader(name.getTableName()) ||
!_helixManager.isConnected())) {
return SegmentCompletionProtocol.RESP_NOT_LEADER;
}
- final String instanceId = reqParams.getInstanceId();
- final int extTimeSec = reqParams.getExtraTimeSec();
- SegmentCompletionFSM fsm = null;
- SegmentCompletionProtocol.Response response =
SegmentCompletionProtocol.RESP_FAILED;
try {
- fsm = lookupOrCreateFsm(segmentName,
SegmentCompletionProtocol.MSG_TYPE_COMMIT);
- StreamPartitionMsgOffset offset = parseOffset(fsm, segmentName,
reqParams.getStreamPartitionMsgOffset());
- response = fsm.extendBuildTime(instanceId, offset, extTimeSec);
+ SegmentCompletionFSM existing = _fsmMap.get(name.getSegmentName());
+ SegmentZKMetadata metadata = existing == null ? getSegmentMetadata(name)
: null;
+ if (!isReplicateMode(existing, metadata)) {
+ return invokeFsm(name, kind, metadata, operation);
+ }
+ return withFsmAdmissionLock(name.getSegmentName(), () -> {
+ if (!isLeader(name.getTableName()) || !_helixManager.isConnected()) {
+ return SegmentCompletionProtocol.RESP_NOT_LEADER;
+ }
+ SegmentZKMetadata currentMetadata = getSegmentMetadata(name);
+ if (currentMetadata == null || !currentMetadata.isReplicateMode()) {
+ return SegmentCompletionProtocol.RESP_FAILED;
+ }
+ if (currentMetadata.getStatus() == Status.DONE) {
+ return completedResponse(name, currentMetadata, params, kind, null);
+ }
+ SegmentCompletionFSM fsm = _fsmMap.get(name.getSegmentName());
+ if (!isCurrentMember(name, currentMetadata, params, kind, fsm)) {
+ if (kind == RequestKind.STOPPED) {
+ return SegmentCompletionProtocol.RESP_PROCESSED;
+ }
+ return kind == RequestKind.CONSUMED || kind == RequestKind.RESET
+ ? SegmentCompletionProtocol.RESP_DISCARD :
SegmentCompletionProtocol.RESP_FAILED;
+ }
+ return invokeFsm(name, kind, currentMetadata, operation);
+ });
} catch (Exception e) {
- LOGGER.error("Caught exception in extendBuildTime for segment {}",
segmentNameStr, e);
+ LOGGER.error("Caught exception processing {} for segment {}", kind,
name.getSegmentName(), e);
+ return SegmentCompletionProtocol.RESP_FAILED;
}
- if (fsm != null && fsm.isDone()) {
- LOGGER.info("Removing FSM (if present):{}", fsm.toString());
- _fsmMap.remove(segmentNameStr);
+ }
+
+ /// Never hold the assignment gate while waiting for an existing FSM's
commit monitor. Once both are held, verify
+ /// that cleanup did not replace that FSM while we waited. Recovery uses
only the gate and nonblocking observations.
+ private SegmentCompletionProtocol.Response withFsmAdmissionLock(String
segmentName,
+ Supplier<SegmentCompletionProtocol.Response> operation) {
+ while (true) {
+ SegmentCompletionFSM expected = _fsmMap.get(segmentName);
+ SegmentCompletionProtocol.Response response;
+ if (expected == null) {
+ response = withSegmentCompletionLock(segmentName,
+ () -> _fsmMap.get(segmentName) == null ? operation.get() : null);
+ } else {
+ synchronized (expected) {
+ response = withSegmentCompletionLock(segmentName,
+ () -> _fsmMap.get(segmentName) == expected ? operation.get() :
null);
+ }
+ }
+ if (response != null) {
+ return response;
+ }
}
- return response;
}
- public SegmentCompletionProtocol.Response reduceSegmentSizeAndReset(
- SegmentCompletionProtocol.Request.Params reqParams) {
- String segmentName = reqParams.getSegmentName();
- SegmentCompletionFSM fsm = _fsmMap.get(segmentName);
- if (fsm != null && fsm.isImmutableSegmentCreated()) {
- // In this case, other replica already starts committing the segment. It
is a false alert.
- LOGGER.warn("Segment {} cannot build is a false alert", segmentName);
- return SegmentCompletionProtocol.RESP_DISCARD;
+ private boolean isCurrentMember(LLCSegmentName name, SegmentZKMetadata
metadata,
+ SegmentCompletionProtocol.Request.Params params, RequestKind kind,
@Nullable SegmentCompletionFSM fsm) {
+ IdealState idealState =
+
_segmentManager.getIdealState(TableNameBuilder.REALTIME.tableNameWithType(name.getTableName()));
+ if (idealState == null) {
+ return false;
+ }
+ Map<String, String> assignment =
idealState.getInstanceStateMap(name.getSegmentName());
+ if (assignment == null || assignment.size() != 1) {
+ return false;
+ }
+ String state = assignment.get(params.getInstanceId());
+ if (metadata.getStatus() == Status.IN_PROGRESS) {
+ return SegmentStateModel.CONSUMING.equals(state) &&
params.getInstanceId().equals(
Review Comment:
The same server can own this unfinished segment twice. After A → B → A, a
delayed `stoppedConsuming` from A’s first tenure passes this check and marks
the current A OFFLINE. Can we validate the assignment generation when applying
state-changing reports? A delayed stop after the second handoff should leave A
consuming. An already-admitted commit can still finish through its existing
path.
##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java:
##########
@@ -595,18 +636,34 @@ public void commitSegmentFile(String realtimeTableName,
CommittingSegmentDescrip
// Copy the segment file to the controller
String segmentLocation = committingSegmentDescriptor.getSegmentLocation();
Preconditions.checkArgument(segmentLocation != null, "Segment location
must be provided");
+ boolean replicateMode = getSegmentZKMetadata(realtimeTableName,
segmentName).isReplicateMode();
if (isPeerUrl(segmentLocation)) {
+ Preconditions.checkState(!replicateMode,
+ "Replicate mode requires a durable artifact before DONE; a sole
consuming peer is not sufficient");
LOGGER.info("No moving needed for segment on peer servers: {}",
segmentLocation);
return;
}
URI tableDirURI = URIUtils.getUri(_controllerConf.getDataDir(),
rawTableName);
PinotFS pinotFS = PinotFSFactory.create(tableDirURI.getScheme());
- String uriToMoveTo = moveSegmentFile(rawTableName, segmentName,
segmentLocation, pinotFS);
- moveMetadataTarFile(realtimeTableName, rawTableName, segmentName,
+ // A commit admitted by the old leader can finish after a handoff,
including on another Controller.
+ // Publish immutable attempt files; the version-checked metadata write
selects the winning file.
+ String artifactName = segmentName;
+ String uriToMoveTo;
+ if (replicateMode) {
+ artifactName = segmentName + ".commit." + UUID.randomUUID();
Review Comment:
The chosen object now has an attempt UUID, but
`SegmentAdminClient.downloadSegment(table, segmentName)` calls `GET
/segments/{table}/{segmentName}` and the controller looks up that literal
filename. On a newly committed segment the client can get 404 while followers
load it through `downloadUrl`. Can the logical-name endpoint resolve the
winning owned artifact from segment metadata? Please cover both a normal commit
and a recovered segment.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java:
##########
@@ -290,6 +279,15 @@ private class PartitionConsumer implements Runnable {
@Override
public void run() {
try {
+ if (_strictRecovery) {
+ Preconditions.checkState(_partitionMetadataProvider != null,
+ "Cannot validate retained replay interval for segment: %s",
_segmentName);
+ StreamPartitionMsgOffset smallestOffset =
_partitionMetadataProvider.fetchStreamPartitionOffset(
+ OffsetCriteria.SMALLEST_OFFSET_CRITERIA, _fetchTimeoutMs);
+ Preconditions.checkState(smallestOffset.compareTo(_startOffset) <= 0,
Review Comment:
A compacted Kafka topic can pass the earliest-offset check after it has
removed a record inside the range. If A indexed two events with the same key, B
can reach the saved end with one fewer row. Can v1 require an uncompacted
replay window and enforce or explicitly validate that prerequisite when
enabling the mode? A test should compare recovered rows as well as the
endpoints.
##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/ReplicateModeRecoveryExecutor.java:
##########
@@ -0,0 +1,289 @@
+/**
+ * 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.time.Clock;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BooleanSupplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+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.ControllerMeter;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.common.utils.helix.HelixHelper;
+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.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.RecoveryAction;
+import
org.apache.pinot.controller.helix.core.realtime.ReplicateModeRecoveryPlanner.SegmentRecoveryPlan;
+import
org.apache.pinot.controller.helix.core.realtime.ReplicateModeRecoveryPlanner.SegmentSnapshot;
+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.IngestionConfigUtils;
+import org.apache.zookeeper.data.Stat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/// Executes bounded recovery work after revalidating each plan against
current metadata and assignment.
+/// The scheduler serializes calls; only the version-checked IdealState
callback mutates role and assignment intent.
+/// Commit admission and local handoffs share a segment lock. Remote commits
remain safe through immutable artifact
+/// publication and the native metadata CAS. Retry bookkeeping is
reconstructible and is cleared on leadership loss.
+/// The persisted handoff timestamp is a cooldown policy, not a new ownership
identity or query-readiness barrier.
+final class ReplicateModeRecoveryExecutor {
+ static final String LAST_HANDOFF_PREFIX = "replicateMode.lastHandoff.";
+ private static final Logger LOGGER =
LoggerFactory.getLogger(ReplicateModeRecoveryExecutor.class);
+ private static final long RETRY_INITIAL_DELAY_MS = 10_000L;
+ private static final int REINGESTION_SUBMISSION_TIMEOUT_MS = 5000;
+
+ private final ControllerConf _config;
+ private final PinotHelixResourceManager _resourceManager;
+ private final LeadControllerManager _leadControllerManager;
+ private final PinotLLCRealtimeSegmentManager _segmentManager;
+ private final SegmentCompletionManager _completionManager;
+ private final ControllerMetrics _metrics;
+ private final Clock _clock;
+ private final ReplicateModeRecoveryPlanner _planner;
+ private final Map<String, Map<String, Retry>> _retries = new HashMap<>();
+
+ ReplicateModeRecoveryExecutor(ControllerConf config,
PinotHelixResourceManager resourceManager,
+ LeadControllerManager leadControllerManager,
PinotLLCRealtimeSegmentManager segmentManager,
+ SegmentCompletionManager completionManager, ControllerMetrics metrics,
Clock clock) {
+ _config = config;
+ _resourceManager = resourceManager;
+ _leadControllerManager = leadControllerManager;
+ _segmentManager = segmentManager;
+ _completionManager = completionManager;
+ _metrics = metrics;
+ _clock = clock;
+ _planner = new ReplicateModeRecoveryPlanner(config);
+ }
+
+ void clear(String table) {
+ _retries.remove(table);
+ }
+
+ void clear() {
+ _retries.clear();
+ }
+
+ void execute(String table, Map<Integer, PartitionRecoveryPlan> plans,
BooleanSupplier running) {
+ Set<String> pending = new HashSet<>();
+ List<Work> work = new ArrayList<>();
+ plans.values().forEach(partition ->
partition.segments().values().forEach(segment -> {
+ pending.add(segment.segmentName());
+ if (segment.action() != RecoveryAction.WAIT_FOR_COMPLETION &&
segment.action() != RecoveryAction.BLOCKED) {
+ work.add(new Work(partition, segment));
+ }
+ }));
+ Map<String, Retry> retries = _retries.computeIfAbsent(table, ignored ->
new HashMap<>());
+ retries.keySet().retainAll(pending);
+ // First restore live consumption, then repair completion, then start
bounded fixed-range background work.
+ work.sort(Comparator.comparingInt((Work entry) ->
entry.segment().action().ordinal())
+ .thenComparingInt(entry -> entry.partition().partitionId())
+ .thenComparing(entry -> entry.segment().segmentName()));
+ int remaining = _config.getReplicateModeRecoveryMaxActionsPerTable();
+ boolean repairedCompletion = false;
+ for (Work entry : work) {
+ if (!authorized(table, running) || remaining == 0) {
+ break;
+ }
+ SegmentRecoveryPlan segment = entry.segment();
+ long nowMs = _clock.millis();
+ Retry retry = retries.get(segment.segmentName());
+ if (retry != null && nowMs < retry.nextAttemptMs()) {
+ continue;
+ }
+ remaining--;
+ try {
+ if (segment.action() == RecoveryAction.REPAIR_COMPLETION) {
+ if (!repairedCompletion && validateCompletionRepair(table, segment,
running)) {
+ _segmentManager.repairCompletedReplicateModeSegments(table);
+ TableConfig config = _resourceManager.getTableConfig(table);
+ if (config != null && authorized(table, running)) {
+ _segmentManager.ensureAllPartitionsConsuming(config,
IngestionConfigUtils.getStreamConfigs(config), null);
+ }
+ repairedCompletion = true;
+ }
+ } else {
+ String target =
_completionManager.withSegmentCompletionLock(segment.segmentName(),
+ () -> prepare(table, entry, running));
+ if (target == null) {
+ continue;
+ }
+ if (segment.action() == RecoveryAction.REASSIGN_CONSUMING) {
+ _metrics.addMeteredTableValue(table,
ControllerMeter.REPLICATE_MODE_HANDOFFS, 1);
+ LOGGER.info("Reassigned replicate-mode segment {} in table {} to
{}", segment.segmentName(), table, target);
+ } else if (authorized(table, running)) {
+ // A fresh target may not have initialized its table manager yet.
A 404 or an in-progress 409 is retried.
+ String endpoint =
_resourceManager.getDataInstanceAdminEndpoints(Set.of(target)).get(target);
+ if (endpoint == null) {
+ throw new IllegalStateException("No Server admin endpoint for "
+ target);
+ }
+ _segmentManager.triggerReingestion(endpoint,
segment.segmentName(), REINGESTION_SUBMISSION_TIMEOUT_MS);
+ _metrics.addMeteredTableValue(table,
ControllerMeter.REPLICATE_MODE_RECOVERY_REQUESTS, 1);
+ LOGGER.info("Requested fixed-range recovery of {} in table {} on
{}", segment.segmentName(), table, target);
+ }
+ }
+ scheduleRetry(retries, segment.segmentName(), nowMs, retry);
+ } catch (Exception e) {
+ scheduleRetry(retries, segment.segmentName(), nowMs, retry);
+ _metrics.addMeteredTableValue(table,
ControllerMeter.REPLICATE_MODE_RECOVERY_FAILURES, 1);
+ LOGGER.warn("Replicate-mode recovery will retry segment {} in table
{}", segment.segmentName(), table, e);
+ }
+ }
+ if (retries.isEmpty()) {
+ _retries.remove(table);
+ }
+ }
+
+ @Nullable
+ private String prepare(String table, Work work, BooleanSupplier running) {
+ String[] selected = {null};
+ HelixHelper.updateIdealState(_resourceManager.getHelixZkManager(), table,
idealState -> {
+ selected[0] = null; // The updater can run again after a version
conflict.
+ PartitionRecoveryPlan expected = work.partition();
+ SegmentRecoveryPlan wanted = work.segment();
+ if (!authorized(table, running) || idealState == null ||
!idealState.isEnabled()
+ || PinotLLCRealtimeSegmentManager.isTablePaused(idealState)
+ || PinotLLCRealtimeSegmentManager.isTopicPaused(idealState,
wanted.segmentName())
+ || !Objects.equals(expected.expectedLeader(),
+ ReplicateModeAssignmentUtils.getLeader(idealState,
expected.partitionId()))
+ || !expected.replicaCandidates().equals(
+ ReplicateModeAssignmentUtils.getReplicas(idealState,
expected.partitionId()))) {
+ return idealState;
+ }
+ long nowMs = _clock.millis();
+ if (wanted.action() == RecoveryAction.REASSIGN_CONSUMING
+ && inCooldown(idealState, expected.partitionId(), nowMs)) {
+ return idealState;
+ }
+ Stat metadataStat = new Stat();
+ SegmentZKMetadata metadata =
+ _segmentManager.getSegmentZKMetadataIfExists(table,
wanted.segmentName(), metadataStat);
+ TableConfig tableConfig = _resourceManager.getTableConfig(table);
+ if (metadata == null || tableConfig == null ||
!metadata.isReplicateMode()
+ || metadata.getStatus() != wanted.status()
+ || !Objects.equals(metadata.getStartOffset(), wanted.startOffset())
+ || !Objects.equals(metadata.getEndOffset(), wanted.endOffset())) {
+ return idealState;
+ }
+ Map<String, String> assignment =
idealState.getInstanceStateMap(wanted.segmentName());
+ if (assignment == null) {
+ return idealState;
+ }
+ Set<String> live = Set.copyOf(_resourceManager.getAllLiveInstances());
+ ExternalView externalView = _resourceManager.getTableExternalView(table);
+ FailureReason failure =
ReplicateModeRecoveryPlanner.getFailureReason(assignment, externalView,
+ wanted.segmentName(), () -> live);
+ SegmentSnapshot snapshot = new SegmentSnapshot(metadata, assignment,
failure,
+ _completionManager.getRecoveryStatus(wanted.segmentName()),
+ metadata.getStatus() == Status.COMMITTING
+ &&
_segmentManager.isExceededMaxSegmentCompletionTime(wanted.segmentName(),
metadataStat, nowMs), false);
+ Map<String, InstanceConfig> configs =
_resourceManager.getAllHelixInstanceConfigs().stream()
+ .collect(Collectors.toMap(InstanceConfig::getInstanceName, config ->
config));
+ CandidateContext context = new CandidateContext(tableConfig, idealState,
+ _segmentManager.getConsumingInstancePartitions(tableConfig),
configs, live);
+ PartitionRecoveryPlan current = _planner.plan(context,
List.of(snapshot), externalView, nowMs)
+ .get(expected.partitionId());
+ SegmentRecoveryPlan action = current != null ?
current.segments().get(wanted.segmentName()) : null;
+ if (action == null || action.action() != wanted.action()
+ || !Objects.equals(action.targetServer(), wanted.targetServer()) ||
action.targetServer() == null) {
+ return idealState;
+ }
+ String target = action.targetServer();
+ if (action.action() == RecoveryAction.REASSIGN_CONSUMING) {
+ ReplicateModeAssignmentUtils.setAssignment(idealState,
expected.partitionId(), target,
+ expected.replicaCandidates());
+ idealState.setInstanceStateMap(wanted.segmentName(),
+ new HashMap<>(Map.of(target, SegmentStateModel.CONSUMING)));
+ idealState.getRecord().setSimpleField(LAST_HANDOFF_PREFIX +
expected.partitionId(), Long.toString(nowMs));
+ } else {
+ // Track before publishing the replay assignment: a fast worker can
publish DONE before the next pass.
+ _segmentManager.ensureReplicateModeCompletionTracked(table,
wanted.segmentName());
+ // ONLINE deliberately does not launch an unbounded consumer. The
explicit API rebuilds exactly [start,end).
+ idealState.setInstanceStateMap(wanted.segmentName(), new
HashMap<>(Map.of(target, SegmentStateModel.ONLINE)));
Review Comment:
Suppose A is still serving this frozen range, B now leads the successor, and
A’s upload runs past the completion timeout. The planner can pick B and this
write removes A from routing before B reconstructs any rows. Can we keep the
serving assignment on A while B replays, then retire A once a replacement is
queryable? The existing held-upload integration test could keep the upload
blocked through the timeout.
##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/TableRebalancer.java:
##########
@@ -735,6 +781,7 @@ private RebalanceResult doRebalance(TableConfig
tableConfig, RebalanceConfig reb
- startTimeMs) + " ms.";
tableRebalanceLogger.info(msg);
// Record completion
+ completeRebalancedReplicateModeSegments(tableNameWithType,
targetTableAssignment, idealState);
Review Comment:
A different partition can roll after the convergence check and before
`completeRebalancedReplicateModeSegments` compares the full assignment or
writes its version fence. An exception here skips both `onSuccess` and
`onError`, so the async job can stay `IN_PROGRESS` until the stale-job checker
runs. Can assignment drift re-enter the rebalance loop, with other failures
recorded as terminal? An unrelated rollover at this boundary would exercise it.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/TableConfigUtils.java:
##########
@@ -591,6 +591,12 @@ static void validateIngestionConfig(TableConfig
tableConfig, Schema schema,
Preconditions.checkState(indexingConfig == null ||
MapUtils.isEmpty(indexingConfig.getStreamConfigs()),
"Should not use indexingConfig#getStreamConfigs if
ingestionConfig#StreamIngestionConfig is provided");
StreamIngestionConfig streamIngestionConfig =
ingestionConfig.getStreamIngestionConfig();
+ if (streamIngestionConfig.isReplicateMode()) {
+ Preconditions.checkState(tableConfig.getTableType() ==
TableType.REALTIME,
+ "replicateMode is only supported for REALTIME tables");
+ Preconditions.checkState(!tableConfig.isUpsertEnabled() &&
!tableConfig.isDedupEnabled(),
Review Comment:
Can we validate every configured stream and the routing selector when
enabling this Kafka-only mode? For example, put two Kafka partitions in one
instance partition with their sole leaders in different replica groups. A query
spanning both fails with `multiStageReplicaGroup` because neither group covers
both segments. With `strictReplicaGroup`, simultaneous fanout on opposite
leaders can exclude both servers for their shared assignment set, including
historical segments. Please cover these cases or reject the combinations in v1.
##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/ReplicateModeRecoveryExecutor.java:
##########
@@ -0,0 +1,289 @@
+/**
+ * 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.time.Clock;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BooleanSupplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+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.ControllerMeter;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.common.utils.helix.HelixHelper;
+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.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.RecoveryAction;
+import
org.apache.pinot.controller.helix.core.realtime.ReplicateModeRecoveryPlanner.SegmentRecoveryPlan;
+import
org.apache.pinot.controller.helix.core.realtime.ReplicateModeRecoveryPlanner.SegmentSnapshot;
+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.IngestionConfigUtils;
+import org.apache.zookeeper.data.Stat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/// Executes bounded recovery work after revalidating each plan against
current metadata and assignment.
+/// The scheduler serializes calls; only the version-checked IdealState
callback mutates role and assignment intent.
+/// Commit admission and local handoffs share a segment lock. Remote commits
remain safe through immutable artifact
+/// publication and the native metadata CAS. Retry bookkeeping is
reconstructible and is cleared on leadership loss.
+/// The persisted handoff timestamp is a cooldown policy, not a new ownership
identity or query-readiness barrier.
+final class ReplicateModeRecoveryExecutor {
+ static final String LAST_HANDOFF_PREFIX = "replicateMode.lastHandoff.";
+ private static final Logger LOGGER =
LoggerFactory.getLogger(ReplicateModeRecoveryExecutor.class);
+ private static final long RETRY_INITIAL_DELAY_MS = 10_000L;
+ private static final int REINGESTION_SUBMISSION_TIMEOUT_MS = 5000;
+
+ private final ControllerConf _config;
+ private final PinotHelixResourceManager _resourceManager;
+ private final LeadControllerManager _leadControllerManager;
+ private final PinotLLCRealtimeSegmentManager _segmentManager;
+ private final SegmentCompletionManager _completionManager;
+ private final ControllerMetrics _metrics;
+ private final Clock _clock;
+ private final ReplicateModeRecoveryPlanner _planner;
+ private final Map<String, Map<String, Retry>> _retries = new HashMap<>();
+
+ ReplicateModeRecoveryExecutor(ControllerConf config,
PinotHelixResourceManager resourceManager,
+ LeadControllerManager leadControllerManager,
PinotLLCRealtimeSegmentManager segmentManager,
+ SegmentCompletionManager completionManager, ControllerMetrics metrics,
Clock clock) {
+ _config = config;
+ _resourceManager = resourceManager;
+ _leadControllerManager = leadControllerManager;
+ _segmentManager = segmentManager;
+ _completionManager = completionManager;
+ _metrics = metrics;
+ _clock = clock;
+ _planner = new ReplicateModeRecoveryPlanner(config);
+ }
+
+ void clear(String table) {
+ _retries.remove(table);
+ }
+
+ void clear() {
+ _retries.clear();
+ }
+
+ void execute(String table, Map<Integer, PartitionRecoveryPlan> plans,
BooleanSupplier running) {
+ Set<String> pending = new HashSet<>();
+ List<Work> work = new ArrayList<>();
+ plans.values().forEach(partition ->
partition.segments().values().forEach(segment -> {
+ pending.add(segment.segmentName());
+ if (segment.action() != RecoveryAction.WAIT_FOR_COMPLETION &&
segment.action() != RecoveryAction.BLOCKED) {
+ work.add(new Work(partition, segment));
+ }
+ }));
+ Map<String, Retry> retries = _retries.computeIfAbsent(table, ignored ->
new HashMap<>());
+ retries.keySet().retainAll(pending);
+ // First restore live consumption, then repair completion, then start
bounded fixed-range background work.
+ work.sort(Comparator.comparingInt((Work entry) ->
entry.segment().action().ordinal())
+ .thenComparingInt(entry -> entry.partition().partitionId())
+ .thenComparing(entry -> entry.segment().segmentName()));
+ int remaining = _config.getReplicateModeRecoveryMaxActionsPerTable();
+ boolean repairedCompletion = false;
+ for (Work entry : work) {
+ if (!authorized(table, running) || remaining == 0) {
+ break;
+ }
+ SegmentRecoveryPlan segment = entry.segment();
+ long nowMs = _clock.millis();
+ Retry retry = retries.get(segment.segmentName());
+ if (retry != null && nowMs < retry.nextAttemptMs()) {
+ continue;
+ }
+ remaining--;
+ try {
+ if (segment.action() == RecoveryAction.REPAIR_COMPLETION) {
+ if (!repairedCompletion && validateCompletionRepair(table, segment,
running)) {
+ _segmentManager.repairCompletedReplicateModeSegments(table);
+ TableConfig config = _resourceManager.getTableConfig(table);
+ if (config != null && authorized(table, running)) {
+ _segmentManager.ensureAllPartitionsConsuming(config,
IngestionConfigUtils.getStreamConfigs(config), null);
+ }
+ repairedCompletion = true;
+ }
+ } else {
+ String target =
_completionManager.withSegmentCompletionLock(segment.segmentName(),
+ () -> prepare(table, entry, running));
+ if (target == null) {
+ continue;
+ }
+ if (segment.action() == RecoveryAction.REASSIGN_CONSUMING) {
+ _metrics.addMeteredTableValue(table,
ControllerMeter.REPLICATE_MODE_HANDOFFS, 1);
+ LOGGER.info("Reassigned replicate-mode segment {} in table {} to
{}", segment.segmentName(), table, target);
+ } else if (authorized(table, running)) {
+ // A fresh target may not have initialized its table manager yet.
A 404 or an in-progress 409 is retried.
+ String endpoint =
_resourceManager.getDataInstanceAdminEndpoints(Set.of(target)).get(target);
+ if (endpoint == null) {
+ throw new IllegalStateException("No Server admin endpoint for "
+ target);
+ }
+ _segmentManager.triggerReingestion(endpoint,
segment.segmentName(), REINGESTION_SUBMISSION_TIMEOUT_MS);
+ _metrics.addMeteredTableValue(table,
ControllerMeter.REPLICATE_MODE_RECOVERY_REQUESTS, 1);
+ LOGGER.info("Requested fixed-range recovery of {} in table {} on
{}", segment.segmentName(), table, target);
+ }
+ }
+ scheduleRetry(retries, segment.segmentName(), nowMs, retry);
Review Comment:
An accepted submission only tells us the server queued the work. If Kafka
has deleted the required start offset, the async job fails, logs the error and
disappears. The next pass can submit the same impossible replay indefinitely,
including after a controller change. Please carry a terminal result for that
segment and range back to the controller, expose the required and earliest
offsets, and allow an explicit retry after restoration.
##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/rebalance/TableRebalancer.java:
##########
@@ -1761,14 +1820,156 @@ private DataLossRiskAssessor
createDataLossRiskAssessor(TableConfig tableConfig,
/// Sets the given segment assignment and partition assignment in the given
IdealState, with the number of
/// partitions and replicas derived from the segment assignment. The
replicas are left as they are when there is no
/// segment.
- private static void setAssignment(IdealState idealState, Map<String,
Map<String, String>> segmentAssignment,
- Map<Integer, List<String>> partitionAssignment) {
+ @VisibleForTesting
+ static void setAssignment(IdealState idealState, Map<String, Map<String,
String>> segmentAssignment,
+ Map<Integer, List<String>> partitionAssignment, TableAssignment target) {
+ Map<Integer, ReplicateModePartitionAssignment> nextRoles =
+ getReplicateModeAssignmentForStep(idealState, segmentAssignment,
partitionAssignment, target);
+ Map<String, Map<String, String>> previousAssignment =
idealState.getRecord().getMapFields();
+ for (String segment : target.getReplicateModeSegments()) {
+ Map<String, String> next = segmentAssignment.get(segment);
+ Map<String, String> previous = previousAssignment.get(segment);
+ if (next == null || next.size() != 1 ||
!next.containsValue(SegmentStateModel.CONSUMING)) {
+ continue;
+ }
+ String server = next.keySet().iterator().next();
+ LLCSegmentName name = new LLCSegmentName(segment);
+ if (previous != null &&
SegmentStateModel.CONSUMING.equals(previous.get(server))
+ && (previous.size() != 1 || !server.equals(
+ ReplicateModeAssignmentUtils.getLeader(idealState,
name.getPartitionGroupId())))) {
+ // A previous full-R rebalance or stale role can have made this
retained consumer terminal DISCARDED.
+ // Persist restart intent with the normalized singleton; an unchanged
Helix state alone cannot restart it.
+ ReplicateModeAssignmentUtils.setPendingRestart(idealState, segment,
server);
+ }
+ }
idealState.getRecord().setMapFields(segmentAssignment);
PartitionAssignmentUtils.setPartitionAssignment(idealState,
partitionAssignment);
+ nextRoles.forEach((partition, assignment) ->
ReplicateModeAssignmentUtils.setAssignment(idealState, partition,
Review Comment:
After replicate mode is disabled and its last unfinished range seals, a
rebalance can produce no role for that partition. This update only writes roles
present in the target. A drained follower can therefore stay in the persisted
candidate list and instance-drop validation still treats it as in use. Please
remove obsolete roles in the versioned update once no unfinished range, handoff
or fanout needs them, and cover disable → rollover → rebalance → drop.
--
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]