Skip to content

Remove inplace_build_mutex: only the planning thread builds a shared IN subquery set - #124804

Open
groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/remove-inplace-build-mutex
Open

groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/remove-inplace-build-mutex

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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 serialised FutureSetFromSubquery::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:

  • MergeTree: for a filter with an IN subquery set, the planning thread generates the per-partition ConditionTemplate conditions 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). SAMPLE regenerates the unsubstituted key condition there too.
  • Iceberg manifest-file pruner and FormatFilterInfo: ready-only (require_ready_sets_).
  • Hive: partition and file conditions are built once, before the pool.

Cost: none at default settings. With use_constant_folding_in_index_analysis = 1 (default 0), a filter with an IN subquery 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) with PARTITION BY p ORDER BY x keeps its partition pruning.

Validation: 05339 checks that the subquery runs once (also with cold statistics; never for EXPLAIN when the primary key drops every part) and the rows read for a primary key, a minmax skip index (also with use_skip_indexes_on_data_read = 1) and a keyValuePairs text index; letting the pool generate the conditions again makes the subquery run 8 times. 02707 and 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_query did not run locally (Hive container timeout).

Related: #118486, #118959, #116723 (added the mutex).


Workflow [PR]
Sync PR [sync-upstream/pr/124804]

groeneai and others added 7 commits October 8, 2026 22:47
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ⚠️ 05339 passes on master too; read_rows < 500 would allow partial decline DISAGREE The test guards the invariant once the mutex is gone (removing only the mutex fails it with 8 executions, as does each partial revert); partial decline is unreachable because every partition condition reads one set, fixed on the planning thread before the pool starts.
2 ⚠️ 05340 asserts > 0 and does not tell this PR from master DISAGREE The description says the Iceberg change is not observable; the test checks that pruning with subquery sets is preserved at decode concurrency 1 and 4, with a use_index_for_in_with_subqueries = 0 negative control.
3 ⚠️ No runtime proof that Hive pool tasks never build a set DISAGREE After the hoist, pool tasks construct no KeyCondition and read no filter DAG, only the const checkInHyperrectangle; the only builds are the two constructors before ThreadPool pool{.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261009-014200

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, for what the mutex hides: with only the lock removed, 05339 runs the IN subquery 8 times (once per partition), 3/3; a TSan build of this branch with per-partition conditions allowed to build reports 3 data races and a heap-use-after-free on set_and_key->set in one query.
b Root cause explained? Clones of a filter DAG share their FutureSetFromSubquery, and index analyses on several threads could each build it first, writing set_and_key->set and source concurrently; the mutex hid this by blocking pool threads on another thread's subquery.
c Fix matches root cause? Yes: only the planning-thread analysis may build a shared set, every pool or reading-thread analysis is ready-only, then the mutex is removed; no widened bounds, tags or crash-site guards.
d Test intent preserved / new tests added? New 05339 (MergeTree primary key, minmax skip index, planning-time positive control) and 05340 (Iceberg pruning with subquery sets at decode concurrency 1 and 4, with a negative control).
e Both directions demonstrated? 05339 fails with only the mutex removed (8/8), with the skip-index part reverted, and with the constructor made ready-only; passes on master and this PR. TSan: 4 reports vs 0.
f Fix is general across code paths? Every buildOrderedSetInplace caller and KeyCondition / skip-index construction was classified by thread; all pool and execution-time carriers are covered (MergeTree templates incl. SAMPLE, 4 skip-index classes, Iceberg, Hive, FormatFilterInfo).
g Fix generalizes across inputs (params/datatypes/wrappers)? Only subquery sets can be unbuilt; all set-reading skip-index types are threaded; checked with constant folding on and off, decode concurrency 1 and 4, and 2x50 randomized runs.
h Backward compatible? (maintainer-approved exception only) No setting, default or format change; with opt-in use_constant_folding_in_index_analysis = 1, a partition-specialised-only IN no longer prunes (stated in the description).
i Invariants and contracts preserved? A shared set is mutated only by the planning-thread analysis and only read afterwards; ConditionTemplate's cache locking is unchanged; a set whose build stopped is not retried on a pool thread.

Session id: cron:clickhouse-impl-slot-40:20261008-221200

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ee3ccb7]

Summary: ✅


AI Review

Summary

Reviewed head ee3ccb7222a4144e2024dfbe4064918e06d95932. The PR removes inplace_build_mutex by preparing shared IN subquery sets before parallel index analysis, while retaining partition-specific pruning. No new actionable findings. The earlier statistics-probe race and unnecessary execution when the primary key rejects every part are addressed. I accept the author's documented tradeoff of eagerly preparing later skip-index conditions with use_constant_folding_in_index_analysis = 1; the existing discussion needs no further reply. The focused 05339_index_analysis_subquery_set_built_once regression passes in the current-head Fast test report.

Final Verdict

Status: ✅ Approve

