Skip to content

Enforce scan budgets between restricted scan chunks - #20231

Open
xiangfu0 wants to merge 1 commit into
apache:masterfrom
xiangfu0:xiangfu0/codex2/rls-limit-streaming-20261111
Open

xiangfu0 wants to merge 1 commit into
apache:masterfrom
xiangfu0:xiangfu0/codex2/rls-limit-streaming-20261111

Conversation

@xiangfu0

@xiangfu0 xiangfu0 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #19589. An eligible row-level security query can now scan its authorized candidates lazily. Each chunk updates the scan-cost counter and checks the query budget before yielding matches or starting another chunk. This also covers chunks with zero matches.

The restricted scan and the block pull share the same cumulative counter, so each scanned entry is charged once, including work done on the final pull. The budget check reuses the existing scan-killing strategy and the iterator closes its readers on termination.

Validation

  • Added a regression for budget enforcement on an unmatched chunk and strengthened coverage for exact accounting through EOF.
  • Passed 89 focused TestNG cases across document iteration, RLS filtering, and query killing. Compiled the affected sources with JDK 25 against cached dependencies.
  • Passed the Pinot Core Spotless, Checkstyle, and license checks.

@xiangfu0 xiangfu0 added query Related to query processing performance Related to performance optimization auth Related to authentication and authorization test-coverage Adds or improves test coverage labels Nov 11, 2026
@codecov-commenter

codecov-commenter commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 71.47%. Comparing base (38f0081) to head (e83cf4b).

Additional details and impacted files
@@            Coverage Diff            @@
##             master   #20231   +/-   ##
=========================================
  Coverage     71.47%   71.47%           
  Complexity     1639     1639           
=========================================
  Files          3615     3615           
  Lines        244521   244532   +11     
  Branches      39767    39768    +1     
=========================================
+ Hits         174764   174785   +21     
+ Misses        56572    56568    -4     
+ Partials      13185    13179    -6     
Flag Coverage Δ
integration 100.00% <ø> (ø)
integration1 100.00% <ø> (ø)
integration2 0.00% <ø> (ø)
java-25 71.47% <100.00%> (+<0.01%) ⬆️
lane-a 100.00% <ø> (ø)
lane-b 0.00% <ø> (ø)
temurin 71.47% <100.00%> (+<0.01%) ⬆️
unittests 71.47% <100.00%> (+<0.01%) ⬆️
unittests1 61.24% <100.00%> (+0.02%) ⬆️
unittests2 42.96% <8.33%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

gortiz added a commit to gortiz/pinot that referenced this pull request Nov 13, 2026
A streaming AND restriction keeps its scan readers open until the
candidate stream ends. A selection that fills its LIMIT never gets
there, so the readers stayed open until the segment plan was dropped.

- DocIdSetOperator implements AutoCloseable. close() closes the filter
  iterator when it has not reached EOF, and later nextBlock() calls
  return null.
- SelectionOnlyOperator closes its DocIdSetOperator once it has its
  rows. SelectionPlanNode passes it through the new
  ProjectPlanNode#createDocIdSetOperator() and
  ProjectPlanNode#run(DocIdSetOperator).
- AndDocIdIterator and OrDocIdIterator propagate close() to their
  children, so the close reaches a nested RestrictedScanDocIdIterator.
- BenchmarkAndRestrictionPushdown adds the SINGLE_SCAN shape (a bitmap
  AND one scan, the row-level security case) and runs INDEXED_OR.

The approach follows apache#20231.
@xiangfu0
xiangfu0 force-pushed the xiangfu0/codex2/rls-limit-streaming-20261111 branch from 3de7e41 to e2daec5 Compare November 19, 2026 10:05
xiangfu0 added a commit that referenced this pull request Nov 25, 2026
* SPIKE: streaming restriction kernel (option 4)

Adds the two pieces the lazy restriction needs, without wiring them in:

