Skip to content

[FEATURE] Improve PIT usage for large queries over wildcard index patterns #5698

Open

Description

@dai-chen

Is your feature request related to a problem?

The plugin creates a PIT whenever a non-aggregate request needs more rows than index.max_result_window (default 10,000). When the query uses a wildcard index pattern, OpenSearch expands the wildcard and opens one reader context per matching shard, so a broad pattern over hundreds of daily indices can exhaust the per-node search.max_open_pit_context limit (default 300) and the query fails:

Trying to create too many point in time contexts. Must be less than or equal to: [300].

Examples

Two common query shapes trigger it:

  1. Explicit large limit: source=logs-* | head 100000 - the limit is pushed into the scan and exceeds the window, so a PIT is created and ten pages are fetched.
  2. Unbounded scan: source=logs-* | streamstats count() as seen - no explicit limit, so the plugins.query.size_limit cap sits above an operator it cannot be pushed through. The scan is left unbounded and a PIT is created, but only 10,000 rows are returned and no second page is ever requested, so the snapshot serves no purpose.

What solution would you like?

Option Approach Pros Cons Notes
1. Predicate-based index pruning Narrow the wildcard to only the indices that can match, then open the PIT over that set. Snapshot semantics unchanged. No consistency change. Smallest change. Works even for shapes that cannot avoid a PIT. Reimplements pruning core already does, and misses core's ongoing work in this area. Core could instead expose can_match, or new index/field-level stats, as an internal API. See opensearch-project/OpenSearch#21865, #22483, #22451.
2. Incremental execution Split the resolved index set into batches and scan batch by batch, opening and closing one PIT per batch. Bounds context count regardless of how broad the pattern is. Complements option 1 when many indices still match after pruning. Snapshot is per batch rather than global. More PIT create/delete calls and longer wall-clock time. Could later extend to progressive result delivery, returning rows as each batch completes.
3. Stateless pagination Drop the PIT and page with a value-based search_after cursor. Each page is a plain search holding no server state. Nothing accumulates against the cap. Every page gets can_match and coordinator pruning automatically. No cross-page snapshot, so concurrent writes may cause missed or duplicated rows. Needs a stable, unique sort key, and none is both cheap and globally unique. Known as keyset pagination. _shard_doc requires a PIT (opensearch-project/OpenSearch#18924); _seq_no is the closest alternative but is unique only per shard. Paginate docs
4. Full pipeline pushdown Compile the whole pipeline into one search so the cluster returns a finished result — no pagination, like aggregation queries today. Removes the failure mode entirely. Fixes a far broader translation gap than this issue. Largest effort. Feasibility unverified, and coverage can never be complete, so a fallback is still needed. #3879 and #5646 are prior art for widening pushdown coverage. Scripted metrics are a possible escape hatch for pipelines with no aggregation equivalent.
5. New search primitive Add the missing primitive in core: a PIT scoped by predicate, or a search that owns its own pagination state. Clean for every client, not just SQL/PPL. A core contribution, so timeline and effort are unknown. CreatePitRequest has no query body or can-match phase today, and no upstream proposal exists. opensearch-project/OpenSearch#22530 is a precedent for adding a can-match phase to an engine.

What alternatives have you considered?

Mitigations and adjacent directions considered, none of which we treat as a fix:

Alternative Effect Drawback
Raise search.max_open_pit_context Query untouched; more contexts permitted. Each context pins segment readers and blocks merged-segment deletion.
Raise index.max_result_window and use from + size Avoids the PIT entirely. Every matching shard then returns up to size top hits for coordinator-side reduction, a far larger memory spike than paged reads.
Request fewer rows than max_result_window No PIT; the query succeeds immediately. Truncates the input to downstream row-consuming operators, so results change.
Fewer primary shards for new indices Cuts fan-out as indices roll over. Only affects indices created afterwards, so it does not resolve an active failure.
Precompute with rollups or transforms Removes the query shape entirely for recurring dashboards. Only suits known, repeated queries, and adds a pipeline to maintain.
Offload to the async query path Sidesteps coordinator limits for very large fetches. Changes the interaction model to submit-and-poll; not a drop-in for dashboard traffic.

Do you have any additional context?

Related work in this repo:

Activity

  1. added
    enhancement
    on Aug 13, 2026
  2. dai-chen commented on Aug 25, 2026

    @dai-chen
    CollaboratorAuthor

    Option 1 - Index Pruning Approaches

    Example query — the shape that triggers this issue (head 100000 exceeds index.max_result_window, so a PIT is opened over every shard of every index matching logs-*):

    source=logs-*
    | where `@timestamp` >= TIMESTAMP('2026-04-03 08:00:00')
        and `@timestamp` <= TIMESTAMP('2026-04-07 19:00:00')
        and match_phrase(body, '"method":"POST"')
    | head 100000

    Pushed-down filter, referred to below as <FILTER>:

    {"bool":{"must":[
      {"range":{"@timestamp":{"from":"2026-04-03T08:00:00.000Z","to":"2026-04-07T19:00:00.000Z","include_lower":true,"include_upper":true,"format":"date_time","boost":1.0}}},
      {"match_phrase":{"body":{"query":"\"method\":\"POST\"","slop":0,"zero_terms_query":"NONE","boost":1.0}}}
    ],"adjust_pure_negative":true,"boost":1.0}}
    Approach Request Prunes on Latency / overhead Verdict
    A _field_caps + index_filter POST logs-*/_field_caps?fields=@timestamp {index_filter:<FILTER>} Date range only Metadata-only check per shard — no search context, aggregator, or doc collection. Stops at the first matching shard, so a matching index costs ~1 shard visit Recommended. Fastest in practice, and returns a ready-to-use indices array. Ref: https://docs.opensearch.org/latest/api-reference/search-apis/field-caps/#example-using-an-index-filter
    B _index terms agg probe POST logs-*/_search {size:0, track_total_hits:false, terminate_after:1, query:<FILTER>, aggs:{_idx:{terms:{field:"_index", size:4096}}}} Full filter, including text predicates Full query phase on every surviving shard; size:0 and terminate_after trim only the tail, not the setup. And can_match runs only above pre_filter_shard_size (default 128 shards) — below that, nothing is pruned Fallback when text predicates must help prune. Guard sum_other_doc_count > 0 for the 4096-bucket cap
    C Per-index min/max @timestamp cache POST /_msearch per index, {size:0, aggs:{mn:{min:{field:"@timestamp"}}, mx:{max:{...}}}}, no query Date range only 0 on cache hit; on miss one cheap min/max per index (omitting query is what keeps it cheap) Defer — a stale cache under-includes, and the write index must always be kept
    D _search_shards + query POST logs-*/_search_shards {query:<FILTER>} Unknown 1 request, coordinator-only if the query is ignored — unverified whether it is honored Skip — offers nothing A doesn't
    E Index name / creation_date GET /_cat/indices/logs-*?h=index&format=json Index name and creation time 1 cheap request, no shard contact Unsafe. Names tell you when data was written, not what timestamps it contains, so backfilled data gets dropped and results silently go missing. Fine for grouping indices, not for choosing them
    F Core-side index pruning API none — coordinator reads index_field_domains off IndexMetadata, behind search.index_pruning.enabled Date range in bool.filter/bool.must on configured fields No extra request, cluster-state read only. PR reports avg can_match 27 → 0.6 over 90 daily indices Skip — disabled for PIT searches and never runs at PIT creation, so it cannot help this issue. Ref: opensearch-project/OpenSearch#21865
    Gate Only prune when needed IndexNameExpressionResolver.concreteIndexNames() + routing table n/a — decides whether to prune In-process cluster-state read, no network Worth adding. Skips the prune entirely unless the pattern would exceed search.max_open_pit_context
  3. dai-chen commented on Aug 26, 2026

    @dai-chen
    CollaboratorAuthor

    Option 1 — Implementation Approaches [WIP]

    Overview

    When exploring the implementation approach for Option 1 index pruning, we also want to see whether it can mitigate the recently reported schema-conflict problem, not just PIT exhaustion. Either way, this rests on two explicit assumptions about the common time-series case:

    • (a) Schema conflicts. After pruning, the surviving (most recent) indices are unlikely to disagree on field mappings, so the conflict disappears.
    • (b) PIT exhaustion. After pruning, only a few recent indices remain, so the per-node reader-context count stays well under search.max_open_pit_context.

    Note: Both are assumptions about typical rollover-shaped data, not guarantees. Where they don't hold — a wildcard with no time predicate, a conflict uncorrelated with time, or a pruned set that is still wide — we still need dedicated solutions for each problem: a proper conflict representation, and incremental/batched execution (Option 2) for PIT.

    Approaches

    The table below lists implementation options for the pruning step itself. All three share the same probe, _field_caps with index_filter. They differ only in where the partition predicate comes from — each time-bucketed index is effectively a partition — which in turn decides whether the schema half is reachable at all.

    # Partition predicate source Schema conflicts PIT exhaustion Key drawbacks
    1 Extracted from where — no upstream or UI change needs AST extraction before analyze(); the only place a time predicate exists pre-scan separate mechanism: reuse the resolved filter already in PushDownContext at OpenSearchRequestBuilder.build() two mechanisms. Calcite parses the WHERE literal but Lucene parses the probe, so a non-UTC session zone can make the plan-time bound narrower → silently drops indices; needs outward widening and ISO-only literals. Must discard OR/NOT/function-wrapped subtrees, needs boundary analysis for eval-redefined fields, and cannot attribute predicates across a join → single-relation pipelines only
    2 Inline earliest=/latest= in the search command, already in PPL — local scope, matching Splunk's rule that an inline range "apply only to that portion of the search" available without extraction — attach TimeBounds to Relation in AstBuilder.visitSearchFrom, prune in OpenSearchSchema.registerTable before the scan. No divergence risk: already normalized to OpenSearch date math, so the same parser evaluates both sides not automatic. The modifiers are folded into a query_string, which has no doRewrite yielding MatchNoneQueryBuilder, so can_match cannot prune on it. Must use the structured TimeBounds for the probe, not sourceBuilder only fires when the user writes earliest=/latest=; hardcoded to @timestamp (OpenSearchConstants.IMPLICIT_FIELD_TIMESTAMP); primary source only, cross-source semantics undefined today
    3 New start_time/end_time request parameters — global scope, as with ES|QL's request-level filter vs WHERE and Splunk's time range picker, which does propagate to subsearches bounds exist before planning starts — seed once in buildFrameworkConfig, apply in registerTable to every OpenSearch-backed table. No AST work, no visitor change, no ordering problem same mechanism and same probe — one call serves both new API surface; needs client adoption (Query Workbench, dashboards) to deliver value; prunes only on the declared time field, so a query whose selectivity lies elsewhere gets nothing

    Pseudocode

    Approach 1 — extraction for schema, pushdown context for PIT (two mechanisms)

    SCHEMA half
      QueryService, before analyze()
        walk UnresolvedPlan: single-relation only, seal at Aggregation/Eval/...,
          conjunction only, drop OR/NOT/function-wrapped
        accept Compare(@timestamp, Literal) with ISO-8601 or epoch literal only
        widen bounds outward by slop (>= max tz offset)      // parser-mismatch guard
        probe -> rewrite Relation name -> analyze()
    
    PIT half
      CalciteEnumerableIndexScan.scan()            // execution, per iteration
        -> OpenSearchRequestBuilder.build()
             if (pit path && wildcard && sourceBuilder.query() != null)
                 indexName = memoized_prune(indexName, sourceBuilder.query())
        -> createPit() / SearchRequest              // both use pruned indexName
    

    Approach 2 — bounds on the Relation, one mechanism

    1 PARSE    AstBuilder.visitSearchFrom
                 + relation.setTimeBounds(earliest, latest)     // date-math strings
                   (additive; still folds into query_string as today)
    
    2 VISIT    CalciteRelNodeVisitor.visitRelation
                 + if (relation.getTimeBounds() != null)
                 +     holder.put(tableName, relation.getTimeBounds())
                   relBuilder.scan(...)                          // call unchanged
    
    3 RESOLVE  OpenSearchSchema.registerTable
                 + TimeBounds b = holder.get(identifierName)
                 + if (b != null && engine instanceof SupportsIndexPruning p)
                 +     return p.getTable(schemaName, identifierName, b)
                   return engine.getTable(schemaName, identifierName)
    
    4 PROBE    OpenSearchStorageEngine  (new overload, opensearch module)
                 fieldCaps(indices=name, fields=@timestamp, index_filter=range(b))
                 -> new OpenSearchIndex(client, settings, prunedName)
    
    5 INHERIT  getRowType() merges only survivors | CreatePitRequest | SearchRequest
    

    The holder must be shared between CalcitePlanContext and the per-query OpenSearchSchema — both are created together in QueryService.buildFrameworkConfig, so construct one mutable holder there and hand it to both. The probe lives in the opensearch module because it needs an OpenSearchClient; a narrow SupportsIndexPruning interface keeps core free of OpenSearch types.

    Approach 3 — global external parameter (no AST work at all)

    1 REQUEST  POST _plugins/_ppl
                 {"query": "source=logs-* | ...", "start_time": "-7d", "end_time": "now"}
    
    2 PARSE    PPLQueryRequestFactory.parsePPLRequestFromPayload
                 + recognise start_time / end_time
               PPLQueryRequest  + getters reading jsonContent
                 // wire-safe: whole body travels as ONE JSON string in
                 // TransportPPLQueryRequest.writeTo -- no StreamOutput change, no BWC work.
                 // Precedent: fetch_size is already a planning-affecting body field.
    
    3 SEED     QueryService.buildFrameworkConfig
                 + holder.setGlobalBounds(start_time, end_time)     // once, pre-visit
    
    4 APPLY    OpenSearchSchema.registerTable
                 applies global bounds to EVERY OpenSearch-backed table resolved
                 (a source whose @timestamp is not a date self-excludes, because the
                  same _field_caps response reports its type)
    
    5 PRECEDENCE  prefer the Relation's own bounds when set, else the global ones
    

    Suggested sequencing

    The PIT fix is the same regardless of which schema approach is eventually chosen — always take the DSL filter already sitting in the scan's PushDownContext and use it as the index_filter for _field_caps. It is independent of approaches 2 and 3.

    So the proposed order:

    1. Fix PIT exhaustion first, via the pushdown-context filter. No API change, no UI change, no semantic change, and the broadest coverage — it prunes for any query with a pushed filter, not only those that declare a range.
    2. Then decide the schema-conflict fix separately. Either approach 2 or 3 — or a conflict-handling policy that addresses conflicts directly regardless of pruning.

    If both land, the overlap is harmless: a pre-scan prune from 2 or 3 narrows indexName first, and the pushdown-stage prune then operates on the already-narrowed expression, appending fewer or no additional exclusions.

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions