xiangfu0 commented on code in PR #20321:
URL: https://github.com/apache/pinot/pull/20321#discussion_r4636876359


##########
pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java:
##########
@@ -1059,22 +1059,50 @@ protected void handleUpsert(ImmutableSegment 
immutableSegment, @Nullable Segment
     }
   }
 
+  /// Replaces the old segment with the new one in the upsert metadata, then 
publishes the new segment and offloads the
+  /// old one.
+  ///
+  /// If the upsert metadata replacement fails, the upsert metadata manager 
reverts it, so no primary key points at the
+  /// new segment. The old segment stays registered on its own as before, and 
the new segment is released (destroyed
+  /// once no query holds it), so a later reload, refresh or `ONLINE` 
transition can replace the old segment again.
   protected void replaceUpsertSegment(String segmentName, SegmentDataManager 
oldSegmentManager,
       ImmutableSegmentDataManager newSegmentManager, 
PartitionUpsertMetadataManager partitionUpsertMetadataManager) {
     IndexSegment oldSegment = oldSegmentManager.getSegment();
     ImmutableSegment immutableSegment = newSegmentManager.getSegment();
     UpsertConfig.ConsistencyMode consistencyMode = 
_tableUpsertMetadataManager.getContext().getConsistencyMode();
+    SegmentDataManager duoSegmentDataManager = null;
     if (consistencyMode != UpsertConfig.ConsistencyMode.NONE) {
       // For consistency modes, keep both old and new segments visible to 
queries during replacement so that queries
       // can see the new updates in the new segment while the old segment's 
validDocIds are still being updated.
       // Register the new segment to the upsert metadata manager before making 
it visible to queries so the upsert
       // view is updated before any query can access it.
-      SegmentDataManager duoSegmentDataManager = new 
DuoSegmentDataManager(newSegmentManager, oldSegmentManager);
+      duoSegmentDataManager = new DuoSegmentDataManager(newSegmentManager, 
oldSegmentManager);
       registerSegment(segmentName, duoSegmentDataManager, 
partitionUpsertMetadataManager);
     }
     // Publish the replacement on its own only after its validDocIds and 
partition metadata are initialized, preserving
     // access to the old segment's valid docs during replacement. Mark 
completion before offload releases the permit.
-    partitionUpsertMetadataManager.replaceSegment(immutableSegment, 
oldSegment);
+    try {
+      partitionUpsertMetadataManager.replaceSegment(immutableSegment, 
oldSegment);
+    } catch (RuntimeException e) {
+      _logger.warn("Failed to replace segment: {} with upsert enabled, 
releasing the new segment", segmentName);
+      
partitionUpsertMetadataManager.untrackSegmentForUpsertView(immutableSegment);
+      boolean restored = true;
+      if (duoSegmentDataManager != null) {
+        // The old segment has been serving all along, so restore it without 
firing the post-registration hook again
+        synchronized (_segmentDataManagerMap) {
+          restored = _segmentDataManagerMap.replace(segmentName, 
duoSegmentDataManager, oldSegmentManager);
+        }
+      }
+      if (restored) {
+        // Queries still holding the DuoSegmentDataManager keep the new 
segment until they release it
+        releaseSegment(newSegmentManager);

Review Comment:
   Can we release the replacement only after confirming its metadata references 
are cleared? `revertFailedReplace` logs and suppresses rollback failures, and 
`RecordInfoReader.close()` can throw after the inner replace has moved keys but 
outside the rollback guard. Both can reach this release with primary keys still 
pointing to the replacement. The release decision needs the cleanup result from 
the full metadata operation.



##########
pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java:
##########
@@ -1059,22 +1059,50 @@ protected void handleUpsert(ImmutableSegment 
immutableSegment, @Nullable Segment
     }
   }
 
+  /// Replaces the old segment with the new one in the upsert metadata, then 
publishes the new segment and offloads the
+  /// old one.
+  ///
+  /// If the upsert metadata replacement fails, the upsert metadata manager 
reverts it, so no primary key points at the
+  /// new segment. The old segment stays registered on its own as before, and 
the new segment is released (destroyed
+  /// once no query holds it), so a later reload, refresh or `ONLINE` 
transition can replace the old segment again.
   protected void replaceUpsertSegment(String segmentName, SegmentDataManager 
oldSegmentManager,
       ImmutableSegmentDataManager newSegmentManager, 
PartitionUpsertMetadataManager partitionUpsertMetadataManager) {
     IndexSegment oldSegment = oldSegmentManager.getSegment();
     ImmutableSegment immutableSegment = newSegmentManager.getSegment();
     UpsertConfig.ConsistencyMode consistencyMode = 
_tableUpsertMetadataManager.getContext().getConsistencyMode();
+    SegmentDataManager duoSegmentDataManager = null;
     if (consistencyMode != UpsertConfig.ConsistencyMode.NONE) {
       // For consistency modes, keep both old and new segments visible to 
queries during replacement so that queries
       // can see the new updates in the new segment while the old segment's 
validDocIds are still being updated.
       // Register the new segment to the upsert metadata manager before making 
it visible to queries so the upsert
       // view is updated before any query can access it.
-      SegmentDataManager duoSegmentDataManager = new 
DuoSegmentDataManager(newSegmentManager, oldSegmentManager);
+      duoSegmentDataManager = new DuoSegmentDataManager(newSegmentManager, 
oldSegmentManager);
       registerSegment(segmentName, duoSegmentDataManager, 
partitionUpsertMetadataManager);
     }
     // Publish the replacement on its own only after its validDocIds and 
partition metadata are initialized, preserving
     // access to the old segment's valid docs during replacement. Mark 
completion before offload releases the permit.
-    partitionUpsertMetadataManager.replaceSegment(immutableSegment, 
oldSegment);
+    try {
+      partitionUpsertMetadataManager.replaceSegment(immutableSegment, 
oldSegment);
+    } catch (RuntimeException e) {
+      _logger.warn("Failed to replace segment: {} with upsert enabled, 
releasing the new segment", segmentName);
+      
partitionUpsertMetadataManager.untrackSegmentForUpsertView(immutableSegment);

Review Comment:
   Can we refresh the restored view and publish the old manager before 
untracking the replacement? In SYNC, a query can pick up the Duo in this gap, 
get no upsert bitmap for the replacement, and scan its superseded rows and 
tombstones. In SNAPSHOT, a refresh during replacement can leave the cached old 
bitmap missing keys even after the live bitmap is restored. Keep the 
replacement tracked until queries that acquired the Duo have captured their 
views.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManager.java:
##########
@@ -306,6 +306,38 @@ protected void removeSegment(IndexSegment segment, 
MutableRoaringBitmap validDoc
     }
   }
 
+  @Override
+  protected void revertReplacedKeys(IndexSegment segment, IndexSegment 
oldSegment, MutableRoaringBitmap movedDocIds,
+      boolean oldValidDocIdsIntact) {
+    ThreadSafeMutableRoaringBitmap oldValidDocIds = 
oldSegment.getValidDocIds();
+    ThreadSafeMutableRoaringBitmap oldQueryableDocIds = 
oldSegment.getQueryableDocIds();
+    try (UpsertUtils.RecordInfoReader recordInfoReader = new 
UpsertUtils.RecordInfoReader(oldSegment,
+        _primaryKeyColumns, _comparisonColumns, _deleteRecordColumn)) {
+      Iterator<RecordInfo> recordInfoIterator = 
UpsertUtils.getRecordInfoIterator(recordInfoReader, movedDocIds);
+      while (recordInfoIterator.hasNext()) {
+        RecordInfo recordInfo = recordInfoIterator.next();
+        int oldDocId = recordInfo.getDocId();
+        _primaryKeyToRecordLocationMap.computeIfPresent(
+            HashUtils.hashPrimaryKey(recordInfo.getPrimaryKey(), 
_hashFunction), (primaryKey, recordLocation) -> {
+              if (recordLocation.getSegment() == segment) {
+                replaceDocId(oldSegment, oldValidDocIds, oldQueryableDocIds, 
segment, recordLocation.getDocId(),
+                    oldDocId, recordInfo);
+                return new RecordLocation(oldSegment, oldDocId, 
recordInfo.getComparisonValue());

Review Comment:
   Can we restore the original `RecordLocation` here? With multiple comparison 
columns, a FULL-upsert row stored as `[null, 200]` can have `[100, 200]` in the 
map because ingestion preserves the other source's comparison value. I checked 
the comparator in JShell. After rebuilding from the row, `[50, null]` wins 
where it would previously have been rejected as stale.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManager.java:
##########
@@ -306,6 +306,38 @@ protected void removeSegment(IndexSegment segment, 
MutableRoaringBitmap validDoc
     }
   }
 
+  @Override
+  protected void revertReplacedKeys(IndexSegment segment, IndexSegment 
oldSegment, MutableRoaringBitmap movedDocIds,
+      boolean oldValidDocIdsIntact) {
+    ThreadSafeMutableRoaringBitmap oldValidDocIds = 
oldSegment.getValidDocIds();
+    ThreadSafeMutableRoaringBitmap oldQueryableDocIds = 
oldSegment.getQueryableDocIds();
+    try (UpsertUtils.RecordInfoReader recordInfoReader = new 
UpsertUtils.RecordInfoReader(oldSegment,
+        _primaryKeyColumns, _comparisonColumns, _deleteRecordColumn)) {
+      Iterator<RecordInfo> recordInfoIterator = 
UpsertUtils.getRecordInfoIterator(recordInfoReader, movedDocIds);
+      while (recordInfoIterator.hasNext()) {
+        RecordInfo recordInfo = recordInfoIterator.next();
+        int oldDocId = recordInfo.getDocId();
+        _primaryKeyToRecordLocationMap.computeIfPresent(

Review Comment:
   The previous-location map needs rollback too. A replacement row that loses 
to a consuming row can overwrite its saved predecessor without setting a 
valid-doc bit. This loop misses that entry, and a later PROTECTED 
reconciliation drops the key when the saved predecessor points to the destroyed 
replacement. Can we save and restore previous-location changes alongside 
current ownership?



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManager.java:
##########
@@ -761,6 +779,67 @@ public void replaceSegment(ImmutableSegment segment, 
@Nullable ThreadSafeMutable
     }
   }
 
+  /// Reverts a segment replacement that failed partway, so that no primary 
key points at the new segment and the new
+  /// segment can be destroyed. The keys moved off the old segment point at it 
again ([#revertReplacedKeys]), and the
+  /// other keys still pointing at the new segment are removed. The old 
segment then serves as before the replacement,
+  /// and replacing it again converges to the same metadata as a replacement 
that never failed, except that:
+  /// - Keys the new segment took from other segments stay removed until the 
replacement is retried, because the rows
+  ///   they had in those segments are already invalidated.
+  /// - For tables with inconsistent state, the previous record locations 
dropped for the moved keys are not restored.
+  ///
+  /// A failure of the revert is attached to the replacement failure and 
reported, but not thrown.
+  ///
+  /// @param validDocIdsForOldSegment Copy of the old segment's valid doc ids 
that the replacement updated instead of
+  ///                                 the old segment's own bitmap, or `null` 
if it updated the bitmap in place
+  /// @param oldValidDocIdsBeforeReplace Old segment's valid doc ids before a 
replacement that updated them in place
+  protected void revertFailedReplace(ImmutableSegment segment, IndexSegment 
oldSegment,
+      @Nullable MutableRoaringBitmap validDocIdsForOldSegment,
+      @Nullable MutableRoaringBitmap oldValidDocIdsBeforeReplace, 
RuntimeException replaceFailure) {
+    String segmentName = segment.getSegmentName();
+    try {
+      MutableRoaringBitmap oldValidDocIds = 
getValidDocIdsForOldSegment(oldSegment);
+      if (oldValidDocIds != null) {
+        // The docs moved off the old segment are missing from the copy if the 
old segment's bitmap is kept intact, and
+        // missing from the old segment's bitmap otherwise.
+        boolean oldValidDocIdsIntact = validDocIdsForOldSegment != null;
+        MutableRoaringBitmap movedDocIds = oldValidDocIdsIntact
+            ? MutableRoaringBitmap.andNot(oldValidDocIds, 
validDocIdsForOldSegment)
+            : MutableRoaringBitmap.andNot(oldValidDocIdsBeforeReplace, 
oldValidDocIds);
+        if (!movedDocIds.isEmpty()) {
+          _logger.info("Pointing primary keys of up to {} docs back at the old 
segment: {} after failing to replace it",
+              movedDocIds.getCardinality(), segmentName);
+          revertReplacedKeys(segment, oldSegment, movedDocIds, 
oldValidDocIdsIntact);
+        }
+      }
+      MutableRoaringBitmap validDocIds = 
UpsertUtils.getValidDocIdsSnapshotFromSegment(segment, true);
+      if (!validDocIds.isEmpty()) {
+        _logger.warn("Removing up to {} primary keys added by the failed 
replacement of segment: {}",
+            validDocIds.getCardinality(), segmentName);
+        removeSegment(segment, validDocIds);

Review Comment:
   Can we restore displaced owners from other segments before removing the 
failed copy? If the replacement takes a key from another segment, it clears 
that row's visibility bits. This cleanup then deletes the replacement's 
ownership, leaving the key missing until a successful retry, which may never 
happen. Save the prior location and its visibility state and restore it if the 
failed copy still owns the key.



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

Reply via email to