Repository navigation
Conversation
…alysis `ConditionTemplate` runs its index-condition factory on the planning thread in its constructor, and again later from other threads: once per partition in `generateForPartition` (index-analysis pool and reading threads, when `use_constant_folding_in_index_analysis` is on) and after `addTransformation` reset the cache (`SAMPLE`). Every such run analyses a clone of the same filter DAG, which shares its `FutureSetFromSubquery` objects, so each of them could be the first to build a set and several threads could build the same set at once, executing the subquery once per partition. The factory now receives `require_ready_sets`: the constructor's generation passes `false`, every later generation passes `true`. The flag reaches `KeyCondition` through its existing `require_ready_sets_` parameter (added to the `KeyDescription` overload used by the primary key) and the skip indexes through a new `createIndexCondition` parameter; the skip-index conditions that build sets directly use `FutureSet::getOrderedSetIfAlreadyBuilt` when it is set. Index analyses on reading threads (`MergeTreeIndexReadResultPool`, runtime filters) pass `true`; `WhatIfIndexEstimator` and the direct text-index read keep building as before. At default settings this changes nothing: without constant folding `generateForPartition` returns the constructor's condition, and the `SAMPLE` regeneration finds every set the constructor built already built. With `use_constant_folding_in_index_analysis = 1`, an `IN (subquery)` that only a partition-specialised condition can map to the key (e.g. `x + p IN (...)` with `PARTITION BY p ORDER BY x`) no longer prunes, instead of executing its subquery once per partition. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ManifestFilesPruner` is built per manifest on the manifest decode threads, over the filter DAG they all share, so its key conditions must not be the first to build a shared `FutureSetFromSubquery`. The iterator constructor already prepares every set of that DAG on the constructing thread; with `require_ready_sets_` the decode threads now use those sets only when they are ready, instead of relying on that order. A set whose build was stopped or skipped by the constructor (e.g. a subquery that hit `timeout_overflow_mode = 'break'`) is no longer retried on a decode thread; manifest-file pruning simply does not use it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`StorageHive::collectHiveFiles` analysed the query filter again inside every pool task: one `KeyCondition` per partition and one per file, all over the same `ActionsDAG`, so any of them could be the first to build a shared `IN` subquery set, concurrently. Both conditions depend only on table-level keys (the per-task values reach only `checkInHyperrectangle`), so they are now built once on the calling thread and shared read-only by the tasks. This also removes the redundant per-partition and per-file constructions. The partition condition is built only when the table has a partition key, matching the old code, which never built it for an unpartitioned table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FormatFilterInfo::initKeyConditionOnce` runs on processor threads, and object storage makes a `FormatFilterInfo` per file, each with its own `once_flag`, over the same filter DAG, so several readers of one query can construct this `KeyCondition` at once. Pass `require_ready_sets_` so they only use sets that are already built. In the usual mode this changes nothing: by execution time the planner has either built the set or handed its subquery to the creating-sets step, after which an in-place build has nothing to run. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The mutex serialised `buildOrderedSetInplace` for index analyses that run on several threads over clones of one filter DAG, i.e. it blocked pool threads on another thread's whole subquery execution. After the previous commits only the planning-thread analysis builds a shared set; every analysis that runs on a thread pool or on reading threads uses a set only if it is already built (`FutureSet::getOrderedSetIfAlreadyBuilt`, or `KeyCondition`'s `require_ready_sets_`), so there is nothing left to serialise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`05339` runs per-partition MergeTree index analysis on 8 threads during plan optimization (a normal projection makes it run before the subquery is executed) and asserts that each `IN (subquery)` is executed once, for the primary key and for a minmax skip index, plus a positive control that a set built by the planning-time analysis still prunes. With only the mutex removed both executions counters read 8; without the skip-index part only the skip index one does; with the constructor's analysis also ready-only the control fails. `05340` checks that Iceberg partition and min/max manifest-file pruning keep using subquery sets with 1 and 4 manifest decoding threads, and that the counters drop to 0 with `use_index_for_in_with_subqueries = 0`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the getOrderedSetIfAlreadyBuilt note to one line; state the Hive hoist as the invariant (no KeyCondition on the pool). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings; 1 full pass).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261009-014200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20261008-221200 |
|
Workflow [PR], commit [ee3ccb7] Summary: ✅
AI ReviewSummaryReviewed head Final VerdictStatus: ✅ Approve |
CI finish ledger - 5b3ef11Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The build failure dropped the 99 jobs that depend on it, so this head has no functional test results yet. The 8 jobs that ran passed: Session id: cron:our-pr-ci-monitor:20261009-033007 |
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes when index analysis may build IN-subquery sets. Each KeyCondition and skip-index condition now gets a require_ready_sets flag, only the planning-thread condition may build a set, and the mutex in buildOrderedSetInplace is removed. ClickBench Q33 (+8.5%) and Q34 (+10.4%) are unfiltered, high-cardinality GROUP BY scans with no WHERE clause and no IN sets, so they never reach the changed code. Both queries have noisy master history and the shifts are small. Q34 is downgraded to not_sure and Q33 stays not_sure, so this PR shows no attributable performance change. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…lace-build-mutex Conflicts resolved: - ReadFromMergeTree.cpp, MergeTreeData.cpp: keep master's `skip_analysis_` (no longer tied to `use_skip_indexes`, ClickHouse#123403), the PK factory without `relaxRangeAtomsOverNaNHidingTupleColumns`, and the vector similarity factory capturing `index_helper`; add the factories' `require_ready_sets` argument on top. - MergeTreeIndexText.cpp: master's `params.enable_positions` plus `require_ready_sets`. - ManifestFilesPruning.cpp: take master's version (ClickHouse#123085 made `require_ready_sets` a constructor parameter); pass `true` at the decode thread caller `ManifestFileIterator::getOrCreatePruner`, as this branch did inside the pruner before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n on analysis threads `traverseMapElementKeyValueSetNode` (new on master, for `m['key'] IN (subquery)` on a `keyValuePairs` text index) built the set unconditionally. The per-partition condition generated on the index analysis pool reaches it, so with `use_constant_folding_in_index_analysis = 1` a filter like `m[toString(p)] IN (subquery)` executed the subquery once per partition, now concurrently since `inplace_build_mutex` is gone (measured: 8 executions over 8 partitions). Respect `require_ready_sets` like the other set lookups of `MergeTreeIndexConditionText`, and cover the case in 05339. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units455 translation units recompiled, 3369 s compile time in total, 455 of them have a recent master baseline. |
|
@groeneai, fix conflicts. |
…lace-build-mutex # Conflicts: # src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp # src/Storages/MergeTree/MergeTreeIndexBloomFilter.h # src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp # src/Storages/MergeTree/MergeTreeIndexBloomFilterText.h # src/Storages/MergeTree/MergeTreeIndexConditionText.cpp # src/Storages/MergeTree/MergeTreeIndexConditionText.h # src/Storages/MergeTree/MergeTreeIndexText.cpp
|
Merged master in af16de9. The conflicts were the new |
# Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp # src/Storages/MergeTree/MergeTreeIndexConditionText.cpp # src/Storages/MergeTree/MergeTreeIndexConditionText.h # src/Storages/MergeTree/MergeTreeIndexText.cpp
…ation` call The master merge brought a new caller of `prepareSetsForDefaultValueEvaluation` in `MergeTreeIndexConditionText` (from the `mapValues` default-value check), which did not compile against this PR's three-argument signature. Pass the condition's `require_ready_sets`, like the other callers, so analyses off the planning thread still never build `IN` subquery sets. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@copilot resolve the merge conflicts in this pull request |
|
Findings The author reports 84 → 1,020 rows read for this case. That is a real regression with use_constant_folding_in_index_analysis = 1 , not merely an internal cleanup. Simpler approach I’d ask the author to try preparing conditions before dispatching parallel work:
That could remove most of the skip-index parameter plumbing while retaining partition-specific pruning. It must cover SAMPLE cache invalidation and read-time skip-index consumers—not just the primary-key pool. Don’t replace this with “build every set in the filter upfront.” That executes subqueries for unused indexes; existing test 02707_skip_index_with_in explicitly prohibits it. The tradeoff to measure is serial condition-preparation cost with many partitions. This is a concrete alternative to prototype, not a proven drop-in replacement. |
…lace-build-mutex Conflicts: keep master's canonical-DAG redo in `ConditionTemplate::generateForPartition` and the new `PartitionSpecification` argument of `ManifestFilesPruner`, together with this PR's `require_ready_sets`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master in 6be011c to resolve the conflicts. Two files conflicted. In @nickitat, I did not try your alternative in this pass because it changes the design rather than resolving conflicts. In that approach, the planning thread would prepare the partition-specialised |
|
Acknowledged. I'm prototyping the alternative on this branch now: the planning thread prepares the partition-specialised conditions and the analysis and read threads only look them up. I'll post the measurements here, including the serial preparation cost with many partitions. |
…on the planning thread Generating a partition-specialised condition may execute an `IN` subquery to build a shared set. Before, only the condition generated by the `ConditionTemplate` constructor could build sets, so `x + p IN (subquery)` lost its pruning with `use_constant_folding_in_index_analysis = 1` (the set is needed only after partition substitution). Now, for a filter with an `IN` subquery set, the planning thread prepares the condition of every partition before the parts are analyzed on the pool. That covers the conditions the read-time skip index reader uses: by read time the subquery plans have been moved to the steps that build the sets, so they could not be built in place any more. The analysis and read threads only look these conditions up (`ConditionTemplate::getForPart` falls back to the unsubstituted condition and never generates for such a filter). Other filters keep generating them on the analysis threads, so folding without a subquery has no serial cost. `addTransformation` (SAMPLE) regenerates the unsubstituted condition on the calling thread, since it clears the cache. The `require_ready_sets` parameter of `createIndexCondition` and of the condition factories is gone. Format readers and Iceberg manifest decoders stay ready-only, and the Hive conditions stay hoisted out of the pool. 05339 now also covers `use_skip_indexes_on_data_read = 1` and checks the rows read, with the query condition cache disabled for those queries. Suggested by nickitat in the review of this PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I prototyped it and pushed it to this PR in 4ffbbaa.
Rows read with
Serial preparation on the planning thread (release build, one part per partition):
That is about 20 µs per partition and condition, now on one thread instead of across the pool. End to end (debug build, 10000 partitions, 16 index threads), |
| key_condition_rpn_template->prepareForPart(part); | ||
|
|
||
| for (const auto & index_and_condition : skip_indexes.useful_indices) | ||
| index_and_condition.condition_template->prepareForPart(part); |
There was a problem hiding this comment.
[Major] Prepare skip-index conditions only for parts that survive primary-key pruning
This loop runs before markRangesFromPKRange and canUseIndex, so it can now execute an expensive IN subquery for an index that will never be consulted. Previously its generateForPart call was inside the nonempty-ranges branch after primary-key pruning and the index eligibility check.
I reproduced this with the head's Fast test binary: a table with PARTITION BY p ORDER BY x, a minmax index on y, a normal projection, and 1,000 rows across eight partitions. For EXPLAIN indexes = 1 SELECT count() ... WHERE x = 99999 AND y < 100000 AND y + p IN (SELECT number FROM numbers(20) WHERE NOT ignore(sleep(0.1))), with use_constant_folding_in_index_analysis = 1, optimize_move_to_prewhere = 0, and statistics pruning disabled, the primary key selects 0/8 parts and 0/128 granules, and the skip index processes 0/0 parts, yet SleepFunctionCalls increases by 1. An otherwise empty indexed lookup can therefore synchronously execute an arbitrarily large RHS during planning.
Please preserve the ordering: prune with the primary key first, then prepare skip-index conditions on the planning thread for surviving, eligible parts before dispatching their analysis/readers. Add a focused regression asserting that the RHS is not executed when the primary key rejects every part.
There was a problem hiding this comment.
Fixed in fd82dcf: the skip index conditions are now prepared after the primary key analysis, only for the parts it keeps, and 05339 checks that EXPLAIN does not execute the subquery when the primary key drops every part.
There was a problem hiding this comment.
[Major] The original zero-work case still executes the RHS with per_part_index_stats = 1. In the current head, MergeTreeDataSelectExecutor.cpp:1879 calls generateForPart to format each part's condition, including parts rejected by the primary key. This bypasses the new preparation guard. Re-running the original reproduction with that one setting added gives 0/8 parts and 0/128 granules after the primary key, 0/0 work for every skip-index entry, but 1 SleepFunctionCalls event.
There is another instance of the same eager-preparation problem at MergeTreeDataSelectExecutor.cpp:1795–1796: all useful skip-index conditions are prepared before any skip index runs. With an additional z column and INDEX iz z TYPE minmax GRANULARITY 64, WHERE z = 99999 AND y < 100000 AND y + p IN (SELECT number FROM numbers(20) WHERE NOT ignore(sleep(0.1))) keeps all parts through the primary key, then iz drops all 8 parts and 128 granules. iy processes 0/0, yet its RHS still runs once. Both observations use this head's Fast test binary, folding enabled, optimize_move_to_prewhere = 0, statistics pruning disabled, and use_skip_indexes_on_data_read = 0.
Please preserve lazy condition construction across these paths: statistics should consult prepared conditions, and later skip-index conditions should only be prepared for parts that earlier indexes keep. Add zero-execution regressions for both cases.
There was a problem hiding this comment.
🕵 Addressed the first part in 5b963f2, and merged master in 1db5f12.
per_part_index_stats = 1. The per-part statistics now describe the condition with ConditionTemplate::getForPart instead of generateForPart, so nothing is generated (and no IN subquery is executed) for a part that was not analyzed. 05339 has a new EXPLAIN case with per_part_index_stats = 1 where the primary key drops every part; it asserts 0 SleepFunctionCalls.
Preparing a later skip index only for the parts that earlier skip indexes keep. Not done, deliberately. It would require running the pool once per skip index position, with the planning thread preparing the next index's conditions between the rounds, and carrying the per-part state (alter conversions, the partial disjunction results, the per-part index order) across the rounds. After the merge, the per-part analysis lives in analyzeSinglePart on master, which runs the primary key and all skip indexes of a part in one call; splitting it per index is a much larger change than the two passes it has now (IndexAnalysisStage::PrimaryKey, then IndexAnalysisStage::SkipIndexes).
What it would save is one execution of the subquery, in the case where an earlier skip index drops every part that the primary key keeps, and only with use_constant_folding_in_index_analysis = 1 (default 0). The set is shared, so it is never more than one execution per query. At the default settings the same query shape already builds the set while planning, regardless of what any index drops: the unsubstituted condition is generated in the ConditionTemplate constructor. So the remaining difference from master is confined to the non-default folding mode, and I think the per-index rounds are not worth their complexity. A maintainer may decide otherwise; leaving this thread open for that.
…keeps The planning thread prepared the conditions of every skip index for every part before the primary key analysis, so an `IN` subquery could be executed for an index that is never consulted: with `EXPLAIN indexes = 1`, a filter `x = 99999 AND y < 100000 AND y + p IN (subquery)` on a table with `PARTITION BY p ORDER BY x`, a minmax index on `y` and `use_constant_folding_in_index_analysis = 1` executed the subquery although the primary key drops every part. On master, the skip index conditions are generated only for the parts the primary key keeps. Now, if a skip index condition can execute a subquery, the parts are analyzed in two passes on the pool: the primary key first, then, after the planning thread prepares the skip index conditions of the parts with ranges left, the skip indexes. Otherwise both indexes still analyze a part in one pass. A condition needs preparation only when it is specialized per partition (`use_constant_folding_in_index_analysis = 1`) and its filter has an `IN` subquery set; otherwise every part gets the unsubstituted condition, which the planning thread already generated. So at default settings there is no preparation loop and no second pass. Preparation does not look at `canUseIndex`, so an index that is unusable for a kept part (a column it depends on is updated on the fly) can still build the set; the part is read, so the set is needed anyway. 05339 checks that `EXPLAIN` does not execute the subquery when the primary key drops every part, with and without `use_skip_indexes_on_data_read`. With `optimize_move_to_prewhere = 1` master executes the subquery for these queries too, so they disable it. Reported by the clickhouse-gh review of this PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er_credentials_disk Stress workers with `i % 5 == 1` run every test with `memory_tracker_fault_probability=0.05`. The setting also applies to the client's own query memory tracker, so a `clickhouse client` call can fail with `Code: 241 ... fault injected` before it sends its query. When that call is the cleanup `DROP` of the last `run()` or of `t_policy`, a table that names the dynamic disk `plain_<db>` (or the policy `__server_<db>`) survives the test. Nothing defines that disk after a restart, so the server cannot load the table and does not start (`Code: 479 Unknown disk plain_test_1`, seen on ClickHouse#124804 with ClickHouse#130670 already in the build). Pin the probability to 0 for this test, next to the fuzzer and ignored DROP pins added by ClickHouse#130670. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lace-build-mutex Conflict in `MergeTreeDataSelectExecutor.cpp`: master moved the per-part analysis into `analyzeSinglePart`, while this branch split it into a primary key pass and a skip index pass with the skip index conditions prepared on the planning thread in between. Resolution: keep `analyzeSinglePart` and give it an `IndexAnalysisStage` (`All` by default, `PrimaryKey`, `SkipIndexes`). It looks the conditions up with `ConditionTemplate::getForPart` instead of generating them, and the caller keeps preparing them on the planning thread: the primary key ones before the parts are analyzed, the skip index ones only for the parts the primary key keeps. The top-K and row limit checks stay after the skip indexes. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…tistics With `per_part_index_stats = 1`, the description of every part's skip index condition was produced with `ConditionTemplate::generateForPart`, also for the parts the primary key dropped. For a filter with an `IN` subquery set and `use_constant_folding_in_index_analysis = 1` this executed the subquery even when no skip index was consulted. Use `getForPart`, which returns the condition prepared for the part's partition, else the unsubstituted one. `05339` checks that such an `EXPLAIN` does not execute the subquery. Co-Authored-By: Claude Fable 5.2 <[email protected]>
`hasFewerMarksToReadThan` (from master, now analyzing parts on a pool) called `generateForPart` on its workers. With `use_constant_folding_in_index_analysis = 1` and an `IN` subquery in the filter, every worker of the first window could be the first builder of the shared `FutureSetFromSubquery`, which is unsafe now that `inplace_build_mutex` is gone. With cold statistics and primary index, 8 parts and `max_threads_for_indexes = 8`, the subquery ran 8 times (master, which still has the mutex: 1). The probe now prepares the conditions of each window on the calling thread and the workers only look them up, like the main index analysis. The prepared conditions are cached in the template, so the main analysis reuses them. Nothing changes when the filter needs no preparation. 05339 gets a case with cold statistics: the subquery runs once (head before this commit: 8), and the probe decides from the per-partition conditions not to load the statistics (`text_log`; dropping the preparation loop makes the probe fall back to the unsubstituted condition and load them). The query pins the implicit projection, which makes the index analysis run while the query is planned; an analysis that first runs after the set plans are expanded cannot use the set, as on master. Reported by clickhouse-gh in ClickHouse#124804 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
The style check requires an `event_time` condition on every `system.text_log` query, since a full scan of the large CI log exceeds `max_rows_to_read`. The messages it looks for are logged by the test's own query seconds earlier, so `event_time >= now() - 600` keeps them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Closes #118784. @ nickitat asked to remove
inplace_build_mutex(#118784 (comment)). It serialisedFutureSetFromSubquery::buildOrderedSetInplace, blocking pool threads on another thread's subquery, and not only for Iceberg: any multi-threaded index analysis over clones of one filter DAG shares the set and could build it first.Now a shared
IN (subquery)set is built only on the planning thread:INsubquery set, the planning thread generates the per-partitionConditionTemplateconditions before the parts are analyzed on a pool (the primary key probe for loading statistics too; skip index ones only for parts the primary key keeps); the pool and the read-time skip index reader only look them up (ConditionTemplate::getForPart).SAMPLEregenerates the unsubstituted key condition there too.FormatFilterInfo: ready-only (require_ready_sets_).Cost: none at default settings. With
use_constant_folding_in_index_analysis = 1(default 0), a filter with anINsubquery set has its per-partition conditions generated serially: about 20 µs per partition and condition (release build), 177-204 ms for 10000 partitions and one condition. Other filters keep generating them on the pool.x + p IN (subquery)withPARTITION BY p ORDER BY xkeeps its partition pruning.Validation:
05339checks that the subquery runs once (also with cold statistics; never forEXPLAINwhen the primary key drops every part) and the rows read for a primary key, a minmax skip index (also withuse_skip_indexes_on_data_read = 1) and akeyValuePairstext index; letting the pool generate the conditions again makes the subquery run 8 times.02707and the constant-folding tests pass. Iceberg and Hive code is unchanged since the revision where the Iceberg integration tests (incl.test_data_manifest_decode_concurrency) passed;test_hive_querydid not run locally (Hive container timeout).Related: #118486, #118959, #116723 (added the mutex).
Workflow [PR]
Sync PR [sync-upstream/pr/124804]