This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 18eee833ced Batch match-all and sorted document-ID iteration (#19536)
18eee833ced is described below

commit 18eee833ced6c71d74601017550b6ffe030b547f
Author: Xiang Fu <[email protected]>
AuthorDate: Wed Nov 18 17:08:28 2026 -0800

    Batch match-all and sorted document-ID iteration (#19536)
    
    * Batch match-all and sorted document-ID iteration
    
    Match-all and sorted ranges populate document blocks one ID at a time. Add 
a compatible batch iterator hook and contiguous fills to reduce iteration work 
while preserving exhaustion, checkpoints, cancellation and scan counters.
    
    * Clarify document ID batching contracts and trim redundant tests
    
    * Drop redundant nextBatch bounds checks and tidy batching names
    
    The only production caller, DocIdSetOperator, already validates the batch
    size and passes a scratch array sized to MAX_DOC_PER_CALL, so the per-call
    argument checks are removed and the documented precondition is kept.
    Rename the operator's batch count to numDocIds, rename test helper
    parameters to maxDocs, and drop a test assertion that could not fail.
---
 .../pinot/core/common/BlockDocIdIterator.java      |  25 ++
 .../pinot/core/operator/DocIdSetOperator.java      |  20 +-
 .../pinot/core/operator/blocks/DocIdSetBlock.java  |  16 +-
 .../dociditerators/MatchAllDocIdIterator.java      |  14 +
 .../dociditerators/SortedDocIdIterator.java        |  23 ++
 .../pinot/core/operator/DocIdSetOperatorTest.java  | 312 +++++++++++++++++++++
 .../dociditerators/DocIdIteratorBatchTest.java     | 235 ++++++++++++++++
 .../pinot/queries/DocIdBatchNullQueriesTest.java   | 212 ++++++++++++++
 8 files changed, 836 insertions(+), 21 deletions(-)

diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/common/BlockDocIdIterator.java 
b/pinot-core/src/main/java/org/apache/pinot/core/common/BlockDocIdIterator.java
index 138e81b2554..2ad224f605b 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/common/BlockDocIdIterator.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/common/BlockDocIdIterator.java
@@ -18,6 +18,9 @@
  */
 package org.apache.pinot.core.common;
 
+import org.apache.pinot.segment.spi.Constants;
+
+
 /// The interface `BlockDocIdIterator` represents the iterator for 
`BlockDocIdSet`. The document
 /// ids returned from the iterator should be in ascending order.
 public interface BlockDocIdIterator extends AutoCloseable {
@@ -29,6 +32,28 @@ public interface BlockDocIdIterator extends AutoCloseable {
   /// [org.apache.pinot.segment.spi.Constants#EOF].
   int next();
 
+  /// Writes up to `maxDocs` next matching document ids into the prefix of the 
caller-owned `output` array and returns
+  /// the number written. Requires `0 < maxDocs <= output.length`. Does not 
retain the array or modify its remaining
+  /// elements. A full batch does not consume another document to look ahead.
+  ///
+  /// A return value less than `maxDocs` means the iterator is exhausted. 
There must be no further calls to
+  /// [#next()], [#advance(int)], or this method after a short batch. 
Otherwise, these methods share the same cursor
+  /// and may be interleaved subject to the target constraint of 
[#advance(int)]. This method must not be called after
+  /// either scalar method returns [Constants#EOF].
+  ///
+  /// The default implementation preserves scalar iteration for existing 
implementations.
+  default int nextBatch(int[] output, int maxDocs) {
+    int size = 0;
+    while (size < maxDocs) {
+      int docId = next();
+      if (docId == Constants.EOF) {
+        break;
+      }
+      output[size++] = docId;
+    }
+    return size;
+  }
+
   /// Returns the first matching document whose id is greater than or equal to 
the given target document id, or
   /// [org.apache.pinot.segment.spi.Constants#EOF] if there is no such 
document.
   ///
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/DocIdSetOperator.java 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/DocIdSetOperator.java
index d4e42c2f410..2339f56bb48 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/DocIdSetOperator.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/DocIdSetOperator.java
@@ -26,7 +26,6 @@ import org.apache.pinot.core.common.Operator;
 import org.apache.pinot.core.operator.blocks.DocIdSetBlock;
 import org.apache.pinot.core.operator.filter.BaseFilterOperator;
 import org.apache.pinot.core.plan.DocIdSetPlanNode;
-import org.apache.pinot.segment.spi.Constants;
 import org.apache.pinot.spi.query.QueryScanCostContext;
 import org.apache.pinot.spi.query.QueryThreadContext;
 
@@ -51,7 +50,7 @@ public class DocIdSetOperator extends BaseDocIdSetOperator {
 
   private BlockDocIdSet _blockDocIdSet;
   private BlockDocIdIterator _blockDocIdIterator;
-  private int _currentDocId = 0;
+  private boolean _exhausted;
   private long _lastReportedEntriesScanned = 0;
 
   public DocIdSetOperator(BaseFilterOperator filterOperator, int 
maxSizeOfDocIdSet) {
@@ -62,7 +61,7 @@ public class DocIdSetOperator extends BaseDocIdSetOperator {
 
   @Override
   protected DocIdSetBlock getNextBlock() {
-    if (_currentDocId == Constants.EOF) {
+    if (_exhausted) {
       return null;
     }
 
@@ -74,16 +73,11 @@ public class DocIdSetOperator extends BaseDocIdSetOperator {
 
     QueryThreadContext.sampleUsage();
 
-    int pos = 0;
     int[] docIds = THREAD_LOCAL_DOC_IDS.get();
-    for (int i = 0; i < _maxSizeOfDocIdSet; i++) {
-      _currentDocId = _blockDocIdIterator.next();
-      if (_currentDocId == Constants.EOF) {
-        break;
-      }
-      docIds[pos++] = _currentDocId;
-    }
-    if (pos > 0) {
+    int numDocIds = _blockDocIdIterator.nextBatch(docIds, _maxSizeOfDocIdSet);
+    // A short batch means the iterator is exhausted; do not call it again.
+    _exhausted = numDocIds < _maxSizeOfDocIdSet;
+    if (numDocIds > 0) {
       // Push scan cost delta for proactive query killing
       QueryScanCostContext scanCost = getScanCostContext();
       if (scanCost != null) {
@@ -94,7 +88,7 @@ public class DocIdSetOperator extends BaseDocIdSetOperator {
           _lastReportedEntriesScanned = currentTotal;
         }
       }
-      return new DocIdSetBlock(docIds, pos);
+      return new DocIdSetBlock(docIds, numDocIds);
     } else {
       return null;
     }
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/DocIdSetBlock.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/DocIdSetBlock.java
index cd074a881b3..4ee6fdc2ab4 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/DocIdSetBlock.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/DocIdSetBlock.java
@@ -24,15 +24,15 @@ import org.apache.pinot.core.common.Block;
 /// The `DocIdSetBlock` contains a block of document ids and is returned from
 /// [org.apache.pinot.core.operator.BaseDocIdSetOperator].
 ///
-/// Each `BaseDocIdSetOperator` can return multiple `DocIdSetBlock`s and each 
block contains an array of
-/// document ids.
+/// Each `BaseDocIdSetOperator` can return multiple blocks. The first 
[#getLength()] entries of [#getDocIds()]
+/// contain this block's document ids.
 ///
-/// **IMPORTANT**: The document id array may be a scratch buffer owned and 
reused by the producing operator, in which
-/// case its contents are invalidated by the next `nextBlock()` call on that 
operator. Consumers that hold on to a
-/// block across pulls (e.g. projection operators that prefetch multiple 
blocks ahead) must copy the array, and must
-/// not share other per-block scratch state across the retained blocks (e.g. 
they need a dedicated
-/// [org.apache.pinot.core.common.DataBlockCache] per retained block rather 
than the single shared instance the
-/// default projection operator uses).
+/// Producers may reuse the document id array across pulls. 
[org.apache.pinot.core.operator.DocIdSetOperator] and
+/// [org.apache.pinot.core.operator.ReverseDocIdSetOperator] each share a 
scratch buffer among instances of their class
+/// on the same thread. Consumers that retain a block must copy its document 
ids before any pull that can overwrite
+/// the buffer. They must also keep other per-block scratch state separate for 
each retained block. For example,
+/// projection operators that prefetch multiple blocks need a dedicated 
[org.apache.pinot.core.common.DataBlockCache]
+/// per retained block.
 ///
 /// Do not confuse this class with 
[org.apache.pinot.core.common.BlockDocIdSet], which is returned by
 /// the filter operator and contains a set of document ids that can be 
iterated through.
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/MatchAllDocIdIterator.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/MatchAllDocIdIterator.java
index ae52f1187db..611626730d2 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/MatchAllDocIdIterator.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/MatchAllDocIdIterator.java
@@ -41,6 +41,20 @@ public final class MatchAllDocIdIterator implements 
BlockDocIdIterator {
     }
   }
 
+  @Override
+  public int nextBatch(int[] output, int maxDocs) {
+    int nextDocId = _nextDocId;
+    if (nextDocId >= _numDocs) {
+      return 0;
+    }
+    int size = Math.min(maxDocs, _numDocs - nextDocId);
+    for (int i = 0; i < size; i++) {
+      output[i] = nextDocId + i;
+    }
+    _nextDocId += size;
+    return size;
+  }
+
   @Override
   public int advance(int targetDocId) {
     _nextDocId = targetDocId;
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/SortedDocIdIterator.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/SortedDocIdIterator.java
index 09c02e1e1b5..e8c789cc983 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/SortedDocIdIterator.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/operator/dociditerators/SortedDocIdIterator.java
@@ -60,6 +60,29 @@ public final class SortedDocIdIterator implements 
BlockDocIdIterator {
     }
   }
 
+  @Override
+  public int nextBatch(int[] output, int maxDocs) {
+    int size = 0;
+    while (size < maxDocs) {
+      IntPair currentRange = _docIdRanges.get(_currentRangeId);
+      if (_nextDocId > currentRange.getRight()) {
+        if (_currentRangeId == _numRanges - 1) {
+          break;
+        }
+        currentRange = _docIdRanges.get(++_currentRangeId);
+        _nextDocId = currentRange.getLeft();
+      }
+      int nextDocId = _nextDocId;
+      int numDocs = Math.min(maxDocs - size, currentRange.getRight() - 
nextDocId + 1);
+      for (int i = 0; i < numDocs; i++) {
+        output[size + i] = nextDocId + i;
+      }
+      size += numDocs;
+      _nextDocId += numDocs;
+    }
+    return size;
+  }
+
   @Override
   public int advance(int targetDocId) {
     IntPair currentRange = _docIdRanges.get(_currentRangeId);
diff --git 
a/pinot-core/src/test/java/org/apache/pinot/core/operator/DocIdSetOperatorTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/core/operator/DocIdSetOperatorTest.java
new file mode 100644
index 00000000000..c9802fa58e7
--- /dev/null
+++ 
b/pinot-core/src/test/java/org/apache/pinot/core/operator/DocIdSetOperatorTest.java
@@ -0,0 +1,312 @@
+/**
+ * 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.core.operator;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import org.apache.pinot.core.common.BlockDocIdIterator;
+import org.apache.pinot.core.common.BlockDocIdSet;
+import org.apache.pinot.core.operator.blocks.DocIdSetBlock;
+import org.apache.pinot.core.operator.filter.BaseFilterOperator;
+import org.apache.pinot.core.operator.filter.MatchAllFilterOperator;
+import org.apache.pinot.segment.spi.Constants;
+import org.apache.pinot.spi.accounting.ThreadAccountant;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.TerminationException;
+import org.apache.pinot.spi.query.QueryExecutionContext;
+import org.apache.pinot.spi.query.QueryScanCostContext;
+import org.apache.pinot.spi.query.QueryThreadContext;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNotSame;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+
+/// Exercises document block boundaries, query accounting and scratch 
ownership through public operator pulls.
+/// Every test owns its query context and iterators; only the documented 
thread-local output buffer is shared.
+public class DocIdSetOperatorTest {
+  @DataProvider
+  public Object[][] blockBoundaries() {
+    return new Object[][]{{0, 2}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {8, 
3}};
+  }
+
+  @Test(dataProvider = "blockBoundaries")
+  public void testFullPartialAndEmptyTerminalBlocks(int numDocs, int 
batchSize) {
+    int[] expected = new int[numDocs];
+    for (int i = 0; i < numDocs; i++) {
+      expected[i] = i * 3;
+    }
+    StrictDocIdSet docIdSet = new StrictDocIdSet(expected);
+    FixedFilterOperator filter = new FixedFilterOperator(docIdSet);
+    DocIdSetOperator operator = new DocIdSetOperator(filter, batchSize);
+    ThreadAccountant accountant = mock(ThreadAccountant.class);
+    try (QueryThreadContext ignore = 
QueryThreadContext.open(QueryExecutionContext.forSseTest(), accountant)) {
+      int publicPulls = 0;
+      for (int offset = 0; offset < numDocs; offset += batchSize) {
+        int length = Math.min(batchSize, numDocs - offset);
+        assertDocIds(operator.nextBlock(), Arrays.copyOfRange(expected, 
offset, offset + length));
+        publicPulls++;
+        // A full block must not consume a match or EOF beyond its requested 
prefix.
+        int expectedCalls = offset + length + (length < batchSize ? 1 : 0);
+        assertEquals(docIdSet._nextCalls, expectedCalls);
+      }
+      assertNull(operator.nextBlock());
+      publicPulls++;
+      int activeAttempts = numDocs / batchSize + 1;
+      assertEquals(docIdSet._nextCalls, numDocs + 1);
+      assertEquals(docIdSet._batchCalls, activeAttempts);
+      assertEquals(docIdSet._iteratorCalls, 1);
+      assertEquals(filter._filterCalls, 1);
+
+      assertNull(operator.nextBlock());
+      assertNull(operator.nextBlock());
+      publicPulls += 2;
+      assertEquals(docIdSet._nextCalls, numDocs + 1, "Latched EOF must not 
call the iterator again");
+      assertEquals(docIdSet._batchCalls, activeAttempts);
+      verify(accountant, times(activeAttempts)).sampleUsage();
+      // Filter initialization has its own checkpoint; every public pull keeps 
its checkpoint even after EOF.
+      verify(accountant, times(publicPulls + 1)).waitIfPaused();
+    }
+  }
+
+  @DataProvider
+  public Object[][] scanCostTails() {
+    return new Object[][]{
+        {new int[0], new long[]{20}, 0L},
+        {new int[]{2, 6}, new long[]{3, 7, 20}, 7L},
+        {new int[]{2, 6, 9}, new long[]{3, 7, 10, 20}, 20L}
+    };
+  }
+
+  @Test(dataProvider = "scanCostTails")
+  public void testScanCostPreservesUnmatchedTerminalTail(int[] docIds, long[] 
scanTotals, long expectedPushedCost) {
+    StrictDocIdSet docIdSet = new StrictDocIdSet(docIds, scanTotals);
+    DocIdSetOperator operator = new DocIdSetOperator(new 
FixedFilterOperator(docIdSet), 2);
+    QueryExecutionContext executionContext = 
QueryExecutionContext.forSseTest();
+    QueryScanCostContext scanCost = new QueryScanCostContext();
+    executionContext.setQueryScanCostContext(scanCost);
+    try (QueryThreadContext ignore = QueryThreadContext.open(executionContext, 
mock(ThreadAccountant.class))) {
+      
assertEquals(operator.getExecutionStatistics().getNumEntriesScannedInFilter(), 
0L);
+      while (operator.nextBlock() != null) {
+        // Consume the full stream, including any unmatched tail found while 
looking for EOF.
+      }
+      // Existing proactive accounting only publishes deltas with a nonempty 
block. Final statistics include all scans.
+      assertEquals(scanCost.getNumEntriesScannedInFilter(), 
expectedPushedCost);
+      ExecutionStatistics statistics = operator.getExecutionStatistics();
+      assertEquals(statistics.getNumEntriesScannedInFilter(), 20L);
+      assertEquals(statistics.getNumDocsScanned(), 0L);
+      assertEquals(statistics.getNumEntriesScannedPostFilter(), 0L);
+      assertEquals(statistics.getNumTotalDocs(), 0L);
+      assertNull(operator.nextBlock());
+      assertEquals(scanCost.getNumEntriesScannedInFilter(), 
expectedPushedCost);
+      assertEquals(docIdSet._nextCalls, docIds.length + 1);
+    }
+  }
+
+  @DataProvider
+  public Object[][] cancellationStates() {
+    return new Object[][]{{new int[0]}, {new int[]{1}}, {new int[]{1, 3, 5}}};
+  }
+
+  @Test(dataProvider = "cancellationStates")
+  public void testCancellationBetweenPublicPullsIncludesLatchedEof(int[] 
docIds) {
+    StrictDocIdSet docIdSet = new StrictDocIdSet(docIds);
+    DocIdSetOperator operator = new DocIdSetOperator(new 
FixedFilterOperator(docIdSet), 2);
+    QueryExecutionContext executionContext = 
QueryExecutionContext.forSseTest();
+    ThreadAccountant accountant = mock(ThreadAccountant.class);
+    try (QueryThreadContext ignore = QueryThreadContext.open(executionContext, 
accountant)) {
+      DocIdSetBlock firstBlock = operator.nextBlock();
+      if (docIds.length == 0) {
+        assertNull(firstBlock);
+      } else {
+        assertDocIds(firstBlock, Arrays.copyOf(docIds, Math.min(docIds.length, 
2)));
+      }
+      int nextCallsBeforeCancellation = docIdSet._nextCalls;
+      assertTrue(executionContext.terminate(QueryErrorCode.QUERY_CANCELLATION, 
"cancel between document blocks"));
+      TerminationException failure = expectThrows(TerminationException.class, 
operator::nextBlock);
+      assertSame(failure, executionContext.getTerminateException());
+      assertEquals(docIdSet._nextCalls, nextCallsBeforeCancellation);
+      assertEquals(docIdSet._batchCalls, 1);
+      verify(accountant).sampleUsage();
+    }
+  }
+
+  @Test
+  public void testCancellationBeforeFirstPullDoesNotInitializeFilter() {
+    StrictDocIdSet docIdSet = new StrictDocIdSet(new int[]{1});
+    FixedFilterOperator filter = new FixedFilterOperator(docIdSet);
+    DocIdSetOperator operator = new DocIdSetOperator(filter, 2);
+    QueryExecutionContext executionContext = 
QueryExecutionContext.forSseTest();
+    ThreadAccountant accountant = mock(ThreadAccountant.class);
+    try (QueryThreadContext ignore = QueryThreadContext.open(executionContext, 
accountant)) {
+      assertTrue(executionContext.terminate(QueryErrorCode.QUERY_CANCELLATION, 
"cancel before document blocks"));
+      TerminationException failure = expectThrows(TerminationException.class, 
operator::nextBlock);
+      assertSame(failure, executionContext.getTerminateException());
+      assertEquals(filter._filterCalls, 0);
+      assertEquals(docIdSet._iteratorCalls, 0);
+      assertEquals(docIdSet._batchCalls, 0);
+      verify(accountant, never()).sampleUsage();
+    }
+  }
+
+  @Test
+  public void testScratchRemainsSharedAcrossOperatorsOnOneThread() {
+    DocIdSetOperator first = new DocIdSetOperator(new 
MatchAllFilterOperator(5), 2);
+    DocIdSetOperator second = new DocIdSetOperator(new FixedFilterOperator(
+        new StrictDocIdSet(new int[]{10, 12, 14})), 2);
+    try (QueryThreadContext ignore = QueryThreadContext.openForSseTest()) {
+      DocIdSetBlock firstBlock = first.nextBlock();
+      assertDocIds(firstBlock, 0, 1);
+      int[] retainedCopy = Arrays.copyOf(firstBlock.getDocIds(), 
firstBlock.getLength());
+      DocIdSetBlock secondBlock = second.nextBlock();
+      assertDocIds(secondBlock, 10, 12);
+      assertSame(firstBlock.getDocIds(), secondBlock.getDocIds());
+      assertDocIds(firstBlock, 10, 12);
+      assertEquals(retainedCopy, new int[]{0, 1});
+
+      DocIdSetBlock nextFirstBlock = first.nextBlock();
+      assertDocIds(nextFirstBlock, 2, 3);
+      assertSame(nextFirstBlock.getDocIds(), firstBlock.getDocIds());
+      assertDocIds(secondBlock, 2, 3);
+      assertEquals(retainedCopy, new int[]{0, 1});
+    }
+  }
+
+  @Test
+  public void testScratchIsIsolatedBetweenThreads()
+      throws Exception {
+    ExecutorService executor = Executors.newSingleThreadExecutor();
+    try (QueryThreadContext ignore = QueryThreadContext.openForSseTest()) {
+      DocIdSetOperator operator = new DocIdSetOperator(new 
MatchAllFilterOperator(4), 2);
+      DocIdSetBlock localBlock = operator.nextBlock();
+      assertDocIds(localBlock, 0, 1);
+      DocIdSetBlock otherBlock = executor.submit(() -> {
+        try (QueryThreadContext otherContext = 
QueryThreadContext.openForSseTest()) {
+          return new DocIdSetOperator(new FixedFilterOperator(new 
StrictDocIdSet(new int[]{10, 12})), 2).nextBlock();
+        }
+      }).get(10, TimeUnit.SECONDS);
+      assertDocIds(otherBlock, 10, 12);
+      assertNotSame(localBlock.getDocIds(), otherBlock.getDocIds());
+      assertDocIds(operator.nextBlock(), 2, 3);
+      assertDocIds(otherBlock, 10, 12);
+    } finally {
+      executor.shutdownNow();
+    }
+  }
+
+  private static void assertDocIds(DocIdSetBlock block, int... expected) {
+    assertNotNull(block);
+    assertEquals(block.getLength(), expected.length);
+    assertEquals(Arrays.copyOf(block.getDocIds(), block.getLength()), 
expected);
+  }
+
+  /// A filter with an observable one-time initialization and the real public 
operator checkpoint.
+  private static final class FixedFilterOperator extends BaseFilterOperator {
+    private final BlockDocIdSet _docIdSet;
+    private int _filterCalls;
+
+    private FixedFilterOperator(BlockDocIdSet docIdSet) {
+      super(32, false);
+      _docIdSet = docIdSet;
+    }
+
+    @Override
+    protected BlockDocIdSet getTrues() {
+      _filterCalls++;
+      return _docIdSet;
+    }
+
+    @Override
+    public String toExplainString() {
+      return "TEST_FILTER";
+    }
+
+    @Override
+    public List<BaseFilterOperator> getChildOperators() {
+      return List.of();
+    }
+  }
+
+  /// Scalar-backed fixture that rejects all iterator operations after its 
first terminal result.
+  private static final class StrictDocIdSet implements BlockDocIdSet, 
BlockDocIdIterator {
+    private final int[] _docIds;
+    private final long[] _scanTotals;
+    private int _iteratorCalls;
+    private int _nextCalls;
+    private int _batchCalls;
+    private boolean _exhausted;
+
+    private StrictDocIdSet(int[] docIds) {
+      this(docIds, new long[docIds.length + 1]);
+    }
+
+    private StrictDocIdSet(int[] docIds, long[] scanTotals) {
+      _docIds = docIds;
+      _scanTotals = scanTotals;
+    }
+
+    @Override
+    public BlockDocIdIterator iterator() {
+      assertEquals(++_iteratorCalls, 1, "The filter iterator must only be 
acquired once");
+      return this;
+    }
+
+    @Override
+    public int next() {
+      assertFalse(_exhausted, "Iterator called after terminal EOF");
+      int position = _nextCalls++;
+      if (position == _docIds.length) {
+        _exhausted = true;
+        return Constants.EOF;
+      }
+      return _docIds[position];
+    }
+
+    @Override
+    public int nextBatch(int[] output, int maxDocs) {
+      assertFalse(_exhausted, "Batch called after terminal EOF");
+      _batchCalls++;
+      return BlockDocIdIterator.super.nextBatch(output, maxDocs);
+    }
+
+    @Override
+    public int advance(int targetDocId) {
+      throw new AssertionError("Document block pulls must not advance the 
iterator");
+    }
+
+    @Override
+    public long getNumEntriesScannedInFilter() {
+      return _nextCalls == 0 ? 0 : _scanTotals[_nextCalls - 1];
+    }
+  }
+}
diff --git 
a/pinot-core/src/test/java/org/apache/pinot/core/operator/dociditerators/DocIdIteratorBatchTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/core/operator/dociditerators/DocIdIteratorBatchTest.java
new file mode 100644
index 00000000000..12df53071bd
--- /dev/null
+++ 
b/pinot-core/src/test/java/org/apache/pinot/core/operator/dociditerators/DocIdIteratorBatchTest.java
@@ -0,0 +1,235 @@
+/**
+ * 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.core.operator.dociditerators;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.Supplier;
+import java.util.stream.IntStream;
+import org.apache.pinot.core.common.BlockDocIdIterator;
+import org.apache.pinot.core.plan.DocIdSetPlanNode;
+import org.apache.pinot.segment.spi.Constants;
+import org.apache.pinot.spi.utils.Pairs.IntPair;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+/// Exercises the shared cursor, caller-owned output and terminal-batch 
contract of document-id iterators.
+/// Each test uses its own mutable iterator and may run independently.
+public class DocIdIteratorBatchTest {
+  private static final int UNWRITTEN = -123456;
+
+  @DataProvider
+  public Object[][] batchBoundaries() {
+    int maxDocPerCall = DocIdSetPlanNode.MAX_DOC_PER_CALL;
+    return new Object[][]{
+        {1, 0}, {1, 1}, {1, 2}, {2, 1}, {2, 2}, {2, 3},
+        {maxDocPerCall, maxDocPerCall - 1}, {maxDocPerCall, maxDocPerCall}, 
{maxDocPerCall, maxDocPerCall + 1}
+    };
+  }
+
+  @Test(dataProvider = "batchBoundaries")
+  public void testBatchBoundaries(int maxDocs, int numDocs) {
+    int[] expected = IntStream.range(0, numDocs).toArray();
+    assertBatches(new MatchAllDocIdIterator(numDocs), maxDocs, expected);
+    assertBatches(new ScalarIterator(expected), maxDocs, expected);
+    if (numDocs > 0) {
+      assertBatches(new SortedDocIdIterator(List.of(new IntPair(0, numDocs - 
1))), maxDocs, expected);
+    } else {
+      assertBatches(EmptyDocIdIterator.getInstance(), maxDocs, expected);
+    }
+  }
+
+  @DataProvider
+  public Object[][] sortedRanges() {
+    return new Object[][]{
+        {List.of(new IntPair(7, 7)), new int[]{7}},
+        {List.of(new IntPair(1, 2), new IntPair(3, 3), new IntPair(4, 6)), new 
int[]{1, 2, 3, 4, 5, 6}},
+        {List.of(new IntPair(1, 3), new IntPair(8, 11), new IntPair(18, 20)),
+            new int[]{1, 2, 3, 8, 9, 10, 11, 18, 19, 20}},
+        {List.of(new IntPair(Integer.MAX_VALUE - 8, Integer.MAX_VALUE - 7),
+            new IntPair(Integer.MAX_VALUE - 4, Integer.MAX_VALUE - 1)),
+            new int[]{Integer.MAX_VALUE - 8, Integer.MAX_VALUE - 7, 
Integer.MAX_VALUE - 4,
+                Integer.MAX_VALUE - 3, Integer.MAX_VALUE - 2, 
Integer.MAX_VALUE - 1}}
+    };
+  }
+
+  @Test(dataProvider = "sortedRanges")
+  public void testSortedRangeTransitions(List<IntPair> ranges, int[] expected) 
{
+    for (int maxDocs : new int[]{1, 2, 3, 4, 256}) {
+      assertBatches(new SortedDocIdIterator(ranges), maxDocs, expected);
+    }
+  }
+
+  @Test
+  public void testSortedScalarAdvanceAndBatchShareCursor() {
+    BlockDocIdIterator iterator = new SortedDocIdIterator(
+        List.of(new IntPair(1, 3), new IntPair(8, 11), new IntPair(18, 20)));
+    assertEquals(iterator.next(), 1);
+    assertBatch(iterator, 2, 2, 3);
+    assertEquals(iterator.advance(5), 8);
+    assertBatch(iterator, 2, 9, 10);
+    assertEquals(iterator.next(), 11);
+    assertBatch(iterator, 1, 18);
+    assertEquals(iterator.advance(20), 20);
+    assertBatch(iterator, 2);
+  }
+
+  @Test
+  public void testMatchAllScalarAdvanceAndBatchShareCursor() {
+    BlockDocIdIterator iterator = new MatchAllDocIdIterator(13);
+    assertEquals(iterator.next(), 0);
+    assertBatch(iterator, 3, 1, 2, 3);
+    assertEquals(iterator.advance(7), 7);
+    assertBatch(iterator, 2, 8, 9);
+    assertEquals(iterator.next(), 10);
+    assertBatch(iterator, 3, 11, 12);
+  }
+
+  @Test
+  public void testMatchAllNearMaximumDocumentId() {
+    BlockDocIdIterator iterator = new MatchAllDocIdIterator(Integer.MAX_VALUE);
+    assertEquals(iterator.advance(Integer.MAX_VALUE - 4), Integer.MAX_VALUE - 
4);
+    assertBatch(iterator, 4, Integer.MAX_VALUE - 3, Integer.MAX_VALUE - 2, 
Integer.MAX_VALUE - 1);
+  }
+
+  @Test
+  public void testDefaultDoesNotLookAheadOrRetainOutput() {
+    ScalarIterator iterator = new ScalarIterator(new int[]{1, 2, 3, 8, 9});
+    int[] output = new int[2];
+    assertEquals(iterator.nextBatch(output, 2), 2);
+    assertEquals(output, new int[]{1, 2});
+    assertEquals(iterator._numNextCalls, 2);
+    // Changing caller-owned storage cannot change the iterator's next result.
+    Arrays.fill(output, UNWRITTEN);
+    assertEquals(iterator.next(), 3);
+    assertEquals(iterator.advance(8), 8);
+    assertBatch(iterator, 2, 9);
+    assertEquals(iterator._numNextCalls, 6);
+  }
+
+  @DataProvider
+  public Object[][] fallbackIterators() {
+    Supplier<BlockDocIdIterator> bitmap = () -> bitmap(1, 2, 3, 8, 9, 10, 11, 
18, 19, 20);
+    Supplier<BlockDocIdIterator> and = () -> new AndDocIdIterator(new 
BlockDocIdIterator[]{
+        bitmap(1, 2, 3, 8, 9, 10, 18, 19, 20), bitmap(0, 2, 3, 4, 9, 10, 11, 
19, 20)});
+    Supplier<BlockDocIdIterator> or = () -> new OrDocIdIterator(new 
BlockDocIdIterator[]{
+        bitmap(1, 3, 8, 9, 18, 20), bitmap(2, 3, 10, 11, 19, 20)});
+    Supplier<BlockDocIdIterator> not = () -> new NotDocIdIterator(bitmap(0, 3, 
7, 9), 12);
+    Supplier<BlockDocIdIterator> notOverOr = () -> new NotDocIdIterator(new 
OrDocIdIterator(
+        new BlockDocIdIterator[]{bitmap(0, 3, 7, 9), bitmap(1, 3, 8, 10)}), 
12);
+    Supplier<BlockDocIdIterator> fullExclusion = () -> new 
NotDocIdIterator(bitmap(0, 1, 2, 3), 4);
+    return new Object[][]{
+        {bitmap, new int[]{1, 2, 3, 8, 9, 10, 11, 18, 19, 20}},
+        {and, new int[]{2, 3, 9, 10, 19, 20}},
+        {or, new int[]{1, 2, 3, 8, 9, 10, 11, 18, 19, 20}},
+        {not, new int[]{1, 2, 4, 5, 6, 8, 10, 11}},
+        {notOverOr, new int[]{2, 4, 5, 6, 11}},
+        {fullExclusion, new int[0]}
+    };
+  }
+
+  @Test(dataProvider = "fallbackIterators")
+  public void testDefaultFallbacks(Supplier<BlockDocIdIterator> factory, int[] 
expected) {
+    for (int maxDocs : new int[]{1, 2, 3, 256}) {
+      assertBatches(factory.get(), maxDocs, expected);
+    }
+    BlockDocIdIterator scalar = factory.get();
+    for (int docId : expected) {
+      assertEquals(scalar.next(), docId);
+    }
+    assertEquals(scalar.next(), Constants.EOF);
+
+    // Compare scalar and batched progress while alternately skipping and 
requesting documents.
+    if (expected.length > 5) {
+      BlockDocIdIterator mixed = factory.get();
+      scalar = factory.get();
+      assertEquals(mixed.next(), scalar.next());
+      assertEquals(mixed.advance(expected[2]), scalar.advance(expected[2]));
+      assertBatch(mixed, 2, scalar.next(), scalar.next());
+      assertEquals(mixed.advance(expected[expected.length - 1]), 
scalar.advance(expected[expected.length - 1]));
+      assertBatch(mixed, 2);
+      assertEquals(scalar.next(), Constants.EOF);
+    }
+  }
+
+  private static BitmapDocIdIterator bitmap(int... docIds) {
+    MutableRoaringBitmap bitmap = new MutableRoaringBitmap();
+    bitmap.add(docIds);
+    return new BitmapDocIdIterator(bitmap, 32);
+  }
+
+  private static void assertBatches(BlockDocIdIterator iterator, int maxDocs, 
int[] expected) {
+    int offset = 0;
+    while (true) {
+      int size = Math.min(maxDocs, expected.length - offset);
+      assertBatch(iterator, maxDocs, Arrays.copyOfRange(expected, offset, 
offset + size));
+      offset += size;
+      if (size < maxDocs) {
+        break;
+      }
+    }
+  }
+
+  private static void assertBatch(BlockDocIdIterator iterator, int maxDocs, 
int... expected) {
+    int[] output = new int[maxDocs + 2];
+    Arrays.fill(output, UNWRITTEN);
+    assertEquals(iterator.nextBatch(output, maxDocs), expected.length);
+    assertEquals(Arrays.copyOf(output, expected.length), expected);
+    for (int i = expected.length; i < output.length; i++) {
+      assertEquals(output[i], UNWRITTEN);
+    }
+  }
+
+  /// Models the public scalar contract, including its prohibition on post-EOF 
calls.
+  private static final class ScalarIterator implements BlockDocIdIterator {
+    private final int[] _docIds;
+    private int _position;
+    private int _numNextCalls;
+    private boolean _exhausted;
+
+    private ScalarIterator(int[] docIds) {
+      _docIds = docIds;
+    }
+
+    @Override
+    public int next() {
+      if (_exhausted) {
+        throw new IllegalStateException("Iterator called after EOF");
+      }
+      _numNextCalls++;
+      if (_position == _docIds.length) {
+        _exhausted = true;
+        return Constants.EOF;
+      }
+      return _docIds[_position++];
+    }
+
+    @Override
+    public int advance(int targetDocId) {
+      while (_position < _docIds.length && _docIds[_position] < targetDocId) {
+        _position++;
+      }
+      return next();
+    }
+  }
+}
diff --git 
a/pinot-core/src/test/java/org/apache/pinot/queries/DocIdBatchNullQueriesTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/queries/DocIdBatchNullQueriesTest.java
new file mode 100644
index 00000000000..b7c6dadf774
--- /dev/null
+++ 
b/pinot-core/src/test/java/org/apache/pinot/queries/DocIdBatchNullQueriesTest.java
@@ -0,0 +1,212 @@
+/**
+ * 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.queries;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.function.IntPredicate;
+import javax.annotation.Nullable;
+import org.apache.commons.io.FileUtils;
+import org.apache.pinot.common.response.broker.BrokerResponseNative;
+import org.apache.pinot.common.response.broker.ResultTable;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.core.plan.DocIdSetPlanNode;
+import 
org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader;
+import 
org.apache.pinot.segment.local.segment.creator.impl.SegmentIndexCreationDriverImpl;
+import org.apache.pinot.segment.local.segment.readers.GenericRowRecordReader;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.apache.pinot.segment.spi.creator.SegmentGeneratorConfig;
+import org.apache.pinot.segment.spi.creator.SegmentVersion;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.utils.ReadMode;
+import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertTrue;
+
+
+/// Verifies nullable group aggregation across full and tail doc-id blocks and 
separately executed server responses.
+/// The fixture belongs to this test instance; it has no shared mutable state 
with other query tests.
+public class DocIdBatchNullQueriesTest extends BaseQueriesTest {
+  private static final String TABLE = "DocIdBatchNullQueriesTest";
+  private static final int FIRST_ROWS = DocIdSetPlanNode.MAX_DOC_PER_CALL + 17;
+  private static final int TOTAL_ROWS = FIRST_ROWS + 3;
+  private static final Map<String, String> OPTIONS = 
Map.of("enableNullHandling", "true", "skipStarTree", "true",
+      "maxExecutionThreads", "1", "numGroupsLimit", "100");
+
+  private final List<IndexSegment> _segments = new ArrayList<>(2);
+  private File _directory;
+
+  @BeforeClass
+  public void setUp()
+      throws Exception {
+    _directory = 
Files.createTempDirectory("doc-id-batch-null-queries").toFile();
+    TableConfig tableConfig = new 
TableConfigBuilder(TableType.OFFLINE).setTableName(TABLE).setSortedColumn("s")
+        .setNoDictionaryColumns(List.of("m")).build();
+    Schema schema = new 
Schema.SchemaBuilder().setSchemaName(TABLE).addSingleValueDimension("s", 
DataType.INT)
+        .addSingleValueDimension("g", DataType.INT).addMetric("m", 
DataType.DOUBLE).build();
+    for (int segmentId = 0; segmentId < 2; segmentId++) {
+      int start = segmentId == 0 ? 0 : FIRST_ROWS;
+      int end = segmentId == 0 ? FIRST_ROWS : TOTAL_ROWS;
+      List<GenericRow> rows = new ArrayList<>(end - start);
+      for (int id = start; id < end; id++) {
+        GenericRow row = new GenericRow();
+        row.putValue("s", id);
+        row.putValue("g", group(id));
+        row.putValue("m", metric(id));
+        rows.add(row);
+      }
+      String segmentName = "segment-" + segmentId;
+      SegmentGeneratorConfig config = new SegmentGeneratorConfig(tableConfig, 
schema);
+      config.setOutDir(_directory.getPath());
+      config.setSegmentName(segmentName);
+      config.setSegmentVersion(SegmentVersion.v3);
+      config.setDefaultNullHandlingEnabled(true);
+      SegmentIndexCreationDriverImpl driver = new 
SegmentIndexCreationDriverImpl();
+      try (GenericRowRecordReader reader = new GenericRowRecordReader(rows)) {
+        driver.init(config, reader);
+        driver.build();
+      }
+      IndexSegment segment = ImmutableSegmentLoader.load(new File(_directory, 
segmentName), ReadMode.mmap);
+      _segments.add(segment);
+      
assertTrue(segment.getDataSource("s").getDataSourceMetadata().isSorted());
+      assertNotNull(segment.getDataSource("s").getDictionary());
+      assertNull(segment.getDataSource("m").getDictionary());
+      assertNotNull(segment.getDataSource("m").getNullValueVector());
+      assertTrue(segment.getStarTrees() == null || 
segment.getStarTrees().isEmpty());
+    }
+  }
+
+  @AfterClass(alwaysRun = true)
+  public void tearDown()
+      throws Exception {
+    for (IndexSegment segment : _segments) {
+      segment.destroy();
+    }
+    if (_directory != null) {
+      FileUtils.deleteDirectory(_directory);
+    }
+  }
+
+  @Override
+  protected String getFilter() {
+    return "";
+  }
+
+  @Override
+  protected IndexSegment getIndexSegment() {
+    return _segments.get(0);
+  }
+
+  @Override
+  protected List<IndexSegment> getIndexSegments() {
+    return _segments;
+  }
+
+  @Override
+  protected List<List<IndexSegment>> getDistinctInstances() {
+    return List.of(List.of(_segments.get(0)), List.of(_segments.get(1)));
+  }
+
+  @DataProvider
+  public Object[][] filters() {
+    IntPredicate all = id -> true;
+    IntPredicate range = id -> id >= 5;
+    IntPredicate gaps = id -> id != 7 && id != 10000;
+    return new Object[][]{
+        {"", all}, {" WHERE s >= 5", range}, {" WHERE s NOT IN (7, 10000)", 
gaps}
+    };
+  }
+
+  @Test(dataProvider = "filters")
+  public void testNullableGroupByAcrossBatches(String filter, IntPredicate 
matches) {
+    String query = "SELECT g AS group_key, SUM(m) AS total_value, AVG(m) AS 
average_value,"
+        + " COUNT(*) AS row_count, COUNT(m) AS value_count FROM " + TABLE + 
filter
+        + " GROUP BY g ORDER BY g NULLS FIRST LIMIT 100";
+    Map<Integer, ExpectedGroup> groups = new 
TreeMap<>(Comparator.nullsFirst(Comparator.naturalOrder()));
+    long numDocs = 0;
+    for (int id = 0; id < TOTAL_ROWS; id++) {
+      if (matches.test(id)) {
+        numDocs++;
+        ExpectedGroup expected = groups.computeIfAbsent(group(id), ignored -> 
new ExpectedGroup());
+        expected._numRows++;
+        Double metric = metric(id);
+        if (metric != null) {
+          expected._sum += metric;
+          expected._numValues++;
+        }
+      }
+    }
+    List<Object[]> expectedRows = new ArrayList<>(groups.size());
+    groups.forEach((key, values) -> expectedRows.add(new Object[]{key,
+        values._numValues == 0 ? null : values._sum,
+        values._numValues == 0 ? null : values._sum / values._numValues, 
values._numRows, values._numValues}));
+
+    BrokerResponseNative response = getBrokerResponse(query, OPTIONS);
+    assertFalse(response.isPartialResult(), 
response.getExceptions().toString());
+    assertEquals(response.getTotalDocs(), TOTAL_ROWS);
+    assertEquals(response.getNumDocsScanned(), numDocs);
+    assertEquals(response.getNumEntriesScannedInFilter(), 0L);
+    assertEquals(response.getNumEntriesScannedPostFilter(), numDocs * 2);
+    ResultTable result = response.getResultTable();
+    assertNotNull(result);
+    assertEquals(result.getDataSchema().getColumnNames(),
+        new String[]{"group_key", "total_value", "average_value", "row_count", 
"value_count"});
+    assertEquals(result.getDataSchema().getColumnDataTypes(), new 
ColumnDataType[]{ColumnDataType.INT,
+        ColumnDataType.DOUBLE, ColumnDataType.DOUBLE, ColumnDataType.LONG, 
ColumnDataType.LONG});
+    assertEquals(result.getRows().size(), expectedRows.size());
+    for (int row = 0; row < expectedRows.size(); row++) {
+      assertEquals(result.getRows().get(row), expectedRows.get(row), "Row " + 
row + " for " + query);
+    }
+  }
+
+  @Nullable
+  private static Integer group(int id) {
+    return id % 11 == 0 ? null : id % 4;
+  }
+
+  @Nullable
+  private static Double metric(int id) {
+    // Group 3 has only null metrics; other groups mix null and non-null 
values.
+    return id % 4 == 3 || id % 7 == 0 ? null : (id % 17 - 8) * 0.25;
+  }
+
+  /// Independent exact-quarter arithmetic oracle, including rows excluded by 
COUNT(metric).
+  private static final class ExpectedGroup {
+    private double _sum;
+    private long _numRows;
+    private long _numValues;
+  }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to