- ScanBasedDocIdIterator#matchDocIds(int[], int): a re-entrant per-chunk
  kernel. Unlike applyAnd it does not consume the iterator, so it can be
  called once per chunk. SVScanDocIdIterator delegates to the in-place
  compaction its ValueMatcher already does; MVScanDocIdIterator loops
  doesValueMatch; everything else gets a default built on applyAnd.

- RestrictedScanDocIdIterator: drives a scan from an upstream candidate
  stream a chunk at a time, so the restriction reaches the scan without
  materializing the result.

Measured on the stub scan: draining the stream costs exactly what the
eager applyAnd costs, while stopping after 10 documents costs one chunk
(256 entries) instead of 100000. advance() moves the candidate stream
rather than scanning forward from the target, which is the behaviour that
makes lazily-driven scans pathological today.

Not wired into AndDocIdSet. Spike only.

Refs #19339

* SPIKE: benchmark streaming against eager restriction

Adds a STREAMING arm to BenchmarkAndRestrictionPushdown, modelling what a
streaming push-down produces by assembling the tree from the spike's
RestrictedScanDocIdIterator, since the kernel is not wired into
AndDocIdSet yet. Setup asserts that all three strategies return identical
documents, because a hand-assembled model that is subtly wrong would show
up as an impressive and meaningless number.

Time and allocation as a ratio of master's behaviour (2M docs, chunk 256):

  shape         consume sel     eager        streaming   eager    streaming
                                (time)       (time)      (alloc)  (alloc)
  SCAN_IN_OR    DRAIN   0.01      0.03x         0.03x     0.10x     0.06x
  SCAN_IN_OR    DRAIN   0.5       0.66x         1.21x     1.14x     0.27x
  SCAN_IN_OR    LIMIT   0.01      0.02x         0.01x     0.10x     0.06x
  SCAN_IN_OR    LIMIT   0.5       0.58x         0.04x     1.14x     0.26x
  SCAN_ONLY_OR  DRAIN   0.01      0.32x         0.40x    21.97x     1.41x
  SCAN_ONLY_OR  DRAIN   0.5       0.34x         0.53x   232.27x     1.17x
  SCAN_ONLY_OR  LIMIT   0.01    138.85x         2.23x    25.04x     1.33x
  SCAN_ONLY_OR  LIMIT   0.5    7925.64x         3.27x   383.31x     1.33x

Streaming removes the cliff: the worst case goes from 7926x slower to
3.3x, and allocation from 383x to 1.3x. It is also far better wherever the
consumer stops early, because it keeps the early termination the eager
path destroys.

Eager is still the better strategy for a full drain, though -- 0.66x versus
1.21x on SCAN_IN_OR at high candidate density, where chunking costs more
than it saves. So streaming does not replace the mode, it changes what the
mode chooses: eager when the query will read every matching document,
streaming when it may stop early.

Caveats: the model precomputes the bitmap intersections a real
implementation would also compute; chunk size is fixed at 256; and the scan
is an SVScanDocIdIterator, so this says nothing yet about an expression
scan, which builds a ProjectionOperator per chunk.

Refs #19339

* SPIKE: bound matchDocIds chunks to the scan batch size

SVScanDocIdIterator#matchDocIds passed the whole chunk to its ValueMatcher, whose value buffers have the batch size
of the iterator. RestrictedScanDocIdIterator accepts any chunk size, so a chunk larger than that batch size overran
the buffers. Match a larger chunk one batch at a time through a lazily allocated batch buffer, compacting the matching
document ids to the front of the chunk.

RestrictedScanDocIdIteratorTest#testChunkLargerThanTheScanBatchSize drives a 1041-document chunk through a
256-document SVScanDocIdIterator.

* Stream the AND restriction push-down for LIMIT queries

Add a STREAMING value to andRestrictionPushdownMode. Under STREAMING, an
AND evaluates its scans and its composite children (OR, AND, NOT) on the
candidate bitmap one chunk at a time, instead of materializing every step.
A selection with a LIMIT then reads only the chunks it needs, also under
row-level security, and the user filter still runs only on allowed rows.

