Skip to content

[BUG] eventstats does not push down to OpenSearch (RexOver excluded from aggregation pushdown) #5483

Open

Description

@penghuo

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:

  1. Apply the index template above; index a few sample documents.
  2. Set plugins.calcite.enabled: true, plugins.calcite.pushdown.enabled: true.
  3. Run EXPLAIN on the failing query — observe EnumerableWindow and the absence of an aggregations block in the DSL.
  4. Replace eventstats with stats and re-run EXPLAIN — observe the correct aggregations + track_total_hits shape.

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 — eventstats becomes a Window node
    • opensearch/src/main/java/org/opensearch/sql/opensearch/planner/rules/AggregateIndexScanRule.java:122,171 — pushdown rule excludes RexOver

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.

Activity

  1. added
    bug
    PPL
    on May 28, 2026
  2. RyanL1997 commented on May 29, 2026

    @RyanL1997
    Collaborator

    @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.

  3. ryan-gh-bot commented on May 29, 2026

    @ryan-gh-bot
    Contributor

    Working on /@triage (invoked by @RyanL1997) — posting result when done.

  4. ryan-gh-bot commented on May 29, 2026

    @ryan-gh-bot
    Contributor

    [RCA] eventstats lowers to a RexOver that the aggregate-pushdown rules deliberately exclude, so no aggregation reaches OpenSearch

    PPL eventstats (with or without BY) is parsed as a Window AST node, lowered into a LogicalProject containing RexOver, and then Calcite normalizes that into a LogicalWindow. Every variant of AggregateIndexScanRule is gated by Predicate.not(LogicalProject::containsOver), and there is no rewrite that recognises an unpartitioned/unordered RexOver as a global aggregate — so the plan never matches a pushdown rule, and the coordinator ends up streaming every matching document through EnumerableWindow.

    Environment

    • Tenant: sql (opensearch-project/sql)
    • Refs checked:
      • target/main @ 9300574dc (the agent's starting ref; tip of main at 9300574dc8b)

    Suspected location

    • ppl/.../AstBuilder.java L497-L525 — visitEventstatsCommand builds a WindowFunction for each agg, sets the partition list (empty when there is no BY), and returns new Window(...). There is no branch that emits a flat Aggregation for the unpartitioned case.
    • core/.../CalciteRelNodeVisitor.java L2105-L2135 — visitWindow does relBuilder.projectPlus(overExpressions). That produces a LogicalProject with RexOver calls; Calcite's standard normalization (Project2WindowRule family) then promotes it to a LogicalWindow, which is the EnumerableWindow the reporter sees in EXPLAIN.
    • opensearch/.../AggregateIndexScanRule.java L121-L126, L170-L178, L200-L204 — every Config (DEFAULT / BUCKET_NON_NULL_AGG / BUCKET_NON_NULL_AGG_WITH_UDF) constrains the inner LogicalProject with Predicate.not(LogicalProject::containsOver).and(PlanUtils::distinctProjectList). As long as the project still carries a RexOver, the rule cannot fire. (AGGREGATE_SCAN, the no-project variant, also doesn't help because the eventstats plan lacks the LogicalAggregate parent the rule keys off of.)
    • opensearch/.../OpenSearchIndexRules.java L26-L82 — the registered pushdown rule list contains no rewrite from "global window aggregate" to a flat Aggregate. The closest precedent is RareTopPushdownRule, which inspects RexWindow.partitionKeys / orderKeys to 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 total lowers to a LogicalAggregate(group=[], aggs=[COUNT()]) — LogicalProject — IndexScan. The DEFAULT/AGGREGATE_SCAN configs of AggregateIndexScanRule match, pushDownAggregate builds an AggSpec with size:0 + track_total_hits, and the shard returns a single number.
    • eventstats count() as total lowers (via visitWindow → projectPlus of RexOver → Calcite's project-to-window promotion) to LogicalWindow(window#0=[…COUNT()…]) — IndexScan. There is no LogicalAggregate for the rule to match, and the inner project (after window promotion) still contains RexOver, so the containsOver guard would also reject it. The plan therefore stays as a window over a non-aggregating scan, which forces requestedTotalSize=MAX_INT, _source includes, and COUNT() OVER () evaluated row-by-row at the coordinator.

    The "deliberately exclude" framing in the issue is right: the containsOver guard is correct for windows that need partitioning, ordering, or a frame other than the implicit "all rows". An empty OVER () 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 BY case: OVER (PARTITION BY x) produces one value per distinct x, which is exactly a terms aggregation broadcast back onto the rows of each bucket. Both shapes are the common observability use of eventstats, so they're worth fixing together once the global case lands.

    Evidence

    • Grep + read confirmed the issue's line citations are accurate against 9300574dc:
      • AstBuilder.java#L497-L525 returns new Window(...) unconditionally.
      • AggregateIndexScanRule.java#L125, #L175, #L202 all carry Predicate.not(LogicalProject::containsOver).
      • No file in opensearch/src/main/java/.../planner/rules/ rewrites a LogicalProject containing RexOver (or a LogicalWindow) into a LogicalAggregate — verified by git grep of RexOver, LogicalWindow, containsOver across that package.
    • The existing pushdown path's pushDownAggregate handles aggregate.getGroupSet().cardinality() == 0 correctly (no special-case rejection for empty group set; bucketNames becomes empty and AggregateAnalyzer.analyze produces the size:0 / track_total_hits shape that already works for stats count()). So the rewrite target — LogicalAggregate(group=[], aggs=[count()]) — is a known-good shape for the existing rules.
    • Regression check: not performed — the reporter does not claim a prior working version. The same lowering exists on 2.x-era branches, so this is best treated as a design gap, not a regression.
    • Live verification: not re-run on this invocation. The reporter included EXPLAIN output for both stats and eventstats shapes that directly demonstrates the symptom (DSL has _source includes + requestedTotalSize=MAX_INT for eventstats vs. size:0 + track_total_hits for stats). 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:

    1. Add a planner rule in opensearch/src/main/java/org/opensearch/sql/opensearch/planner/rules/, e.g. EventstatsToAggregateRule, modeled on RareTopPushdownRule's shape (operand on a LogicalProject/LogicalWindow that contains a RexOver, 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 whose keys and orderKeys are 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 the LogicalProject variant since eventstats produces it directly via projectPlus and that's the form containsOver already inspects.
    2. Rewrite shape (global case, no BY):
      Project(input.*, ref-to-agg-output)         // attach the aggregate value back to every row
        Correlate / Join (1×N broadcast)
          Aggregate(group=[], aggs=[<agg>])       // pushable through existing AggregateIndexScanRule
            <input>
          <input>                                 // same input, re-referenced
      
      Calcite's RelBuilder correlate(...) 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 existing RelDecorrelator pass turns this into the cross-join + project that the pushdown rules expect; if it doesn't, the alternative is a literal Join(true) with the scan referenced twice and let the optimizer share it (less ideal because of the double-scan risk).
    3. Partitioned case (BY x, follow-up): same rule, but with Aggregate(group=[<x>], aggs=[<agg>]) joined back on <x>. This maps to the existing terms aggregation pushdown via AggregateIndexScanRule.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.
    4. Constraint guards on the rule predicate, to avoid mis-firing on legitimate window queries:
      • partitionKeys.isEmpty() && orderKeys.isEmpty() (or partitionKeys non-empty and orderKeys.isEmpty() for the BY case).
      • Default/unbounded frame only — reject anything with an explicit ROWS/RANGE frame other than the implicit "entire partition".
      • Aggregate function only (not ROW_NUMBER, LAG, NTH_VALUE, etc.) — those are genuine windows. RareTopPushdownRule already inspects this; we'd reuse BuiltinFunctionName.ofWindowFunction plus the same shape check.
    5. Tests: extend integ-test/.../CalcitePPLEventstatsIT.java and CalciteExplainIT with EXPLAIN-based assertions that the global eventstats count() plan now contains AGGREGATION->...COUNT() in the PushDownContext and track_total_hits in the sourceBuilder, mirroring the existing stats count() assertions. Existing eventstats unit tests in ppl/src/test/.../CalcitePPLEventstatsTest.java should keep passing — the AST-level Window node is unchanged, only the post-Calcite plan shape changes.

    Open questions I'd like a steer on before coding:

    • Which rule variant first — match on the pre-promotion LogicalProject(RexOver) shape, or the post-promotion LogicalWindow? My preference is the project shape because that's what eventstats produces directly and it sidesteps any ordering issue with Project2WindowRule. If you'd rather we hook into LogicalWindow, I'll mirror RareTopPushdownRule's approach.
    • Decorrelation risk — if Correlate(<agg>, <input>) doesn't decorrelate cleanly into the shape AggregateIndexScanRule recognises, 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.
    • Scope of this PR — global only, or global + BY? I lean global-only for the first PR (smaller blast radius, confined test surface), with the BY case 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.

  5. RyanL1997 commented on Jun 1, 2026

    @RyanL1997
    Collaborator

    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:

    LogicalAggregate(group=[{}], c=[COUNT()])
      LogicalTableScan
    

    eventstats count() — ppl/src/test/java/org/opensearch/sql/ppl/calcite/CalcitePPLEventstatsTest.java:22:

    LogicalProject(<all cols>, count()=[COUNT() OVER ()])
      LogicalTableScan
    

    So the structural difference at the time pushdown rules fire is LogicalAggregate vs. LogicalProject(RexOver). (LogicalWindow does not appear here — it only shows up later as EnumerableWindow during Volcano enumerable conversion, well after pushdown rules have had their chance.)

    Why no rule in OpenSearchIndexRules.OPEN_SEARCH_PUSHDOWN_RULES matches the eventstats shape:

    • All 4 AggregateIndexScanRule configs root their operand on LogicalAggregate.class (AggregateIndexScanRule.java:116, 144, 159, 196) — eventstats has no LogicalAggregate → no match.
    • RareTopPushdownRule is the only rule whose operand accepts a LogicalProject containing a RexOver, but it requires LogicalFilter(LESS_THAN_OR_EQUAL) above and containsRowNumberRareTop on the project (RareTopPushdownRule.java:116-122) — eventstats has COUNT() OVER (), not ROW_NUMBER, and no <= filter → no match.
    • None of the remaining 10 rules rewrite a window-style aggregate into a pushable aggregate.

    The plan therefore reaches Volcano with RexOver intact, gets converted to EnumerableWindow, and the scan beneath it stays in its default _source includes + requestedTotalSize=MAX_INT mode — exactly the EXPLAIN shape in the report.

    Rewrite target is provably pushable: CalciteLogicalIndexScan.pushDownAggregate (CalciteLogicalIndexScan.java:374) handles aggregate.getGroupSet().cardinality() == 0 cleanly — bucketNames becomes empty, no special-case rejection. stats count() already exercises this path successfully.

    Requirements for the fix (no shortcuts):

    1. Both no-BY and BY x cases must be addressed. The observability use case in the report is the BY shape (eventstats count() by namespace), not just global. A PR that only handles the no-BY case isn't a fix — it leaves the production query failing. If scope has to be split, the design must explicitly accommodate the BY case from day one, even if the BY-case rule lands in a follow-up PR.

    2. All aggregate functions, not just COUNT(). eventstats supports count/sum/avg/min/max/stddev/var/percentile etc. The rule must work for any aggregate that LogicalAggregate can carry through the existing AggregateIndexScanRule path.

    3. Multiple aggregates in one eventstats call must be handled in a single rewrite. eventstats count(), avg(SAL), max(SAL) produces one project with multiple RexOvers. The rewrite must pack all of them into one Aggregate(group=[...], aggs=[...]) with one broadcast, not N separate broadcasts.

    4. NULL semantics on the BY join-back must be correct. OVER (PARTITION BY x) puts NULL rows in a single "NULL bucket"; the join back onto x needs IS NOT DISTINCT FROM semantics, not =. Silently dropping the aggregate for NULL-keyed rows is a result-correctness regression masquerading as a pushdown fix.

    5. The rule predicate must be tight enough to reject genuine windows. Specifically: empty orderKeys only, default/unbounded frame only, aggregate function only (not ROW_NUMBER, LAG, NTH_VALUE, etc.). streamstats, rare, and top all produce RexOvers that must be left alone.

    6. The rewrite must actually decorrelate into a shape that matches AggregateIndexScanRule's operand chain. If Correlate(Aggregate, input) (or Join(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 existing AggregateIndexScanRule operand chains. Without that, the design isn't done.

    7. No symptom-masking shortcuts. Specifically, don't loosen Predicate.not(LogicalProject::containsOver) in AggregateIndexScanRule's operand chain to let degenerate windows slip through — that doesn't produce the LogicalAggregate the downstream pushDownAggregate path 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: verifyLogical cases for both no-BY and BY shapes in CalcitePPLEventstatsTest asserting the rewritten plan contains LogicalAggregate and no RexOver; EXPLAIN-based assertions in CalciteExplainIT mirroring the existing stats count() assertions (AGGREGATION->...COUNT() in PushDownContext, track_total_hits in sourceBuilder); a NULL-bucket integration test for the BY case showing the aggregate is preserved for NULL-keyed rows.

  6. added
    performance
    and removed on Jun 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    PPLbugperformance

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions