deepthi912 commented on code in PR #19637:
URL: https://github.com/apache/pinot/pull/19637#discussion_r4203804415


##########
pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java:
##########
@@ -831,21 +831,26 @@ public void run() {
         //   persisted.
         // Take upsert snapshot before starting consuming events
         if (_partitionUpsertMetadataManager != null) {
+          // If the previous consuming segment released the semaphore to build 
or download in parallel, it can still be
+          // mutable in the metadata, so this replica's snapshot covers its 
rows up to where it stopped.
+          ConsumerCoordinator.UnsealedRelease unsealedRelease = 
_consumerCoordinator.getUnsealedRelease();
+          String consumedUpToOffset =
+              unsealedRelease != null ? 
unsealedRelease.stoppedAtOffset().toString() : _startOffset.toString();

Review Comment:
   `_unsealedRelease` is only cleared by the segment that set it, in its own 
`doOffload()`. So if N's build or download stalls and N+1 commits sealed (plain 
`release()`, which sets nothing), N+2 still reads N's record and publishes an 
offset from two segments back — which reads as "this replica is far behind" 
when it isn't. That's the exact misreading this field exists to prevent.
   
   Can we only use it when it's actually ahead of where this segment starts? 
`StreamPartitionMsgOffset` is `Comparable`:
   
   ```java
   String consumedUpToOffset = unsealedRelease != null
       && unsealedRelease.stoppedAtOffset().compareTo(_startOffset) > 0
       ? unsealedRelease.stoppedAtOffset().toString() : _startOffset.toString();
   ```
   
   That also covers the race where the predecessor offloads between acquire and 
snapshot, which today silently falls back to `_startOffset` and makes the value 
nondeterministic.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManager.java:
##########
@@ -97,6 +98,10 @@ public abstract class BasePartitionUpsertMetadataManager 
implements PartitionUps
   protected final ServerMetrics _serverMetrics;
   protected final Logger _logger;
 
+  // Scoped to the caller so concurrent snapshot triggers cannot exchange 
provenance. Preserve the existing virtual
+  // takeSnapshot()/doTakeSnapshot() hooks used by custom managers.
+  private final ThreadLocal<DocIdsSnapshot.Trigger> _snapshotTrigger = new 
ThreadLocal<>();

Review Comment:
   The ThreadLocal returns null without any error if `doTakeSnapshot()` ever 
runs on a different thread, so the diagnostics would just quietly stop 
appearing. The constraint you're working around is real (subclasses override 
`doTakeSnapshot()`), but an overload keeps those working and makes the dataflow 
explicit:
   
   ```java
   protected void doTakeSnapshot() { doTakeSnapshot(null); }
   protected void doTakeSnapshot(@Nullable DocIdsSnapshot.Trigger trigger) { 
... }
   ```



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/DocIdsSnapshot.java:
##########
@@ -0,0 +1,128 @@
+/**
+ * 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.segment.local.upsert;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.CRC32;
+import javax.annotation.Nullable;
+import 
org.apache.pinot.segment.spi.index.mutable.ThreadSafeMutableRoaringBitmap;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.roaringbitmap.IntIterator;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/// A persisted bitmap and its optional capture diagnostics, read from the 
same file generation.
+/// The Roaring bytes remain a prefix readable by existing snapshot readers. A 
versioned metadata trailer is published
+/// with that prefix through the existing temporary-file rename, so a 
concurrent reader cannot pair different captures.
+public record DocIdsSnapshot(MutableRoaringBitmap docIds, @Nullable Metadata 
metadata) {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(DocIdsSnapshot.class);
+  private static final int MAGIC = 0x5044534D; // PDSM: Pinot doc ids snapshot 
metadata
+  private static final int VERSION = 1;
+
+  /// The consumer startup that triggered a snapshot. consumedUpToOffset is 
exclusive and per replica: the consumer's
+  /// start offset, or where the previous segment stopped if it was still 
unsealed. It is not a consistency watermark.
+  public record Trigger(String consumingSegmentName, String 
consumedUpToOffset) {
+  }
+
+  /// Which bitmap a snapshot file holds, so its CRC says what it covers.
+  public enum DocIdsType {
+    VALID_DOC_IDS, QUERYABLE_DOC_IDS
+  }
+
+  // Ignore unknown fields so an older server still reads diagnostics written 
by a newer one.
+  @JsonIgnoreProperties(ignoreUnknown = true)
+  public record Metadata(long docIdsCrc, DocIdsType docIdsType, long 
snapshotCapturedAtMs,
+                         @Nullable String snapshotConsumingSegmentName, 
@Nullable String snapshotConsumedUpToOffset) {
+    public Map<String, Object> toResponse(long nowMs) {
+      Map<String, Object> response = new HashMap<>();
+      response.put("docIdsCrc", docIdsCrc);
+      response.put("docIdsType", docIdsType.name());
+      response.put("snapshotCapturedAtMs", snapshotCapturedAtMs);
+      // Do not turn clock skew into an apparently fresh snapshot.
+      if (nowMs >= snapshotCapturedAtMs) {
+        response.put("snapshotAgeMs", nowMs - snapshotCapturedAtMs);
+      }
+      if (snapshotConsumingSegmentName != null && snapshotConsumedUpToOffset 
!= null) {
+        response.put("snapshotConsumingSegmentName", 
snapshotConsumingSegmentName);
+        response.put("snapshotConsumedUpToOffset", snapshotConsumedUpToOffset);
+      }
+      return response;
+    }
+  }
+
+  /// Capture the timestamp with the bitmap under its existing lock, then hash 
the detached bitmap outside that lock.
+  public static ThreadSafeMutableRoaringBitmap.CardinalityAndBytes 
capture(ThreadSafeMutableRoaringBitmap bitmap,
+      DocIdsType docIdsType, @Nullable Trigger trigger)
+      throws IOException {
+    ThreadSafeMutableRoaringBitmap.CardinalityAndBytes snapshot;
+    long capturedAtMs;
+    synchronized (bitmap) {

Review Comment:
   This works only because 
`ThreadSafeMutableRoaringBitmap.getBytesAndCardinality()` is `public 
synchronized`, i.e. locks on `this`. If that class moves to a private lock, the 
timestamp silently stops being atomic with the capture and nothing fails to 
compile. Worth putting the combined accessor on 
`ThreadSafeMutableRoaringBitmap` itself.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/DocIdsSnapshot.java:
##########
@@ -0,0 +1,128 @@
+/**
+ * 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.segment.local.upsert;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.CRC32;
+import javax.annotation.Nullable;
+import 
org.apache.pinot.segment.spi.index.mutable.ThreadSafeMutableRoaringBitmap;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.roaringbitmap.IntIterator;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/// A persisted bitmap and its optional capture diagnostics, read from the 
same file generation.
+/// The Roaring bytes remain a prefix readable by existing snapshot readers. A 
versioned metadata trailer is published
+/// with that prefix through the existing temporary-file rename, so a 
concurrent reader cannot pair different captures.
+public record DocIdsSnapshot(MutableRoaringBitmap docIds, @Nullable Metadata 
metadata) {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(DocIdsSnapshot.class);
+  private static final int MAGIC = 0x5044534D; // PDSM: Pinot doc ids snapshot 
metadata
+  private static final int VERSION = 1;
+
+  /// The consumer startup that triggered a snapshot. consumedUpToOffset is 
exclusive and per replica: the consumer's
+  /// start offset, or where the previous segment stopped if it was still 
unsealed. It is not a consistency watermark.
+  public record Trigger(String consumingSegmentName, String 
consumedUpToOffset) {
+  }
+
+  /// Which bitmap a snapshot file holds, so its CRC says what it covers.
+  public enum DocIdsType {
+    VALID_DOC_IDS, QUERYABLE_DOC_IDS
+  }
+
+  // Ignore unknown fields so an older server still reads diagnostics written 
by a newer one.
+  @JsonIgnoreProperties(ignoreUnknown = true)
+  public record Metadata(long docIdsCrc, DocIdsType docIdsType, long 
snapshotCapturedAtMs,
+                         @Nullable String snapshotConsumingSegmentName, 
@Nullable String snapshotConsumedUpToOffset) {
+    public Map<String, Object> toResponse(long nowMs) {
+      Map<String, Object> response = new HashMap<>();
+      response.put("docIdsCrc", docIdsCrc);
+      response.put("docIdsType", docIdsType.name());
+      response.put("snapshotCapturedAtMs", snapshotCapturedAtMs);
+      // Do not turn clock skew into an apparently fresh snapshot.
+      if (nowMs >= snapshotCapturedAtMs) {
+        response.put("snapshotAgeMs", nowMs - snapshotCapturedAtMs);
+      }
+      if (snapshotConsumingSegmentName != null && snapshotConsumedUpToOffset 
!= null) {
+        response.put("snapshotConsumingSegmentName", 
snapshotConsumingSegmentName);
+        response.put("snapshotConsumedUpToOffset", snapshotConsumedUpToOffset);
+      }
+      return response;
+    }
+  }
+
+  /// Capture the timestamp with the bitmap under its existing lock, then hash 
the detached bitmap outside that lock.
+  public static ThreadSafeMutableRoaringBitmap.CardinalityAndBytes 
capture(ThreadSafeMutableRoaringBitmap bitmap,
+      DocIdsType docIdsType, @Nullable Trigger trigger)
+      throws IOException {
+    ThreadSafeMutableRoaringBitmap.CardinalityAndBytes snapshot;
+    long capturedAtMs;
+    synchronized (bitmap) {
+      snapshot = bitmap.getBytesAndCardinality();
+      capturedAtMs = System.currentTimeMillis();
+    }
+    ImmutableRoaringBitmap captured = new 
ImmutableRoaringBitmap(ByteBuffer.wrap(snapshot.getBytes()));
+    CRC32 crc = new CRC32();
+    IntIterator iterator = captured.getIntIterator();
+    // Canonical ascending doc IDs, four big-endian bytes per ID: independent 
of Roaring container layout.
+    while (iterator.hasNext()) {
+      int docId = iterator.next();
+      crc.update(docId >>> 24);
+      crc.update(docId >>> 16);
+      crc.update(docId >>> 8);
+      crc.update(docId);
+    }
+    Metadata metadata = new Metadata(crc.getValue(), docIdsType, capturedAtMs,
+        trigger != null ? trigger.consumingSegmentName() : null, trigger != 
null ? trigger.consumedUpToOffset() : null);
+    byte[] json = 
JsonUtils.objectToString(metadata).getBytes(StandardCharsets.UTF_8);
+    byte[] bytes = ByteBuffer.allocate(snapshot.getBytes().length + 2 * 
Integer.BYTES + json.length)

Review Comment:
   Nit: this copies the whole serialized bitmap a second time — an extra 
MB-scale array per segment per snapshot round on large partitions. Writing the 
bitmap and the trailer as two writes in `persistDocIdsSnapshot` would avoid it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [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