Repository navigation
Prune indices by request-level time bounds before the schema is resolved - #5766
Conversation
PR Reviewer Guide 🔍(Review updated until commit 468418e)Here are some key observations to aid the review process:
|
PR Code Suggestions ✨Latest suggestions up to 468418e Explore these optional code suggestions:
Previous suggestionsSuggestions up to commit 97ad23a
Suggestions up to commit 705d0e8
Suggestions up to commit e805474
Suggestions up to commit 975c7ef
Suggestions up to commit 3f22a42
|
The schema-conflict half of Approach 1 that opensearch-project#5727 left open, implemented as Approach 3 of the design on opensearch-project#5698: a request-level time range, applied while the table is still being resolved. A wildcard index expression is expanded -- and the mapping of every index it matches merged -- before any predicate in the query text has been parsed, so nothing downstream of that resolution can narrow it. opensearch-project#5727 reads its range from the filter already sitting in the pushdown context, which is the broadest coverage available without an API change but runs too late for the merge. Declaring the range on the request puts it in hand before planning starts: start_time/end_time/time_field -> PPLQueryRequest.getTimeBounds -> AbstractPlan -> QueryService.buildFrameworkConfig (seeded once) -> OpenSearchSchema.registerTable -> OpenSearchStorageEngine.getTable(.., TimeBounds) -> IndexPruner -> OpenSearchIndex Following the design's shape: - Bounds are global, applied to every table the query resolves rather than attributed to one relation -- the scope Splunk's time range picker and ES|QL's request-level filter have. That is what lets them be a plain request parameter with no AST work, no visitor change and no ordering problem. - Narrowing happens as the table is built, via a new SupportsIndexPruning the storage engine implements, not by mutating a table afterwards: a table's row type is derived from the merge, so once one exists the cost is already paid. The interface keeps the probe in the module owning a client to probe with, and core free of OpenSearch types. - Bounds are carried as the strings the request sent and handed to _field_caps as-is, so OpenSearch's own date parser reads them and date math works. Re-interpreting them here risks a narrower window than the caller meant, which would drop an index that can match -- the divergence hazard the design flags for Approach 1. Two additions the design leaves implicit. time_field makes the field explicit rather than assuming @timestamp, because a Dashboards index pattern is routinely configured on another field and would otherwise never prune. And the probe's format list accepts a UTC wall clock alongside the OpenSearch defaults, since a client that also writes the bound into the query text produces the spelling PPL accepts there; without it such a bound fails to parse and pruning silently declines. A source whose time_field is not a date excludes itself, read off the same probe response, so a range that cannot prove an index disjoint prunes nothing. Unusable bounds are dropped rather than rejected: they only decide which indices are read, so failing a query over a parameter it does not need is the worse outcome. Gated by plugins.query.pruning.enabled, which opensearch-project#5759 turns on by default. Verified on a security-enabled cluster over eight monthly indices whose newest one renamed a field's shape from object to keyword. Without bounds the merge sees the object and charting by it fails; with them only the newest is resolved and the same query returns its rows. Row counts are identical either way, a range covering every index prunes none, and a range no index can match declines rather than pruning all. Signed-off-by: Kai Huang <[email protected]>
c16b768 to
c90cee5
Compare
|
Persistent review updated to latest commit c90cee5 |
Correctness An index that does not map the time field was pruned away with its rows. A range on an unmapped field is *disjoint* for that index, not unknown, so _field_caps omits it exactly as it omits an index whose values fall outside the window -- the two are indistinguishable in the response, and the previous type check saw only the date entry the mapping indices reported and let pruning proceed. Verified against a cluster: a wildcard over one index mapping `ts` and one not returns only the former from the probe. The gate now runs on its own unfiltered probe with include_unmapped, which is the only way to see the indices a filtered probe has already hidden, and declines when the field is unmapped anywhere, not a date anywhere, or mapped by nothing. Costs one metadata probe, paid before the filtered one so a declining query stops early. New IT keeps a row that lives only in an index without the field. The gate also ran before the candidate count, so a window matching no index reported "[ts] is not a date field" -- field-caps returns an empty field map along with an empty index list -- and the "0 of N indices matched" line could never fire. Reordered. analyze dropped the bounds on both phases, so `"analyze": true` merged every matched index's mapping and reported a plan over an expression the execution would not have used. Threaded, as explain already was. Broken surface removed The URL-parameter loop could not work: BaseRestHandler rejects parameters absent from responseParams(), so start_time in a query string was a 400, and a real GET carries no jsonContent for the loop to write into. Dropped rather than half-supported. Tests createRoleWithIndexAccess granted neither indices:admin/resolve/index nor indices:data/read/field_caps*, so under security both probes were denied, pruning declined silently, and TimeBoundsPruningSecurityIT's positive case could not pass. Granted, matching what ppl_full_access carries since 3.9. Both ITs pinned the pruning setting to false on teardown; since opensearch-project#5759 made it default true, that left every later class in the cluster running with pruning off. They clear the override instead. Registered CalciteTimeBoundsPruningIT in CalciteNoPushdownIT, which the repo requires and which matters here: request-level pruning is meant to be independent of pushdown. Accuracy Documented that these bounds are not free of effect. Pruning drops whole indices, so a query whose text already constrains the same field to the same window returns the same rows -- the intended use -- while one that does not returns fewer. The previous claim that a request is "answered identically" was false, and this PR's own subsearch IT asserts a row count changing. Corrected the claim that a bound is read by the index's own date parser: the probe's format list replaces the field's, so a field with some other custom format is not pruned on. Said so, and noted that declining costs the optimization and never a row. Stopped promising the unified query path reads these; it builds its own schema and ignores them. The "Request-level time bounds" heading was a section sibling, sweeping the setting's own disable/result-set examples under it. Demoted to prose. Renamed the leftover "hint" and "time_range" vocabulary in tests to the shipped start_time/end_time/TimeBounds, reused OpenSearchConstants.IMPLICIT_FIELD_TIMESTAMP instead of a second copy, and made a one-sided window warn rather than vanish. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit 1380ef7 |
…hose indices Reviewing this against the Dashboards side turned up two things the separate reviews could not see. The guard added for the unmapped-field case was applied to both pruning paths, which regressed opensearch-project#5727's own yaml case "Prunes an index that does not map the timestamp". The two paths are not alike. When the range is read out of the query's own pushed-down filter, an index that does not map the field cannot satisfy that filter either, so its documents are already excluded from the answer and dropping the index is lossless -- which is exactly what that test asserts. When the range arrives as a request parameter the query text need not mention the field at all, so those documents are still wanted. The guard now applies only to the bounds path; the filter path is untouched, and the yaml suite passes again. And rather than declining outright when the field is unmapped somewhere, the bounds path now keeps those indices and prunes among the rest. _field_caps already names them in the unmapped bucket of an include_unmapped probe, so this costs nothing and turns a case that gave up into one that prunes correctly -- worth having because a Dashboards index pattern spanning a stray index without the time field would otherwise never prune at all. Declining is kept only where nothing better is possible: no index maps the field, it is mapped as a non-date somewhere, or the probe does not name the unmapped indices. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit d7b6b4c |
Got integTestWithSecurity running locally for the first time on this branch, and the suite failed two of its four cases -- not on the handoff it was written for, but because of how it observed pruning. It asserted that charting by a field mapped as an object in one index and a keyword in another fails without bounds. Which side of that conflict wins the merge depends on hash iteration order, so it varies between JVMs: the earlier manual run on a standalone cluster returned the expected 400, this one returned 200 and the two negative cases failed. The assertion was never sound. Observes the resolved schema instead, as CalcitePPLTimeBounds... already does: a field that exists only in the out-of-range index either resolves or does not, which is decided by which indices the merge saw and nothing else. Adds a row-count parity case while here, since that is the property that matters most and the old shape could not express it. Confirmed the permission grant added earlier is load-bearing by taking it back out: the positive case then fails with "nothing was thrown", pruning having declined on a denied probe exactly as predicted. Restored, and 5/5 pass. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit c792001 |
Codecov Report❌ Patch coverage is ❌ Your project check has failed because the head coverage (62.86%) is below the target coverage (99.00%). You can increase the head coverage or adjust the target coverage.
Additional details and impacted files@@ Coverage Diff @@
## main #5766 +/- ##
=============================================
- Coverage 98.40% 62.86% -35.54%
- Complexity 2746 8814 +6068
=============================================
Files 266 938 +672
Lines 6758 40205 +33447
Branches 426 4528 +4102
=============================================
+ Hits 6650 25275 +18625
- Misses 107 14125 +14018
- Partials 1 805 +804
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Three time ranges can reach one query and they are not alternatives: a where clause and earliest=/latest= both filter rows and combine, while start_time/end_time only select indices. Spell out the consequence -- a query whose own range is wider than the bounds loses rows, because the indices outside the bounds are never read. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit 5f74855 |
A client cannot assume plugins.query.pruning.enabled is there to read: a cluster older than 3.9 does not have the setting at all, and a newer one may have it off. A pruning boolean in the request body now decides for that request, deferring to the cluster setting when omitted. It rides jsonContent, which already crosses the transport, so there is no StreamOutput change and no version gate -- unlike partial_result, which carries its own wire field. Both pruning paths honour it: the bounds path in OpenSearchStorageEngine and the pushed-down-filter path in OpenSearchRequestBuilder. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit 3f22a42 |
TimeBounds and the AstBuilder field still said the bounds apply to every source; they narrow the outermost one. Also split the run-on paragraph in endpoint.rst, make the priorities table's cross-reference concrete, and cut isMainSource's javadoc to the part a reader cannot infer. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit 975c7ef |
Also drop the Calcite-only line: since the bounds decode in OpenSearchStorageEngine.getTable, which both engines resolve tables through, pruning applies on the V2 path too (verified live). Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit e805474 |
"Send them only alongside an equivalent filter" reads as though the bounds need one to take effect. They do not: they prune regardless, and the filter is what keeps the answer the same. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit 705d0e8 |
| /** Lookup command */ | ||
| @Override | ||
| public UnresolvedPlan visitLookupCommand(OpenSearchPPLParser.LookupCommandContext ctx) { | ||
| // Not narrowed: a lookup index is a dimension table, not one of the searched sources. |
| "time_field" : "event_time", | ||
| "start_time" : "2026-09-07 00:00:00.000", | ||
| "end_time" : "2026-09-14 00:00:00.000", | ||
| "pruning" : true |
There was a problem hiding this comment.
why need pruning override on query level? plugins.query.pruning.enabled is feature flag.
There was a problem hiding this comment.
My previous assumption is that customer can't change cluster setting, but it turns out that they can use _plugins/_query/settings, so a query-level override was solving a problem that doesn't exist. Reverted in full: the request field, the plan/CalcitePlanContext carrier, the shared gate, the two ITs and the doc lines. plugins.query.pruning.enabled decides
The setting is a feature flag and a customer can already change it through _plugins/_query/settings, so a query-level override adds an API for a problem that does not exist. Back to: plugins.query.pruning.enabled decides, full stop. Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit 97ad23a |
Signed-off-by: Kai Huang <[email protected]>
|
Persistent review updated to latest commit 468418e |
…route and the security plugin (#5785) CalciteTimeBoundsPruningIT and TimeBoundsPruningSecurityIT (added in #5766) carried no gates, so integTestRemote failed them on clusters the tests were never meant for: the analytics-engine route does not observe the request-level pruning, and the security IT drives the security REST API, which does not exist without the plugin. Add the TIME_BOUNDS_PRUNING capability and annotate both classes with @RequiresCapability so they skip on the analytics-engine route, and assume the security plugin in TimeBoundsPruningSecurityIT.init() exactly like the sibling security ITs. Verified against four remote clusters: OpenSearch + security passes both classes (15/15), OpenSearch without security passes the Calcite class and skips the security one, and both analytics-engine clusters skip both classes. Signed-off-by: menwe <[email protected]>
…schema is resolved (#5766, #5852) (#5863) * Prune indices by request-level time bounds before the schema is resolved (#5766) (cherry picked from commit f40bfdd) Signed-off-by: Kai Huang <[email protected]> * Fix comma-separated sources with request-level time bounds (#5852) * Encode time bounds once for a comma-separated source With request-level time bounds, AstBuilder encoded the bounds onto every source of a comma-separated list, and Relation then joined the sources with commas. TimeBounds uses a comma as its own separator and decodes only the last block, so `source=a,b` decoded to a garbled name and failed with "no such index". For a cross-cluster source the `cluster:` strip then cut at the colon in the timestamp, giving "no such index [55:54]". Encode the bounds onto the last source only, so the joined name ends in a single block and decodes to every source with its bounds. Signed-off-by: Kai Huang <[email protected]> * Cover comma-separated sources with time bounds end to end A request with time bounds over a comma-separated source returns its rows, and pruning still drops the out-of-range index from every entry of the list. Signed-off-by: Kai Huang <[email protected]> --------- Signed-off-by: Kai Huang <[email protected]> (cherry picked from commit 866dafc) Signed-off-by: Kai Huang <[email protected]> --------- Signed-off-by: Kai Huang <[email protected]>
Description
Implements the schema-conflict half of Approach 1 that #5727 left open, as Approach 3 of that design: a request-level time range, applied while the table is still being resolved.
A wildcard index expression is expanded — and the mapping of every index it matches merged — before any predicate in the query text has been parsed, so nothing downstream of that resolution can narrow it. #5727 reads its range from the filter already sitting in the pushdown context, which is the broadest coverage available without touching the request contract but runs after the merge. Declaring the range on the request puts it in hand before planning starts:
The bounds travel encoded into the table name, so they reach the storage engine through the name the query already resolves rather than a channel of their own — the trick
SystemIndexUtils.restTablealready uses for therestcommand:Decoding lands before the mapping merge, which is the ordering problem this PR exists to solve. It is also the one method both engines resolve a table through (
Analyzer.visitRelationon V2,OpenSearchSchema.registerTableon Calcite), so nothing between the request and the storage engine has to know the bounds exist.Following the design's shape:
source=only. Ajoin's other side, a subsearch's source, amultisearchdataset and alookup's dimension table are left alone. A client splices its own time filter after the first command, so a secondary source keeps every row; narrowing one would drop indices nothing filtered. Splunk's picker does reach a subsearch, but as a row filter on the subsearch itself — reproducing that is Approach 2 of [FEATURE] Improve PIT usage for large queries over wildcard index patterns #5698, not index selection.QueryServicesignature._field_capsas-is, so OpenSearch's own date parser reads them and date math works. Re-interpreting them here risks a narrower window than the caller meant, which would drop an index that can match — the divergence hazard the design flags for Approach 1.Gated by
plugins.query.pruning.enabled, which #5759 turns on by default.Two additions the design leaves implicit
time_field. The design assumes@timestamp. A Dashboards index pattern is routinely configured on another field — OpenSearch Dashboards' own sample-data pattern usestimestamp— and would otherwise never prune. Defaults to@timestamp, so a request that says nothing behaves as designed.An index that does not map
time_fieldis pruned like any other that cannot match: under a request-level time range a document with no time value is in no window, which is also what the pushed-down-filter path does (index_pruning.ymlasserts it). The consequence is deliberate and documented — such an index's rows, and its schema, go with it, so a query naming a field only it maps fails withField [x] not found.rather than quietly returning nothing.A format list on the probe range. Passing bounds through raw means the field's own format applies, and OpenSearch's default rejects
YYYY-MM-DD HH:mm:ss.SSS— the spelling a client that also writes the bound into the query text produces, since PPL accepts it there. Without this the probe throws, the exception is caught, and pruning silently declines. This was caught only by the ITs; 2 of 8 failed with "nothing was pruned" and the sole symptom was absence. The list isstrict_date_optional_time||epoch_millis||yyyy-MM-dd HH:mm:ss.SSS; date math is resolved before any of it applies.Example
Eight monthly indices. The newest renamed a field's shape —
attributes.clusterwas an object holdingname, and is a plain keyword after the roll — so merging them makes charting by it fail.Without bounds, every index is merged and the object wins:
POST _plugins/_ppl {"query": "source=prune-demo-2026.* | where `timestamp` >= '...' and `timestamp` <= '...' | chart count() over timestamp by attributes.cluster"} {"error": {"reason": "Cannot chart by [attributes.cluster] because it is an object.", "status": 400}}With them, only the index that can hold data in the window is resolved:
{"query": "...", "time_field": "timestamp", "start_time": "now-15m", "end_time": "now"} {"schema": [{"name": "timestamp"}, {"name": "attributes.cluster"}, {"name": "count()"}], "total": 50}A wider picker range prunes proportionally rather than all-or-nothing —
prune-demo-2026.* → .07,.08,.09for two months — and a range no index can match declines rather than pruning everything:Testing the changes
core+ppl+opensearchunitCalciteTimeBoundsPruningIT(new)TimeBoundsPruningSecurityIT(new)TimeBoundsTest(new)AstTimeBoundsTest(new)yamlRestTest(incl. #5727'sindex_pruning.yml)CalcitePPLBasicIT/CalcitePPLLookupIT/CalciteMultisearchCommandITThe last row is the regression cover that matters for the encoding: every source a query names goes through the same
AstBuildercode path, sosource=,lookupand a multisearch dataset are all exercised.New IT cases: the schema resolves from the in-range indices only (a field only the out-of-range ones map stops resolving); the whole pattern resolves without bounds; row counts are identical with and without; a range covering every index prunes none; bounds are ignored when the setting is off, when unusable, and when the field is unmapped; an index without the time field is pruned along with its schema; and a
join's other side and a subsearch's source keep every row.Also verified live on a security-enabled cluster, since the bounds cross the transport→worker handoff that #5739 and #5758 each had to fix for a different per-request signal — here they ride the object graph, so there is nothing on
ThreadContextto drop.TimeBoundsPruningSecurityITcovers it; noteintegTestWithSecuritycannot run locally at the moment because today's snapshot distro shipsjackson-core-2.22.1while the security plugin's own zip carries2.22.2(the existingPartialResultSecurityITfails identically), so that suite is CI-verified only.Unusable bounds are dropped rather than rejected: they only decide which indices are read, so failing a query over a parameter it does not need is the worse outcome.
API surface
Three new request-body parameters —
start_time,end_time,time_field— and nothing else:POST /_plugins/_pplis unchanged.TransportPPLQueryRequest.writeTo, so there is noStreamOutputchange and no version gate.fetch_sizeis the precedent: a planning-affecting body field read straight offjsonContent, which the transport already carries. (partial_resultis not — it has its ownwriteOptionalBooleanfield, so it would have needed a wire change.)They do change behaviour when present, which is the point, so this is an API addition rather than a purely internal change — the api-specification companion PR is noted unchecked below.
Internally nothing is added to
core's storage contract: no new interface, andStorageEngine.getTablekeeps its signature. Other engines are untouched — a name they were never handed bounds in decodes to itself.Files touched
core/.../executor/TimeBounds.javappl/.../domain/PPLQueryRequest.javastart_time/end_time/time_fieldoff the bodyppl/.../PPLService.javappl/.../parser/AstBuilder.javaisMainSourcedecides which that isopensearch/.../storage/OpenSearchStorageEngine.javaopensearch/.../request/IndexPruner.java@timestampdocs/user/admin/settings.rst,docs/user/interfaces/endpoint.rstSplit out of this PR
Testing through Dashboards surfaced a partial-result defect:
chart/timechartaggregate twice over the same scan on different group keys, so partial mode could exclude a different index set per aggregation — the top-N ranking then picks columns from rows that are not in the chart. It reproduces onmainwith pruning off, so it is not from this PR, and it is now #5777.Related Issues
Part of #5698. Builds on #5727; expects #5759.
Front-end counterpart: opensearch-project/OpenSearch-Dashboards#12722.
Check List
--signoffor-s.By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
Review notes
A self-review and a joint review against the Dashboards side turned up several defects, fixed in the later commits and worth recording:
_field_capsreports it as not-matching, indistinguishably from one whose values fall outside the range. A first attempt retained such indices via an extrainclude_unmappedprobe, but that regressed Avoid PIT context exhaustion by pruning indices that cannot match #5727's ownindex_pruning.ymlcase (on the pushdown path the range is the query's filter, so dropping the index is lossless there) and it left the partial-result feature something to exclude, producing a spurious "mapping conflict" banner on a field that was merely absent. Both paths now prune it, consistently.analyzedropped the bounds on both of its phases, so"analyze": truereported a plan over an index expression the execution would not have used.BaseRestHandlerrejects parameters absent fromresponseParams(), so?start_time=…was a 400, and a GET carries no body for the loop to write into. Removed rather than half-supported.createRoleWithIndexAccessgranted neitherindices:admin/resolve/indexnorindices:data/read/field_caps*, so both probes were denied and pruning declined silently. Granting them is load-bearing: taking them back out makes the positive case fail again, which is also the first direct evidence for the permission limitation the manual documents.falseon teardown, which since Enableplugins.query.pruning.enabledby default #5759 disables the feature for every later class sharing the cluster. They clear the override instead.AbstractPlanand its three subclasses, threeQueryServiceoverloads, anOpenSearchSchemaconstructor and aSupportsIndexPruningmarker. Encoding them into the table name instead (@penghuo's suggestion) deleted all of it, 281 lines and ten files, and reached the V2 path that the Calcite-only schema hook had silently skipped.lookup's dimension table and ajoin's other side. @penghuo and @mengweieric both caught it, from different directions: a lookup table is a static dataset with no window, and a client'swhereclause only covers the first command, so narrowing a secondary source drops rows nothing filtered. Now only the outermostsource=is narrowed, decided structurally inisMainSourcerather than by visit order. The two ITs that asserted the old behaviour now assert the invariant instead.