Repository navigation
Description
Description
When a filter has the shape P AND (A OR B), Pinot evaluates the (A OR B) subtree independently of P. If P is highly selective, and a branch of the OR contains a predicate with no index — for example IN_ID_SET(...), produced by IN_SUBQUERY, which is evaluated per document through ExpressionScanDocIdIterator — that predicate is evaluated for every document matching the branch, not only for the documents that satisfy P.
Duplicating P inside the OR branch by hand is a sound rewrite (P ∧ (A∨B) ≡ P ∧ ((P∧A) ∨ (P∧B)), and it holds under three-valued logic because the filter only passes TRUE). Doing so makes such queries several times faster, which shows the restriction is simply not being applied.
The cost also depends on whether the branch columns have indexes
AndDocIdSet#iterator() chooses between two strategies at AndDocIdSet.java:121:
if ((numIndexBasedDocIdIterators > 0 && numScanBasedDocIdIterators > 0) || numIndexBasedDocIdIterators > 1) {
// eager: merge the index bitmaps, then scanIterator.applyAnd(docIds)
} else {
return new AndDocIdIterator(allDocIdIterators); // lazy
}- With no index-based child in the AND under the OR, the subtree stays lazy.
OrDocIdSetkeeps it lazy, the outerAndDocIdSetplaces it inremainingDocIdIterators, and the outer merged bitmap — which includesP— drives it. The expensive predicate is only evaluated at documents that already matchP. - With one or more index-based children, the eager path is taken. The branch is fully materialized as a bitmap over the whole segment, ignoring
P, before the outer AND intersects.
So adding an index to a column that appears inside an OR branch can make a query orders of magnitude slower. In a production deployment, the same query returning the same two rows went from ~500 to ~17,000,000 numEntriesScannedInFilter, and allocated 4.6 GB, after the only change was two columns in the branch gaining a range index and an inverted index respectively.
Reproduction sketch
Table events(tenant_id INT, ts LONG, kind STRING, id LONG, value DOUBLE), one selective tenant among many.
SELECT sum(value) FROM events
WHERE tenant_id = 42
AND ( ( ts >= :t0 AND ts <= :t1 AND kind = 'a'
AND IN_SUBQUERY(id, 'SELECT ID_SET(id) FROM events WHERE tenant_id = 42 AND ts >= :t2') = 0 )
OR ( ts >= :t2 AND kind = 'b' ) )Run it twice: once with no index on ts or kind, once with a range index on ts and an inverted index on kind. The second configuration is far slower and scans far more entries in the filter.
Suggested fixes
- Push the restriction down at execution time (preferred). Generalize
applyAndfromScanBasedDocIdIteratortoBlockDocIdSet, soAndDocIdSetcan pass its merged index bitmap into composite children:OrDocIdSet.applyAnd(b)= union ofchild.applyAnd(b),AndDocIdSet.applyAnd(b)= intersect starting fromb. This needs no heuristic, adds no duplicated index lookups, works at any nesting depth, and removes the eager/lazy cliff. Needs care withnumEntriesScannedInFilteraccounting,NotDocIdSet, and null handling. - Rewrite in the planner. Add a
FilterOptimizerthat distributes selective conjuncts (EQ/IN on dictionary-encoded columns) from an enclosing AND into each OR branch. Cheaper to implement and gateable behind a query option, but it is a heuristic: duplicating a predicate on a raw column doubles a scan.
Activity
waterWang commentedon Aug 24, 2026
I've opened PR #19350 to fix this issue. The fix adds a
DistributeConjunctsIntoOrFilterOptimizerthat implements the planner-based approach (option 2 from the issue): selective conjuncts (EQUALS/IN on single columns) from an enclosing AND are distributed into each OR branch, so thatP AND (A OR B)becomesP AND ((P AND A) OR (P AND B)). This ensures the OR subtree's scan-based predicates are only evaluated against documents matching the selective predicate P.alexch2000 commentedon Aug 25, 2026
We hit the same cliff, from a different direction. Instead of a subquery inside the OR, the OR is on two time ranges (day-over-day comparison) and the scan appears only on segments that lack the configured range index.
Query shape (v1 engine, realtime table, ~134K segments):
name,flow_id,action_id,device_oshave inverted indexes.tsis the time column and hasrangeIndexColumnsconfigured, but ~3% of segments are missing the index on disk (separate issue, being fixed by reload).Numbers
numEntriesScannedInFilternumDocsScannednumSegmentsProcessedrealtimeThreadMemAllocatedBytes~4,400× more filter work for ~2.3× more matched rows. Window B alone behaves like window A alone.
Verbose EXPLAIN on the OR query (all cohorts, 4,588 segments after pruning):
FILTER_RANGE_INDEXunderFILTER_ANDFILTER_OR→ 2×FILTER_RANGE_INDEXFILTER_FULL_SCANunderFILTER_ANDFILTER_OR→ 2×FILTER_FULL_SCANFILTER_EMPTYThe 83 segments account for essentially all of the 441M: ~2.7M docs × 2 predicates each, i.e. a full pass over the column per range predicate. The 44 unindexed segments whose scan sits directly under the AND cost almost nothing, because
AndDocIdSethands them the intersected inverted-index bitmap viaScanBasedDocIdIterator.applyAnd. The 83 get no candidate set becauseOrDocIdSethas no equivalent, andAndDocIdSet#iterator()callsiterator()on the OR child before it has computed anything.Two details that made this particularly sharp for us:
EmptyFilterOperatorand is dropped from the OR, so the OR only survives on segments that overlap both windows.On the two proposed fixes
+1 to option 1 (push
applyAnddown into composite doc-id sets). For our shape, #19350 as currently scoped would help only marginally: the only conjunct it can distribute isdevice__os IN ('android','ios'), which matches most rows. The selective part of the outer AND is theOR(AND(name, flow_id, action_id), AND(name, flow_id))block, which isn't a single-column EQ/IN and so wouldn't be pushed into the time-range branches.richardstartin commentedon Aug 28, 2026
@gortiz if you push the intersection down to the range index you can make use of RangeBitmap’s context parameter, which allows the range index evaluation to skip over unnecessary regions of the range index itself. This is typically much faster; RangeBitmap is being used for observability at Yandex and making use of the context parameter to push intersections down is critical to performance there.
gortiz commentedon Aug 31, 2026
I've opened #19408 implementing option 1, the execution-time push-down.
applyAndis generalized fromScanBasedDocIdIteratorup toBlockDocIdSet, so an AND hands the document ids it has matched to its composite children:OrDocIdSetunions the restricted branches,AndDocIdSetintersects starting from the candidate set,NotDocIdSetsubtracts. No heuristic, no duplicated index lookups, any nesting depth, and the eager/lazy cliff goes away rather than being routed around.It ships disabled. The push-down materializes the filter result instead of streaming it, so a query that stops at its LIMIT ends up doing the full filter work — measured on the existing suite at 21–41% more entries scanned for a selection with LIMIT, against 7–19% fewer for aggregations. Hence
andRestrictionPushdownMode:NEVER(default),AUTO(only queries that read every matching document, i.e. aggregation and group-by),ALWAYS.@alexch2000 — I think this covers your shape, and I'd appreciate a check against your data. Your query is an aggregation with a GROUP BY, so
AUTOenables it. The 83 segments where the plan isFILTER_OR → 2× FILTER_FULL_SCANshould now receive the candidate set fromOR(cohorts) ∩ device_osinstead of evaluating each range predicate over the whole column. Worth spelling out why it is so bad today: an OR left lazy is driven throughadvance(target), andSVScanDocIdIterator.advancescans forward from the target until it finds a match — so on a segment where the predicate matches nothing it walks to the end. The push-down replaces that with a batchedapplyAndbounded by the candidate set, which is where your ~441M goes.@richardstartin — I like the
RangeBitmapcontext suggestion a lot, and I think this PR is a good short-term fix that yours can be built on top of rather than an alternative to it. Two reasons:AndDocIdSetonly pushes into its own scan children, andStarTreeFilterOperatorandFilterPlanNode#wirePreFilterForVectorOperatorsare both AND-only. This PR is what makes a range index nested under an OR reachable at all.wirePreFilterForVectorOperatorsdoes exactly the shape you're describing — partition the AND's children, checkFilterAwareVectorIndexReader#supportsPreFilter(), check the producers can cheaply produce bitmaps, apply a selectivity cost model, then push the bitmap in. AFilterAwareRangeIndexReaderforwarding torangeBitmap.between(min, max, context)looks like a fairly mechanical generalization of it.The real blocker for the context parameter is one level below this PR:
AndFilterOperator#getTrues()evaluates every child eagerly, soBitSlicedRangeIndexReaderhas already produced its full bitmap by the time anyBlockDocIdSetexists. Consuming a context needs the restriction to arrive at the operator level, which means ordered rather than eager evaluation of the AND's children. Happy to open that as a separate issue if you think that framing is right — it is also the one that would speed up a plainAND(a = 1, ts BETWEEN …)with no OR anywhere, which this PR does nothing for.For completeness on the other option in the description: I don't think the planner rewrite in #19350 is the right primary fix. It only distributes single-column EQ/IN, so it cannot reach @alexch2000's case; it costs an extra index read per branch on the common all-indexed OR, where there is nothing to gain; and it leaves the cliff in place — adding an index to a column inside an OR branch still flips that branch to the eager path, just with
Pinside it now.Jackie-Jiang commentedon Sep 8, 2026
@gortiz Some historical context that seems relevant to #19408:
OR(isSubnetOf(...), ...), whereadvance()can scan almost the entire segment. It proposes wiring the outer bitmap into the nested scans. I previously linked it to Improve AND filter operator #9839, which tracks restricted scans, switching from indexes to scans when few candidates remain, and lazy evaluation / limit pushdown.P AND ((A AND B) OR C), with roughly 42.8M versus 554 filter entries scanned after changing a nested predicate. The discussion also points to Provide bitmap from previous stages of queries toRangeIndexReader#7597 for passing previously matched documents into the range index.OrDocIdSet; Fix Bitmap Filter Execution Order in OrDocIdSet #15756 fixed the resulting loss of bitmap-based scan restriction. One workload saw almost 100x higher latency in Pinot 1.2 (report), and some combinations of sorted and inverted indexes also returned incorrect results. This was an implementation regression, but it illustrates how sensitive the surrounding iterator contracts are.My reading is that the history supports fixing the execution-layer gap. It does not establish that an earlier implementation of this same OR pushdown was tried and failed. Restricting which documents a filter examines and deciding how eagerly to examine them are separate decisions; improving the former can still regress early-terminating queries through the latter.
The disabled default and conservative
AUTOmode in #19408 acknowledge that tradeoff. Could you evaluate the history above against the current proposal and see whether any adjustments are needed? In particular:Please summarize which historical cases are already covered and whether they suggest changes to the implementation, mode eligibility, or regression tests.
Push AND restrictions into composite filter children
Make the AND restriction push-down a tri-state option
Address review: ship disabled, reuse iterator(), fix AUTO
Fix the numDocs bound and release short-circuited children
Defer only scan-bearing subtrees, and benchmark the push-down
gortiz commentedon Sep 17, 2026
Thanks @Jackie-Jiang — that history is exactly the right frame, and I agree with your reading. I have worked through all three questions; #19408 has been updated.
2. Should deferral be limited to subtrees containing scan/expression predicates?
Yes. Done.
Deferral is now driven by
BlockDocIdSet#isScanBased(), which the composites compute over their children;isApplyAndDeferrable()follows it. An index-only subtree returns the same bitmap either way, so handing it a candidate set only added an intersection per branch.Reading this off the DocIdSet rather than the operator tree turned out to be both simpler — no new constructor parameters anywhere — and more accurate. An operator that scans internally and hands back a bitmap, such as a non-exact range index or an H3 index, has already paid for that scan by the time its DocIdSet exists, so restricting it later would gain nothing; the DocIdSet-level view correctly reports
false, where an operator-level flag would have said "scan-based". It also takes the last piece of policy out ofisApplyAndDeferrable(), so the mode is enforced only by the parentAndDocIdSet.Measured neutral:
INDEXED_ORbelow is 0.99–1.02x time and 1.00x allocation.3. Can we validate with latency and allocation benchmarks?
Done —
BenchmarkAndRestrictionPushdowninpinot-perf. 2M documents, a realSVScanDocIdIteratorover a fixed-bit forward index,-prof gcfor allocation. Ratios of push-down on to push-down off, lower is better:SCAN_IN_ORis a scan next to an index-based predicate inside an OR branch — the shape reported here.SCAN_ONLY_ORis scans directly under the OR with no index-based sibling.INDEXED_ORhas no scan anywhere.You were right to push on this: the entries-scanned proxy understated the risk by three orders of magnitude. What the PR previously described as "21–41% more entries scanned" for a limited selection is, in the worst shape, 9431x slower and 384x more allocation. That shape's OR is already lazy on master, so materializing it replaces a scan of a few dozen documents with a scan of the whole segment.
Two other things fell out that I did not expect:
SCAN_IN_ORwith a LIMIT is faster with the push-down, not slower. That OR is not lazy on master either — it is driven byadvance(), andSVScanDocIdIterator.advancescans forward from the target until it finds a match. So the loss is not "selections" in general; it is specifically ORs that are genuinely lazy today.1. Can candidate propagation preserve lazy evaluation and early termination?
Yes, and there is now a spike with numbers rather than a design argument: #19589 (draft, stacked on #19408).
It adds a re-entrant per-chunk kernel,
ScanBasedDocIdIterator#matchDocIds(int[], int), and aRestrictedScanDocIdIteratorthat drives a scan from an upstream candidate stream a chunk at a time. The scan still never sees a document outside the candidate set, but nothing is materialized. The only thing that madeapplyAndnon-re-entrant was a trailingclose()inSVScanDocIdIteratorreleasing oneForwardIndexReaderContext;MVScanDocIdIterator#applyAndwas already re-entrant.Same benchmark, three strategies, with a setup assertion that all three return identical documents:
Streaming removes the cliff — worst case 3.27x instead of 7926x, allocation 1.33x instead of 383x — and beats eager wherever the consumer stops early, because it keeps the early termination eager destroys.
But eager is still the better strategy for a full drain: 0.66x against 1.21x on
SCAN_IN_ORat high candidate density, where streaming is actually slower than master. Chunking costs more than it saves when every matching document will be read anyway.So my answer to your first question is: streaming does not let us drop the mode, it changes what the mode chooses — eager when the query will drain the filter, streaming when it may stop early.
AUTOstops being a safety gate and becomes a strategy selector, and its excluded branch goes from merely safe to fast.I would still keep it as an explicit follow-up rather than folding it into #19408, for two reasons: the spike is not wired into
AndDocIdSet, and the scan in the benchmark is anSVScanDocIdIterator. AnExpressionScanDocIdIterator— theIN_SUBQUERYcase that opened this issue — builds a wholeProjectionOperatorper call, so per chunk it will want a much larger chunk, and a larger chunk erodes the early-termination granularity that is the entire point. Measuring that trade-off is the entry criterion for doing it properly, and it is still open.The historical cases
P AND ((A AND B) OR C)isSCAN_IN_ORabove; Performance degradation case in evaluation of nested AND-OR operators. #10396'sadvance()scanning nearly the whole segment is the mechanism I describe under question 3. With this issue that is three independent reports of the same gap.RangeIndexReader#7597 is not covered. Pushing the restriction into the range index itself viaRangeBitmap's context parameter is a layer below this, and needs the restriction to arrive at the operator level —AndFilterOperator#getTrues()evaluates every child eagerly, soBitSlicedRangeIndexReaderhas already produced its bitmap by the time anyBlockDocIdSetexists.FilterPlanNode#wirePreFilterForVectorOperatorsalready does exactly that shape for vector indexes, so aFilterAwareRangeIndexReaderlooks like a fairly mechanical generalization. Happy to open that separately.SCAN_ONLY_ORcliff surfaced at all.release()for children abandoned by a short-circuit (those iterators holdForwardIndexReaderContexts and are otherwise closed only by reaching EOF), rejects a second consumption of a composite DocIdSet, and preserves the[0, numDocs)bound thatNotDocIdIteratorapplies — the candidate set can carry ids pastnumDocsbecauseBitmapDocIdIterator#getDocIds()hands out the raw bitmap while itsnext()clamps. An intersection cannot introduce such an id, but a complement can. The 200-tree randomized differential test is there to catch exactly the class of regression Fix Bitmap Filter Execution Order in OrDocIdSet #15756 had to fix.AUTOencodes, and the numbers above put a size on it.Adjustments made
The default stays
NEVER.AUTOis unchanged. What changed as a result of your comment: deferral is now limited to scan-bearing subtrees, the benchmark exists, and the PR description now states theSCAN_ONLY_ORrisk in latency and allocation rather than in entries scanned —ALWAYSis genuinely dangerous on a selection workload, and the PR previously undersold that.Push AND restrictions into composite filter children (apache#19408)
SPIKE: streaming restriction kernel (option 4)
SPIKE: benchmark streaming against eager restriction
Stream the AND restriction push-down for LIMIT queries (#19589)