Repository navigation
Use the text index for IN with a set whose elements were not stored - #118128
Conversation
`traverseMapElementKeyNode` and `traverseJSONSubcolumnKeyNode` decide whether a text index can answer `m['key'] IN (...)` (and the JSON-subcolumn equivalent) by evaluating the sub-DAG on a default value: if the predicate is already true for a missing key, no granule can be skipped. That evaluation runs `FunctionIn`, which needs the `IN` set to exist - but it never looks at the set's elements, and the returned `prepared_set` was discarded immediately. Both sites nevertheless required `hasExplicitSetElements`. A set larger than `use_index_for_in_with_subqueries_max_values` is built without storing its elements, and a `StorageSet` need not store them either, so the check gave up on the index for exactly the large `IN` sets it is most worth using on. Require only that the set is built. This cannot change a result: both functions derive their `RPNElement` from the map key or JSON path, never from the set contents. It only lets the index prune where it previously could not. On the test added here, the granule count for a set above the limit goes from 3/3 to 1/3 while the answer stays the same. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Workflow [PR], commit [9acba26] Summary: ✅
AI ReviewSummaryThis PR broadens Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 9acba26.
Changed lines: Changed C/C++ lines covered: 46/60 (76.67%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units192 translation units recompiled, 1793 s compile time in total, 192 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
`05076_text_index_in_set_without_elements` exercises only the oversized-subquery carrier, where `buildOrderedSetInplace` still returns a set and the previous `hasExplicitSetElements` check was the only thing standing in the way. `ENGINE = Set` is a separate implementation: it never calls `Set::fillSetElements`, so `FutureSetFromStorage::buildOrderedSetInplace` returns nothing at all for it and the `get` fallback is what makes `m['key'] IN set_table` reach the text index. Add a test for that carrier, covering both call sites - `traverseMapElementKeyNode` and `traverseJSONSubcolumnKeyNode`. Verified against a binary with the fix reverted: both sections report `Granules: 3/3` with no pruning line, and both report `1/3` with the fix. Also strip the tree-drawing prefix from the `EXPLAIN` lines in both tests. Under parallel replicas the read step is nested inside the local plan and every line is prefixed with `|`, which `trim` alone does not remove; without this both tests fail whenever parallel replicas are enabled. Co-Authored-By: Claude Opus 5 <[email protected]>
`traverseMapElementKeyNode` and `traverseJSONSubcolumnKeyNode` decide once, at analysis
time, that a text index may answer `m['key'] IN (...)`, by evaluating the predicate on a
default value: if it is already false for a missing key, granules without the key can be
pruned.
A `FutureSetFromStorage` is not a snapshot. `StorageSet::insertBlock` inserts into the
very `Set` object the query holds - only `TRUNCATE` swaps in a new one - so a query sees
values inserted after it started. Confirmed on a running server: a query started against
a set of `{'0','1'}` returned `[0,1,5]` when `'5'` was inserted while it was still
reading. An `INSERT` of the default value landing after the decision above therefore
makes the predicate true for rows whose key is missing, while the granules holding those
rows have already been pruned, and the query silently misses them.
Reject `FutureSetFromStorage` at both sites. This restores what
`hasExplicitSetElements` used to reject there by accident - a `StorageSet` never fills
its set elements - while keeping the intended change for a set the query owns, which is
built once and never mutated afterwards.
The test now pins the guard: for `ENGINE = Set` no granule is pruned, while an `IN`
subquery of the same shape still prunes 1/3 at both sites.
Co-Authored-By: Claude Opus 5 <[email protected]>
The guard added in the previous commit used the concrete `FutureSetFromStorage` type as
a proxy for "live table-backed set", but that type also carries a set the query owns:
`optimizeLazyFinal` wraps a `Set` it fills itself via `CreatingSetStep`, passing
`storage_id = std::nullopt`. Nothing can mutate that set behind the query's back, yet
the guard refused it.
That is reachable, not theoretical. `LazyFinalKeyAnalysisTransform` builds
`<primary key expression> IN <that set>` and runs index analysis on it, so a table with
`ORDER BY m['k']` and a `mapKeys` text index hits `traverseMapElementKeyNode` there. On
such a table the trace shows the index being consulted:
LazyFinalKeyAnalysisTransform: PK index has dropped 6/52 granules
LazyFinalKeyAnalysisTransform: Index `idx` has dropped 0/46 granules
With the previous commit's guard the second line was absent - the text index was skipped
for a set that cannot change.
Ask the carrier instead of matching on its type. `canChangeDuringQuery` is false for
every set the query builds for itself and true only for a set backed by a table, which
is exactly `storage_id.has_value()`: `PreparedSets::addFromStorage` takes a `StorageID`
by value, so `StorageSet` and `StorageSharedSet` always carry one and only the
`optimizeLazyFinal` carrier does not.
No test is added for the lazy-final direction: the predicate there is on the primary key
expression itself, so the primary key condition prunes whatever the text index would,
and nothing observable in a query result or `EXPLAIN` distinguishes the two. The
verification above was done from the query trace.
Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
Note
Copilot was unable to run its full agentic suite in this review.
Pull request overview
Adds safeguards and tests to ensure the text skip index is not used for IN predicates backed by a mutable ENGINE = Set (to avoid incorrect pruning), while still allowing index usage when a large IN set drops explicit elements.
Changes:
- Add stateless tests covering text-index behavior for
INwith large sets (without stored elements) and withENGINE = Set. - Update
MergeTreeIndexConditionTextto avoid relying on explicit set elements and to disable the index for sets that can mutate during query execution. - Extend
FutureSet/FutureSetFromStoragewith acanChangeDuringQuery()signal.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/queries/0_stateless/05077_text_index_in_storage_set.sql | New test asserting no granule pruning when IN uses mutable ENGINE = Set. |
| tests/queries/0_stateless/05077_text_index_in_storage_set.reference | Expected output for the new storage-set test. |
| tests/queries/0_stateless/05076_text_index_in_set_without_elements.sql | New test asserting index remains usable even when IN set elements are dropped. |
| tests/queries/0_stateless/05076_text_index_in_set_without_elements.reference | Expected output for the new “set without elements” test. |
| src/Storages/MergeTree/MergeTreeIndexConditionText.cpp | Use canChangeDuringQuery() gating + stop requiring explicit set elements. |
| src/Interpreters/PreparedSets.h | Introduce canChangeDuringQuery() and implement it in FutureSetFromStorage. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
`canChangeDuringQuery` read `storage_id.has_value()`, which is an identity, not a
statement about who may write to the set. It happens to agree with mutability today -
`PreparedSets::addFromStorage` takes a `StorageID` by value, and the one caller that
constructs a `FutureSetFromStorage` around a set the query owns passes `std::nullopt` -
but nothing holds that alignment in place, and reading a capability off an identity is
what made the previous round's guard too broad in the first place.
`src/Functions/in.cpp` already answers this question for the same hazard: folding an
empty `IN` set is refused for a set that can still grow, because `StorageSet::insertBlock`
writes into the very `Set` the query holds. It decides by carrier kind, treating anything
that is not a tuple or subquery set as mutable. Its predicates stay as they are - the
question there is whether a set the query owns has been filled yet, which is not mutation
by anyone else, and the lazy-final carrier must keep answering "not foldable" there.
Record the answer where it is known instead. `FutureSetFromStorage` now carries
`is_mutable_during_query`, set by whoever builds it:
- `addFromStorage` passes true. Its `StorageID` parameter already means "this set lives
in a table", and both callers - `StorageSet` and, in Cloud, `SharedSet` - hand over
the table's own `Set` object.
- `SetsSerialization` passes true: the `StorageSet` a replica resolved the name to.
- `optimizeLazyFinal` passes false: the query builds that set itself.
Verified on a running server that both directions still hold: `m['key'] IN <Set table>`
prunes nothing while an `IN` subquery of the same shape prunes 1/3, and a `FINAL` query
over `ORDER BY m['k']` still reports `Index `idx` has dropped 0/46 granules` from
`LazyFinalKeyAnalysisTransform`.
Co-Authored-By: Claude Opus 5 <[email protected]>
The tests so far only exercise the local plan. When the plan is shipped instead, the `IN` set of an `ENGINE = Set` table travels as a table name and the worker rebuilds it in `makeSetsFromStorage` before rerunning index analysis, so that call site declares the set's mutability a second time and nothing was pinning it. The path needs a real worker: `serialize_query_plan = 1` over `remote(...)`, with `process_query_plan_packet` enabled on the receiving side, which the stateless config already installs. `make_distributed_plan` with `distributed_plan_execute_locally` does not reach it - instrumenting `makeSetsFromStorage` shows no hit for either that pair or `serialize_query_plan` alone on a local plan. The worker's index analysis appears neither in the result nor in `EXPLAIN`, so the test reads `read_rows` back from `system.query_log`. Flipping the flag at that call site to false takes the mutable set from 3 rows to 1, and the new test fails while `05077_text_index_in_storage_set` still passes - the local path does not go through there, which is exactly the gap. Parallel replicas are pinned off in the two queries. Minimizing the randomizer's settings over 192 candidates lands on `automatic_parallel_replicas_mode` together with `enable_parallel_replicas`: the read is then planned elsewhere and the set the query owns stops pruning too, which leaves the comparison with nothing to say. Pinning per setting keeps the test running in the parallel-replicas run, unlike a tag. Co-Authored-By: Claude Opus 5 <[email protected]>
The `is_mutable_during_query_ = false` at the `optimizeLazyFinal` call site is what keeps a `FINAL` query's own set eligible for the text index, and nothing was pinning it: with that argument flipped back to true, 05076, 05077 and 05078 all stay green, because none of them plans a `FINAL` query. Only this carrier reaches that line. `LazyFinalKeyAnalysisTransform` builds `<primary key expression> IN <that set>` and runs index analysis on it, so a table with `ORDER BY m['k']` and a `mapKeys` text index reaches `traverseMapElementKeyNode` there. The test asserts the transform's own trace, the way the other lazy FINAL tests assert theirs, and fails with the flag flipped. Only the presence of the `Index` line is asserted, not the granule counts it carries: how many granules the index drops depends on the granularity the randomizer picks, while being consulted at all is the property under test. That is also why no `no-random-merge-tree-settings` tag is needed, unlike `03990_lazy_final_index_analysis` which pins exact mark counts. Every row carries the map key on purpose. A row without it takes the default value for `m['k']`, which would put that default into the set of key values and make the index unusable for a reason unrelated to the one under test. Co-Authored-By: Claude Opus 5 <[email protected]>
`system.query_log` keeps every past run and `SYSTEM FLUSH LOGS` does not clear it, so `max(read_rows)` answered from the whole history of the current database. On a server where the test had run before, a stale row from a healthy run would keep the assertion true after a regression started pruning the query - the test would go green on the evidence of an earlier run. Reproduced directly: with rows `[3, 1]` for one marker, the newest being the regressed one, `max(read_rows) = 3` still holds while `argMax(read_rows, event_time_microseconds) = 3` does not. The per-run database name usually hides this, but it does not always hold - the test file run by hand against a fixed database is the case that first surfaced it here, when a polluted `default` produced a reference with duplicated rows. Read the newest matching row instead, and keep a time fence for the other direction: if this run's row is missing and only stale ones match, the fence reports no rows rather than a stale verdict. Co-Authored-By: Claude Opus 5 <[email protected]>
Ergus
left a comment
There was a problem hiding this comment.
The analyzer and test's tag comments are the most important
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118128&sha=d5892466ff0386a0574d718b759e2d47d8f50b4c&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%202%2F3%29 #118128 The test failed in the old analyzer run, reproducibly, reporting that the text index was not consulted. It is not: without the analyzer `optimizeLazyFinal` does not run at all, so `LazyFinalKeyAnalysisTransform` never reaches index analysis and there is no trace to observe. With `enable_analyzer = 0` not one line of the transform appears; with it, all three do, ending in `Index `idx_keys` has dropped 0/88 granules`. Ask for the analyzer explicitly, as every other lazy FINAL test already does. Verified under the same condition the job creates, `--client-option enable_analyzer=0`: the test passes with the request in place and fails without it. The other two failures on that commit, `04648_distributed_plan_task_error_propagation` and `04340_distributed_plan_status_reenqueue_fault`, are not from this branch. Both passed all three reruns, and both already fail on master - 14 and 9 times over the last 14 days. Co-Authored-By: Claude Opus 5 <[email protected]>
#118128 Four review points, one of them a real coverage hole. `traverseJSONSubcolumnKeyNode` got the same "the set exists but its elements were dropped" change as the map path, but nothing pinned it: the JSON case in 05077 uses a three-element right-hand side under the default unlimited `use_index_for_in_with_subqueries_max_values`, so the set kept its elements and the fallback was never on the path. Reverting only that function to `hasExplicitSetElements` left all four tests green. 05076 now runs the same above-the-limit probe for `json.a.:String`, and with it that revert fails 05076 while 05077, 05078 and 05079 still pass. `isMutableDuringQuery` is abstract now. A default of false meant a future `FutureSet` would silently claim immutability and be trusted for granule pruning; all three carriers and the one test mock state it explicitly instead. The base comment named "a set backed by a table" for what is specifically an `ENGINE = Set` (`SharedSet` in Cloud) writing into the `Set` object the query holds, and the two guard comments repeated the whole rationale at both call sites. Both trimmed. The `system.query_log` note in 05078 claimed the time fence "reports no rows" when only stale rows match. It does not: the aggregate returns one row holding 0, and the assertion fails - checked. It also only covers stale rows older than the fence, which the note now says. Co-Authored-By: Claude Opus 5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
#118128 The review is right, and the case reproduces. `use_index_for_in_with_subqueries = 0` forbids using an index for a set on the right of `IN`, and these helpers used to obey it only as a side effect: `FutureSetFromSubquery::buildOrderedSetInplace` returns null straight away when the setting is off, so the old `!prepared_set` test rejected the set. Testing `get` instead asks a different question - is the set ready - and something else can make it ready. `ReadFromMergeTree::applyFilters` builds PREWHERE sets unordered exactly when the ordered build declines, and `ColumnSet` keeps the same `FutureSet` across a clone, so a read step analyzed afterwards finds it built. One read step is not enough, because it memoizes its indexes before the sets are built. Lazy FINAL supplies the second by cloning the reading step: SELECT count() FROM t FINAL PREWHERE m['k'] IN (SELECT ...) SETTINGS use_index_for_in_with_subqueries = 0, query_plan_optimize_lazy_final = 1 consulted the text index before this commit and does not now. A plain read was never affected, which is why the earlier tests did not catch it. Ask the setting directly rather than reading it off the ordered build's refusal. The two call sites shared the whole set-preparation block verbatim, so it moves into one helper instead of growing a third repeated paragraph, which also answers the review note about those comments being repetitive. Co-Authored-By: Claude Opus 5 <[email protected]>
…guard The guard reads the carrier type, and a `make_distributed_plan` worker task does not see that type: `serializeForDistributedTask` ships a ready subquery set as its values (`SetSerializationKind::TupleValues`) and `makeSetsFromTuple` rebuilds it as a `FutureSetFromTuple`, so the set no longer says it came from a subquery. Not a regression from this branch, and not confined to these helpers. The previous code tested `buildOrderedSetInplace() && hasExplicitSetElements()`, and `FutureSetFromTuple::buildOrderedSetInplace` never consults the setting either, so a worker used the index for such a set before this branch too. `KeyCondition`, `MergeTreeIndexBloomFilter` and `MergeTreeIndexBloomFilterText` all take the set through the same call, so a worker also uses the primary key index for `pk IN (SELECT ...)` with the setting off. Closing it means carrying the origin through set serialization, behind a plan-version gate, and having every consumer honour it - a change of its own, and one this environment cannot exercise, since distributed-plan worker tasks need a worker client that is not configured here or in the stateless suite. Record the boundary where the check is, so the next reader does not take it for airtight. The path that is reachable here does hold: over `remote(...)` with `serialize_query_plan = 1` the set ships as a subquery plan, keeps its carrier, and the index stays off with the setting off. Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit's message claimed this environment cannot exercise a
`make_distributed_plan` worker task. That was wrong. The stateless suite ships the config
that enables it, `tests/config/config.d/distributed_query.xml`, and with it installed
(plus a free `interserver_http_port` and `distributed_query.streaming_exchange_port`, and
the server logger at `debug`) the path runs locally. Worker task logs do not stream back
to the client, which is why a `--send_logs_level=debug` check looked clean; the whole-server
log shows both sides, told apart by the `::stage_0_0` suffix on the task's query id.
Measured on `SELECT count() FROM t FINAL PREWHERE m['k'] IN (SELECT ...)` with
`make_distributed_plan = 1`:
use_index_for_in_with_subqueries = 1 -> analysis in {<id>} and in {<id>::stage_0_0}
use_index_for_in_with_subqueries = 0 -> analysis in {<id>::stage_0_0} only
So the worker does use the text index with the setting off, as the review said.
The two claims made for deferring it are now measured rather than argued. Restoring the
pre-branch helper body (`buildOrderedSetInplace` plus `hasExplicitSetElements`) and
rerunning gives the identical split, so the bypass predates this branch. And it is not
confined to these helpers: `id IN (SELECT ...)` with the setting off reports
`Key condition: unknown` on the initiator and `Key condition: (column 0 in 3-element set)`
on the worker, so the primary key index bypasses it too, in code this branch does not touch.
The source comment already describes this accurately and stands as written.
Co-Authored-By: Claude Opus 5 <[email protected]>
Ergus
left a comment
There was a problem hiding this comment.
LGTM.
However, I would like to see some numbers about performance change before merging.
|
05076 and 05077 are already taken by open pull requests ClickHouse#118128 and ClickHouse#118003, and 05081/05082 by ClickHouse#117314/ClickHouse#117318, so a merge of any of them would collide. Co-Authored-By: Claude Opus 5 <[email protected]>
Changelog category (leave one):
Changelog entry:
Text indexes on
mapKeysandJSONAllPathscan now pruneINpredicates even when the right-hand-side set exceededuse_index_for_in_with_subqueries_max_valuesand was built without stored elements.Workflow [PR]
Sync PR [sync-upstream/pr/118128]
Version info
26.9.1.1134(included in26.9and later)