Comment thread src/Formats/FormatFilterInfo.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5b3ef11

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 2/4) / Build ClickHouse master build break, not from this PR: src/Common/Scheduler/Nodes/tests/gtest_throttler_constraint.cpp:25: error: use of undeclared identifier 'FifoQueue'. That test line came with #113697 (merged 2026-10-08 23:18Z), and #116800 had already removed FifoQueue from master. This PR does not touch src/Common/Scheduler #124798 (external, open)
Mergeable Check, PR rollups, red only because of the row above #124798 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

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: Fast test, Style check, the other three arm_tidy shards, Code Review, Config Workflow and Finish Workflow. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261009-033007

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1040 1128 +8.5% 0.0318 aggregation: Full-scan high-cardinality GROUP BY with no WHERE clause and no IN sets, so the changed index-analysis set-building path never runs. The +8.5% shift is borderline on a query with noisy history.
⚠️ 34 not_sure 1020 1126 +10.4% 0.0034 aggregation: Unfiltered GROUP BY over the whole table with no IN subquery, so the PR's require_ready_sets and set-build mutex changes are not on this path. The +10.4% shift matches this query's noisy history.

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
  • StressHouse run: f04773eb-0720-44c9-958a-ea5755f90aa3
  • MIRAI run: ae1e23a1-590b-4361-a80d-bf5def76aaf3
  • PR check IDs:
    • clickbench_665402_1791607259
    • clickbench_665408_1791607260
    • clickbench_665414_1791607259
    • tpch_adapted_1_official_665425_1791607259
    • tpch_adapted_1_official_665437_1791607260
    • tpch_adapted_1_official_665472_1791607260

groeneai and others added 2 commits October 23, 2026 12:37
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ee3ccb722 with master 2a2f57466 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

455 translation units recompiled, 3369 s compile time in total, 455 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

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

Copy link
Copy Markdown
Collaborator Author

Merged master in af16de9. The conflicts were the new IsShadowingColumn parameter of the bloom filter and text index conditions next to this PR's require_ready_sets; both are kept.

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Storages/MergeTree/MergeTreeIndexConditionText.cpp
#	src/Storages/MergeTree/MergeTreeIndexConditionText.h
#	src/Storages/MergeTree/MergeTreeIndexText.cpp
alexey-milovidov and others added 2 commits November 10, 2026 18:28
…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]>
@nickitat

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

@nickitat

Copy link
Copy Markdown
Member

Findings

⚠️ The mutex removal sacrifices existing pruning. In  ConditionTemplate::generateForPartition , sets must now already exist. But with  PARTITION BY p ORDER BY x , an expression such as  x + p IN (subquery)  becomes index-usable only after partition substitution. The constructor therefore never builds its set.

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:

  1. Keep the Hive hoist: construct conditions once, then share them.
  2. For MergeTree, prepare/cache the needed partition-specialized conditions on the planning thread.  ConditionTemplate  already has a per-partition cache. Workers should consume prepared conditions; granule reading/filtering stays parallel.
  3. Keep runtime-only consumers, such as format readers and Iceberg manifest decoders, read-only.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master in 6be011c to resolve the conflicts. Two files conflicted. In ConditionTemplate::generateForPartition, master's canonical ActionsDAGWithInversionPushDown redo is kept and still uses require_ready_sets = true. In ManifestFileIterator, the new PartitionSpecification argument is kept alongside require_ready_sets = true. The binary builds, and 05339_index_analysis_subquery_set_built_once and 02707_skip_index_with_in pass locally.

@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 ConditionTemplate conditions, so x + p IN (subquery) keeps its pruning with use_constant_folding_in_index_analysis = 1 and most of the createIndexCondition plumbing goes away. It also has to cover SAMPLE cache invalidation and read-time skip-index consumers, and it must not build sets for unused indexes (02707). @groeneai, please prototype it as described and measure the serial preparation cost with many partitions.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

I prototyped it and pushed it to this PR in 4ffbbaa.

  • For a filter with an IN subquery set, the planning thread generates the per-partition conditions before the parts are analyzed on the pool, including the ones the read-time skip index reader uses: by read time the subquery plans have moved to the set-building steps, so a set can no longer be built in place. The pool and the reader only look the conditions up (ConditionTemplate::getForPart). Filters without such a set keep generating them on the pool. After SAMPLE changes the key condition, its unsubstituted condition is regenerated on the planning thread.
  • The require_ready_sets plumbing of createIndexCondition and of the condition factories is gone: the diff against master is 15 files instead of 37. Hive stays hoisted; FormatFilterInfo and the Iceberg manifest decoders stay ready-only.
  • 02707_skip_index_with_in passes. 05339 now also checks the rows read and covers use_skip_indexes_on_data_read = 1.

Rows read with use_constant_folding_in_index_analysis = 1, 1000 partitions:

Filter master previous head now
x + p IN (subquery) 500 16100 500
y < 100000 AND y + p IN (subquery), minmax index on y 500 16100 500
the same, use_skip_indexes_on_data_read = 1 16100 16100 500

Serial preparation on the planning thread (release build, one part per partition):

Partitions x + p IN (subquery), 1 condition y < 100000 AND y + p IN (subquery), 3 conditions x + p < 50 folding off
1000 16-19 ms 52-85 ms 0 ms 0 ms
10000 177-204 ms 561-608 ms 0 ms 0-2 ms

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), x + p IN (subquery) takes 487-496 ms on master and 628-671 ms here. Where index analysis first runs after the subquery plans have moved (no projection that triggers early analysis, parallel-replica followers, parts analyzed remotely), the substituted IN atom stays unavailable, as on master.

key_condition_rpn_template->prepareForPart(part);

for (const auto & index_and_condition : skip_indexes.useful_indices)
index_and_condition.condition_template->prepareForPart(part);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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]>
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
…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]>
alexey-milovidov and others added 2 commits November 20, 2026 23:50
…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]>
Comment thread src/Interpreters/PreparedSets.cpp Resolved
groeneai and others added 2 commits November 21, 2026 01:35
`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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Data race on FutureSetFromSubquery::source between two storage iterators building the sets of a shared ActionsDAG

3 participants