Repository navigation
Description
Query Information
PPL Command/Query:
source=logs-*
| where `@timestamp` > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
| where severityText = 'ERROR'
| eventstats count() as total
| head 10
| fields severityText, total
Expected Result:
The global eventstats count() should push down to OpenSearch as track_total_hits (the same way stats count() does), so the shard returns one number and the coordinator scales it across documents — instead of streaming every matching document to the coordinator just to count them.
Actual Result:
Pushdown does not fire. The scan runs with requestedTotalSize=2147483647 and _source includes — i.e., every matching document streams to the coordinator, where a COUNT() OVER () window function counts them in memory. On a 47B-document index this exceeds query timeouts (the reported "FAIL on PI") and on smaller indices it returns 0 rows when the streaming exceeds limits ("0 rows on CAPE/WI"). The query returns correct results on tiny test data but the plan is unviable at production scale.
Dataset Information
Dataset/Schema Type
- OpenTelemetry (OTEL)
Index Mapping
{
"index_patterns": ["logs-*"],
"template": {
"mappings": {
"properties": {
"@timestamp": { "type": "date" },
"body": { "type": "text", "norms": false },
"severityText": { "type": "keyword" }
}
}
}
}
Sample Data
{ "@timestamp": "2026-05-28T17:44:20.000Z", "severityText": "ERROR", "body": "..." }
{ "@timestamp": "2026-05-28T17:44:21.000Z", "severityText": "INFO", "body": "..." }
{ "@timestamp": "2026-05-28T17:44:22.000Z", "severityText": "ERROR", "body": "..." }
{ "@timestamp": "2026-05-28T17:44:23.000Z", "severityText": "ERROR", "body": "..." }
Bug Description
Issue Summary:
eventstats (no BY, no partition) — equivalent to a global stats count() for purposes of the count value — produces a COUNT() OVER () window function instead of a flat aggregation, and the existing pushdown rules deliberately skip it.
Explain output for both shapes (Calcite engine, pushdown enabled):
stats count() as total (works, pushed down):
CalciteEnumerableIndexScan(
PushDownContext=[[FILTER->..., AGGREGATION->...COUNT(), LIMIT->10000]],
sourceBuilder={"size":0, ..., "track_total_hits":2147483647})
DSL has "size":0 and track_total_hits — the shard returns one number.
eventstats count() as total (fails to push down):
EnumerableLimit(fetch=[10000])
EnumerableLimit(fetch=[10])
EnumerableWindow(window#0=[window(aggs [COUNT()])])
CalciteEnumerableIndexScan(
PushDownContext=[[PROJECT->[@timestamp, severityText],
FILTER->AND(>(@ts,...), =(severityText,'ERROR')),
PROJECT->[severityText]]],
sourceBuilder={"_source":{"includes":["severityText"]},
"query":{"bool":{"must":[{"range":...},{"term":{"severityText":"ERROR"}}]}}},
requestedTotalSize=2147483647)
DSL has _source includes and requestedTotalSize=MAX_INT — every matching document streams up to the coordinator. EnumerableWindow then counts them.
Root cause:
PPL eventstats is parsed in AstBuilder.visitEventstatsCommand (ppl/src/main/java/org/opensearch/sql/ppl/parser/AstBuilder.java:498) as a Window node, which Calcite lowers to a RexOver. The aggregation pushdown path in AggregateIndexScanRule (opensearch/.../planner/rules/AggregateIndexScanRule.java:122,171) explicitly excludes RexOver from pushdown — windows are treated as opaque coordinator-side computations.
This treatment is correct for windows that need partitioning or ordering. But eventstats <agg> without a BY clause produces an unpartitioned, unordered window — OVER () — which is semantically equivalent to: "compute a single global aggregate, broadcast it to every input row." The first half of that (the global aggregate) is exactly what OpenSearch can do natively in the shard.
The result is pathological at scale: instead of one round-trip returning a single number, the coordinator pulls every matching document.
Steps to Reproduce:
- Apply the index template above; index a few sample documents.
- Set
plugins.calcite.enabled: true,plugins.calcite.pushdown.enabled: true. - Run
EXPLAINon the failing query — observeEnumerableWindowand the absence of anaggregationsblock in the DSL. - Replace
eventstatswithstatsand re-runEXPLAIN— observe the correctaggregations+track_total_hitsshape.
Environment Information
OpenSearch Version: 3.7.0-SNAPSHOT (reproduced on main, commit ec433f4ff).
Additional Details:
- Calcite engine:
plugins.calcite.enabled = true - Pushdown:
plugins.calcite.pushdown.enabled = true - Code locations:
ppl/src/main/java/org/opensearch/sql/ppl/parser/AstBuilder.java:498—eventstatsbecomes aWindownodeopensearch/src/main/java/org/opensearch/sql/opensearch/planner/rules/AggregateIndexScanRule.java:122,171— pushdown rule excludesRexOver
Possible fix:
Add a rule that recognizes RexOver with empty partition/order/frame as a global aggregate and rewrites it to:
Project(input.*, broadcast(globalAgg))
Aggregate(group=[], aggs=[<agg>])
<input>
The aggregate is then pushable through the existing AggregateIndexScanRule. The broadcast step on the coordinator is one extra column join that costs nothing — far cheaper than streaming the entire matched set.
Same fix applies to eventstats count() by <field>: OVER (PARTITION BY <field>) → Aggregate(group=[<field>], aggs=[<agg>]) joined back on <field>. Both shapes are common in observability queries.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNot Started
Activity
RyanL1997 commentedon May 29, 2026
@ryan-gh-bot can you do a rca and propose a fix? I would like to review it before you actually open the PR. You can just post it here.
ryan-gh-bot commentedon May 29, 2026
Working on
/@triage(invoked by @RyanL1997) — posting result when done.ryan-gh-bot commentedon May 29, 2026
[RCA]
eventstatslowers to aRexOverthat the aggregate-pushdown rules deliberately exclude, so no aggregation reaches OpenSearchPPL
eventstats(with or withoutBY) is parsed as aWindowAST node, lowered into aLogicalProjectcontainingRexOver, and then Calcite normalizes that into aLogicalWindow. Every variant ofAggregateIndexScanRuleis gated byPredicate.not(LogicalProject::containsOver), and there is no rewrite that recognises an unpartitioned/unorderedRexOveras a global aggregate — so the plan never matches a pushdown rule, and the coordinator ends up streaming every matching document throughEnumerableWindow.Environment
sql(opensearch-project/sql)target/main @ 9300574dc(the agent's starting ref; tip ofmainat9300574dc8b)Suspected location
ppl/.../AstBuilder.javaL497-L525 —visitEventstatsCommandbuilds aWindowFunctionfor each agg, sets the partition list (empty when there is noBY), and returnsnew Window(...). There is no branch that emits a flatAggregationfor the unpartitioned case.core/.../CalciteRelNodeVisitor.javaL2105-L2135 —visitWindowdoesrelBuilder.projectPlus(overExpressions). That produces aLogicalProjectwithRexOvercalls; Calcite's standard normalization (Project2WindowRulefamily) then promotes it to aLogicalWindow, which is theEnumerableWindowthe reporter sees inEXPLAIN.opensearch/.../AggregateIndexScanRule.javaL121-L126, L170-L178, L200-L204 — everyConfig(DEFAULT / BUCKET_NON_NULL_AGG / BUCKET_NON_NULL_AGG_WITH_UDF) constrains the innerLogicalProjectwithPredicate.not(LogicalProject::containsOver).and(PlanUtils::distinctProjectList). As long as the project still carries aRexOver, the rule cannot fire. (AGGREGATE_SCAN, the no-project variant, also doesn't help because the eventstats plan lacks theLogicalAggregateparent the rule keys off of.)opensearch/.../OpenSearchIndexRules.javaL26-L82 — the registered pushdown rule list contains no rewrite from "global window aggregate" to a flatAggregate. The closest precedent isRareTopPushdownRule, which inspectsRexWindow.partitionKeys/orderKeysto recognise a specific window shape and rewrite it into a pushable form — exactly the pattern this fix would follow.Analysis
The reporter's EXPLAIN comparison is the smoking gun:
stats count() as totallowers to aLogicalAggregate(group=[], aggs=[COUNT()]) — LogicalProject — IndexScan. The DEFAULT/AGGREGATE_SCAN configs ofAggregateIndexScanRulematch,pushDownAggregatebuilds anAggSpecwithsize:0+track_total_hits, and the shard returns a single number.eventstats count() as totallowers (viavisitWindow→projectPlusofRexOver→ Calcite's project-to-window promotion) toLogicalWindow(window#0=[…COUNT()…]) — IndexScan. There is noLogicalAggregatefor the rule to match, and the inner project (after window promotion) still containsRexOver, so thecontainsOverguard would also reject it. The plan therefore stays as a window over a non-aggregating scan, which forcesrequestedTotalSize=MAX_INT,_sourceincludes, andCOUNT() OVER ()evaluated row-by-row at the coordinator.The "deliberately exclude" framing in the issue is right: the
containsOverguard is correct for windows that need partitioning, ordering, or a frame other than the implicit "all rows". An emptyOVER ()is the degenerate case where the window's value is identical for every input row — i.e., a global aggregate broadcast back onto each row — which OpenSearch can produce far more cheaply (single shard request returning a single value) than the coordinator can by streaming.The same observation extends to the
BYcase:OVER (PARTITION BY x)produces one value per distinctx, which is exactly atermsaggregation broadcast back onto the rows of each bucket. Both shapes are the common observability use ofeventstats, so they're worth fixing together once the global case lands.Evidence
9300574dc:AstBuilder.java#L497-L525returnsnew Window(...)unconditionally.AggregateIndexScanRule.java#L125,#L175,#L202all carryPredicate.not(LogicalProject::containsOver).opensearch/src/main/java/.../planner/rules/rewrites aLogicalProjectcontainingRexOver(or aLogicalWindow) into aLogicalAggregate— verified bygit grepofRexOver,LogicalWindow,containsOveracross that package.pushDownAggregatehandlesaggregate.getGroupSet().cardinality() == 0correctly (no special-case rejection for empty group set;bucketNamesbecomes empty andAggregateAnalyzer.analyzeproduces thesize:0 / track_total_hitsshape that already works forstats count()). So the rewrite target —LogicalAggregate(group=[], aggs=[count()])— is a known-good shape for the existing rules.2.x-era branches, so this is best treated as a design gap, not a regression.statsandeventstatsshapes that directly demonstrates the symptom (DSL has_sourceincludes +requestedTotalSize=MAX_INTforeventstatsvs.size:0+track_total_hitsforstats). Combined with the source-code evidence above, this is two independent confirming signals for one hypothesis.Confidence: High
Source-code pattern unambiguously matches the symptom (signal a) and the reporter-provided EXPLAIN deltas confirm the runtime shape (signal d). No contradicting evidence.
Next steps
I'd like to confirm the design before opening a PR. Sketch of the fix I'd implement:
opensearch/src/main/java/org/opensearch/sql/opensearch/planner/rules/, e.g.EventstatsToAggregateRule, modeled onRareTopPushdownRule's shape (operand on aLogicalProject/LogicalWindowthat contains aRexOver, with a predicate that picks the rewritable shape). Two operand variants:LogicalProject(RexOver(<empty PARTITION/ORDER, default frame>))— pre-window-promotion shape.LogicalWindow(...)with a single group whosekeysandorderKeysare both empty — post-promotion shape, in case Calcite has already converted the project. We need at least one of these to fire reliably; I'd start with theLogicalProjectvariant sinceeventstatsproduces it directly viaprojectPlusand that's the formcontainsOveralready inspects.BY):RelBuildercorrelate(...)plus a constant-true correlation condition is the cleanest expression of "broadcast a single-row aggregate onto N rows" without literally duplicating the scan. We need to sanity-check that the existingRelDecorrelatorpass turns this into the cross-join + project that the pushdown rules expect; if it doesn't, the alternative is a literalJoin(true)with the scan referenced twice and let the optimizer share it (less ideal because of the double-scan risk).BY x, follow-up): same rule, but withAggregate(group=[<x>], aggs=[<agg>])joined back on<x>. This maps to the existingtermsaggregation pushdown viaAggregateIndexScanRule.DEFAULT. I'd land the unpartitioned case first and add the partitioned case in a follow-up commit on the same PR if testing confirms the broadcast pattern survives decorrelation.partitionKeys.isEmpty() && orderKeys.isEmpty()(orpartitionKeysnon-empty andorderKeys.isEmpty()for the BY case).ROWS/RANGEframe other than the implicit "entire partition".ROW_NUMBER,LAG,NTH_VALUE, etc.) — those are genuine windows.RareTopPushdownRulealready inspects this; we'd reuseBuiltinFunctionName.ofWindowFunctionplus the same shape check.integ-test/.../CalcitePPLEventstatsIT.javaandCalciteExplainITwith EXPLAIN-based assertions that the globaleventstats count()plan now containsAGGREGATION->...COUNT()in thePushDownContextandtrack_total_hitsin thesourceBuilder, mirroring the existingstats count()assertions. Existing eventstats unit tests inppl/src/test/.../CalcitePPLEventstatsTest.javashould keep passing — the AST-levelWindownode is unchanged, only the post-Calcite plan shape changes.Open questions I'd like a steer on before coding:
LogicalProject(RexOver)shape, or the post-promotionLogicalWindow? My preference is the project shape because that's whateventstatsproduces directly and it sidesteps any ordering issue withProject2WindowRule. If you'd rather we hook intoLogicalWindow, I'll mirrorRareTopPushdownRule's approach.Correlate(<agg>, <input>)doesn't decorrelate cleanly into the shapeAggregateIndexScanRulerecognises, the simplest backup is to ship the rewrite and add a small targeted test on the decorrelator output. I'd rather catch this in CI than guess up front.BY? I lean global-only for the first PR (smaller blast radius, confined test surface), with theBYcase as an immediate follow-up.Once you signal which variant + scope you want, I'll open the PR.
Automated response from @ryan-gh-bot (maintainer-triggered agent). About this agent.
RyanL1997 commentedon Jun 1, 2026
RCA confirmed independently from source. Pinning evidence here so the fix can't fall back to a shortcut.
Lowered plan shapes (pinned by existing unit tests):
stats count() as c—ppl/src/test/java/org/opensearch/sql/ppl/calcite/CalcitePPLAggregationTest.java:25:eventstats count()—ppl/src/test/java/org/opensearch/sql/ppl/calcite/CalcitePPLEventstatsTest.java:22:So the structural difference at the time pushdown rules fire is
LogicalAggregatevs.LogicalProject(RexOver). (LogicalWindowdoes not appear here — it only shows up later asEnumerableWindowduring Volcano enumerable conversion, well after pushdown rules have had their chance.)Why no rule in
OpenSearchIndexRules.OPEN_SEARCH_PUSHDOWN_RULESmatches the eventstats shape:AggregateIndexScanRuleconfigs root their operand onLogicalAggregate.class(AggregateIndexScanRule.java:116, 144, 159, 196) — eventstats has noLogicalAggregate→ no match.RareTopPushdownRuleis the only rule whose operand accepts aLogicalProjectcontaining aRexOver, but it requiresLogicalFilter(LESS_THAN_OR_EQUAL)above andcontainsRowNumberRareTopon the project (RareTopPushdownRule.java:116-122) — eventstats hasCOUNT() OVER (), notROW_NUMBER, and no<=filter → no match.The plan therefore reaches Volcano with
RexOverintact, gets converted toEnumerableWindow, and the scan beneath it stays in its default_source includes + requestedTotalSize=MAX_INTmode — exactly the EXPLAIN shape in the report.Rewrite target is provably pushable:
CalciteLogicalIndexScan.pushDownAggregate(CalciteLogicalIndexScan.java:374) handlesaggregate.getGroupSet().cardinality() == 0cleanly —bucketNamesbecomes empty, no special-case rejection.stats count()already exercises this path successfully.Requirements for the fix (no shortcuts):
Both no-
BYandBY xcases must be addressed. The observability use case in the report is theBYshape (eventstats count() by namespace), not just global. A PR that only handles the no-BYcase isn't a fix — it leaves the production query failing. If scope has to be split, the design must explicitly accommodate theBYcase from day one, even if the BY-case rule lands in a follow-up PR.All aggregate functions, not just
COUNT().eventstatssupportscount/sum/avg/min/max/stddev/var/percentileetc. The rule must work for any aggregate thatLogicalAggregatecan carry through the existingAggregateIndexScanRulepath.Multiple aggregates in one eventstats call must be handled in a single rewrite.
eventstats count(), avg(SAL), max(SAL)produces one project with multipleRexOvers. The rewrite must pack all of them into oneAggregate(group=[...], aggs=[...])with one broadcast, not N separate broadcasts.NULL semantics on the
BYjoin-back must be correct.OVER (PARTITION BY x)puts NULL rows in a single "NULL bucket"; the join back ontoxneedsIS NOT DISTINCT FROMsemantics, not=. Silently dropping the aggregate for NULL-keyed rows is a result-correctness regression masquerading as a pushdown fix.The rule predicate must be tight enough to reject genuine windows. Specifically: empty
orderKeysonly, default/unbounded frame only, aggregate function only (notROW_NUMBER,LAG,NTH_VALUE, etc.).streamstats,rare, andtopall produceRexOvers that must be left alone.The rewrite must actually decorrelate into a shape that matches
AggregateIndexScanRule's operand chain. IfCorrelate(Aggregate, input)(orJoin(true)with the scan referenced twice) survives planning in a shape the existing pushdown rules don't recognise, the new rule fires but pushdown still doesn't — different bug, same symptom. A design proposal needs a concrete post-decorrelation EXPLAIN sketch showing the plan reaches one of the four existingAggregateIndexScanRuleoperand chains. Without that, the design isn't done.No symptom-masking shortcuts. Specifically, don't loosen
Predicate.not(LogicalProject::containsOver)inAggregateIndexScanRule's operand chain to let degenerate windows slip through — that doesn't produce theLogicalAggregatethe downstreampushDownAggregatepath needs, and risks letting genuine windows reach a path that mis-handles them. The fix has to be a real Window→Aggregate rewrite, not a guard-loosening.Tests required:
verifyLogicalcases for both no-BYandBYshapes inCalcitePPLEventstatsTestasserting the rewritten plan containsLogicalAggregateand noRexOver; EXPLAIN-based assertions inCalciteExplainITmirroring the existingstats count()assertions (AGGREGATION->...COUNT()inPushDownContext,track_total_hitsinsourceBuilder); a NULL-bucket integration test for theBYcase showing the aggregate is preserved for NULL-keyed rows.Extend rewrite to dc / distinct_count via canonical-name translation