- BlockDocIdSet#restrictedIterator(ImmutableRoaringBitmap) is the lazy
  counterpart of applyAnd. AndDocIdSet, OrDocIdSet and NotDocIdSet
  implement it; NOT uses the new RestrictedNotDocIdIterator.
- RestrictedScanDocIdIterator applies several scans per chunk. The chunk
  grows from 256 to MAX_DOC_PER_CALL, resets when advance() skips
  candidates, checks query termination per chunk and closes every scan at
  EOF.
- ScanBasedDocIdIterator#matchDocIds is abstract.
  ExpressionScanDocIdIterator implements it with one projection per chunk.
- AndRestrictionPushdown (OFF, EAGER, STREAMING plus the documents to read)
  replaces the boolean flag in the filter operators. An AND falls back to
  EAGER when LIMIT + OFFSET is not less than its candidate count. A null
  value means OFF, as the boolean it replaces defaulted to false.
- AUTO picks STREAMING for selection queries without ORDER BY, EAGER for
  aggregation and group-by, and OFF for everything else, DISTINCT
  included. Under RLS, NEVER resolves like AUTO and OFF becomes EAGER.
- DocIdSetOperator also reports the scan cost on the call that returns no
  document, because a lazy filter can scan the rest of the segment there.
- BenchmarkAndRestrictionPushdown measures the real AndDocIdSet in the
  three strategies.

A server that does not know STREAMING rejects the query option, so use it
only after every server is upgraded. Closing the scans when the consumer
stops early is left for a follow-up.

* Close the filter scans when a selection stops at its LIMIT

A streaming AND restriction keeps its scan readers open until the
candidate stream ends. A selection that fills its LIMIT never gets
there, so the readers stayed open until the segment plan was dropped.

- DocIdSetOperator implements AutoCloseable. close() closes the filter
  iterator when it has not reached EOF, and later nextBlock() calls
  return null.
- SelectionOnlyOperator closes its DocIdSetOperator once it has its
  rows. SelectionPlanNode passes it through the new
  ProjectPlanNode#createDocIdSetOperator() and
  ProjectPlanNode#run(DocIdSetOperator).
- AndDocIdIterator and OrDocIdIterator propagate close() to their
  children, so the close reaches a nested RestrictedScanDocIdIterator.
- BenchmarkAndRestrictionPushdown adds the SINGLE_SCAN shape (a bitmap
  AND one scan, the row-level security case) and runs INDEXED_OR.

The approach follows #20231.

* Benchmark the streaming push-down at query level and by chunk size

- BenchmarkRowLevelSecurityLimitQueries runs single-stage queries under
  row-level security end to end on 4 segments of 1M rows: a scan, an
  expression scan, an OR, an OR with fewer matches than the LIMIT, and
  a COUNT as a control. It compares the eager push-down (ALWAYS) with
  the default (NEVER), which streams a selection under RLS, and prints
  numEntriesScannedInFilter for each mode.
- BenchmarkRestrictedScanChunkSize runs RestrictedScanDocIdIterator
  with first chunk sizes from 64 to MAX_DOC_PER_CALL.
- RestrictedScanDocIdIterator gets a constructor that takes the first
  chunk size. The other constructor keeps MIN_CHUNK_SIZE.

* Constrain restriction streaming and close filter readers

* Defer the first pull of a negated document iterator

---------

Co-authored-by: Gonzalo Ortiz <1913993+gortiz@users.noreply.github.com>
Co-authored-by: Xiang Fu <xiangfu@startree.ai>
@xiangfu0
xiangfu0 force-pushed the xiangfu0/codex2/rls-limit-streaming-20261111 branch from e2daec5 to e83cf4b Compare November 25, 2026 01:54
@xiangfu0 xiangfu0 changed the title Stream eligible RLS scans for unordered LIMIT selections Enforce scan budgets between restricted scan chunks Nov 25, 2026
@xiangfu0
xiangfu0 marked this pull request as ready for review November 25, 2026 03:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth Related to authentication and authorization performance Related to performance optimization query Related to query processing test-coverage Adds or improves test coverage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants