Skip to content

Take the in-place build mutex in FutureSetFromSubquery::buildSetInplace - #118959

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-buildsetinplace-inplace-build-mutex
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-buildsetinplace-inplace-build-mutex

Conversation

@groeneai

@groeneai groeneai commented Sep 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):

Serialize the two in-place builds of one FutureSetFromSubquery against each other.

Description

Stress test (*_tsan) reports a data race on FutureSetFromSubquery::source, filed as #118784 and
requested in #115798 (comment). 14 stress
jobs on 13 pull requests over 14 days, none on master.

ActionsDAG::clone shares one FutureSetFromSubquery between the Iceberg manifest filter DAG and the
path/file filter DAG, so the manifest producer and query threads build it at once.
323aee4fbfe7fa0 added inplace_build_mutex for this, but only buildOrderedSetInplace takes it:
buildSetInplace reaches build's std::move(source) unlocked and destroys the pointer the locked
builder is dereferencing.

The change is one std::lock_guard, held across the whole in-place build. The issue's objection that a
plain mutex is not sufficient holds for a pointer-scoped lock, where the second caller finds
source == nullptr and skips; held across the build, the second arrival waits and re-tests through
build's existing isCreated() gate. In a reproducer the second builder moves from inside the first's
802 ms build to waiting for it and seeing isCreated() = 1; removing the line restores the overlap.
Measured: a plain local read does not reach this pair, because its set is built during analysis.

#118486 removes the Iceberg callback behind today's second builder; this closes the missing half of the
lock, as the issue asks.

Scope: the lock serializes the two in-place builders; it does not make a waiter's set ready, because the
deferred build() is a plan handoff by design. SetAndKey::set's publication in this vehicle is
unsynchronized, a separate defect the new test can surface next. buildSetInplace also records no
failure reason when a build throws; that code is released, so it needs a different changelog category.

Regression corpus and 50 randomized runs of the new test are green, no hangs. A 16-way IN-subquery
benchmark stays inside its own noise (median 3144 vs 3352 QPS, base spread 9.2%, p99 unchanged).

CIDB census: 14 rows / 13 pull requests / 0 master, last 14 days
SELECT check_start_time, check_name, pull_request_number, left(commit_sha, 8)
FROM checks
WHERE test_status IN ('FAIL','ERROR')
  AND position(test_context_raw, 'PreparedSets.cpp:430') > 0
  AND position(test_context_raw, 'IcebergIterator.cpp:357') > 0
  AND check_start_time > now() - INTERVAL 14 DAY
ORDER BY check_start_time DESC
2026-09-08 13:17:22	Stress test (arm_tsan)	98992	7fe50787
2026-09-08 10:16:18	Stress test (arm_tsan)	118386	98931136
2026-09-08 09:50:17	Stress test (amd_tsan)	115798	a1f841ff
2026-09-07 22:24:41	Stress test (arm_tsan)	117054	71326cc9
2026-09-07 19:40:16	Stress test (amd_tsan)	115970	47dc2333
2026-09-07 18:32:19	Stress test (amd_tsan)	107106	60dc8fa8
2026-09-06 23:50:32	Stress test (amd_tsan)	111895	3cff708c
2026-09-06 23:49:37	Stress test (amd_tsan)	117383	9e39419c
2026-09-06 23:22:04	Stress test (arm_tsan)	118427	b03a2ce3
2026-09-06 21:11:03	Stress test (arm_tsan)	117054	f30735ab
2026-09-06 20:06:56	Stress test (arm_tsan)	118429	b92a5ca7
2026-09-06 16:07:13	Stress test (amd_tsan)	112808	debb128c
2026-09-06 13:01:02	Stress test (arm_tsan)	118095	4ac9d78d
2026-09-05 22:13:45	Stress test (amd_tsan)	114613	9f16968a

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

groeneai and others added 3 commits September 8, 2026 17:10
`ActionsDAG::clone` shares one `FutureSetFromSubquery` between the Iceberg
manifest filter DAG and the path/file filter DAG, so the Iceberg manifest
producer thread and the query thread can build that set at the same time: the
producer runs `buildOrderedSetInplace` from the `prepare` callback of
`DataFileEntriesStream`, while the query thread runs `buildSetInplace` from the
`ObjectIteratorWithPathAndFileFilter` constructor.

323aee4 added `inplace_build_mutex` for exactly this situation, but only
`buildOrderedSetInplace` takes it. `buildSetInplace` reaches `build`, whose
`std::move(source)` destroys the pointer the locked builder tests and then
dereferences, which ThreadSanitizer reports as a data race on
`FutureSetFromSubquery::source`.

Holding the mutex across the whole in-place build, rather than around the
pointer alone, is what makes the second arrival wait for the first build's
outcome instead of finding `source` already taken and silently skipping. The
re-test it then performs is `build`'s existing `isCreated()` gate, so no new
readiness state is introduced and a build that stops without creating the set
stays retryable, which is why `callOnce` is still not usable here.

The lock serializes the two in-place builders and nothing more: the deferred
build hands a plan to the pipeline by design, so a waiter's set is not
necessarily ready afterwards.

The new test is a cluster read of a local Iceberg table filtered by
`_path IN (subquery)`, which is the only shape in the tree that reaches both
builders concurrently. Its assertions are deterministic; the concurrency oracle
is the sanitizer and stress arms.

Related: ClickHouse#118784

Co-Authored-By: Claude Opus 5 <[email protected]>
… in 05105

The test's only oracle is CI's sanitizer and stress arms observing the two
in-place set builders overlap, so it has to reach both builders.

The manifest-pruning builder has two gates. makeManifestFilterDag returns
nullptr when use_iceberg_partition_pruning is false, so the Iceberg iterator's
constructor never calls buildOrderedSetsForDAG and there is no second builder;
and buildOrderedSetInplace returns before its lock when
use_index_for_in_with_subqueries is false. The first of those is reachable in
CI without touching the test: SettingsChangesHistory records the default flip
in 25.6, and the stress runner passes compatibility='<20..26>.<1..12>' on 20%
of runs, which reverts it. The test then still prints its expected output while
exercising nothing. Pin both in the query, where the value beats the runner's
client option.

The helper table was created with a fixed name and never dropped, while
clickhouse-test skips the per-test database drop whenever --database is passed
and the stress runner passes --database=test_<i> for every odd worker. A second
execution in such a worker failed with TABLE_ALREADY_EXISTS, a false failure in
the arm that carries the oracle. Give it the per-database suffix and the
DROP-before-CREATE the other table already had, and drop it at the end.

No change to the expected output, and no source change.

Co-Authored-By: Claude Opus 5 <[email protected]>
…s claim

The previous round made the helper table re-runnable but not the Iceberg
directory, and the directory is the harder half: DROP TABLE does not delete
Iceberg data, because iceberg_delete_data_on_drop defaults to false, and the
trap that removes it is skipped when clickhouse-test kills a timed-out test's
process group. Measured directly: six data files before the DROP, the same six
after it. With a fixed directory name the next execution in the same database
then creates the table over the leftover snapshot, so the deterministic
assertion no longer holds. Measured: the previous file fails with
"Iceberg table with path ... already exists" and prints 0 0 instead of 20 5090.

The stress runner also passes ignore_drop_queries_probability=0.2, and an
ignored DROP of a table that stores data on disk returns without dropping, so
the helper table can survive its own DROP IF EXISTS as well.

Give both names a per-run suffix, which makes the directory per-run too, and
remove the directory before the CREATE, as the other IcebergLocal tests do.
Both are conventional here: 224 stateless shell tests use a ${RANDOM} suffix.

The header claimed no other test reaches the racing pair, which was never
measured. It is now: 05043_object_storage_path_virtual_column_empty_namespace
filters _path with a subquery on an IcebergLocal table, and an instrumented run
of it reaches only the ordered builder, on one thread. A plain local read
finishes the set during analysis, so the manifest producer and the iterator
constructor both find it already created and skip; disabling
use_index_for_in_with_subqueries there brings the second builder back, one
thread, no overlap. The cluster read is what leaves the set unbuilt for two
threads at once. Say that instead of the unmeasured claim.

The oracle survives the rename: the two builders still meet on one set object
with an 802 ms arrival overlap, including on a second run in the same database.

No change to the expected output, and no source change.

Co-Authored-By: Claude Opus 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 Sep 9, 2026
@groeneai

groeneai commented Sep 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) over three rounds, alongside my own cold
pass each round. 5 gate findings in total; the final round on the tree published here returned none. No
finding ever touched the source change, which is byte-identical across all three rounds.

# Sev Finding Verdict Evidence / action
1 ⚠️ Stress compatibility randomization can disable Iceberg partition pruning, removing the ordered builder the new test needs AGREE, fixed @ 660af13 makeManifestFilterDag returns null at use_iceberg_partition_pruning = 0 (IcebergIterator.cpp:109), the 25.6 settings-history entry reverts that default under an older compatibility, and the stress runner sets a random one on 20% of runs. Both gates of the ordered builder are now pinned in the query, with a negative control showing the pin is load-bearing: removing only the pins leaves the test green while the two builders no longer meet.
2 ⚠️ The test asserts only the query result, so it never proves both in-place builders ran DISAGREE True and not fixable by an assertion. The only counter in the tree, SetsBuiltFromSubquery (CreatingSetsTransform.cpp:260), counts builds rather than entrants, and the measured loser skips instead of building (created=0, source=0, the if (!source) exit at PreparedSets.cpp:548), so it reads 1 both before and after the fix. A rendezvous hook would mean a new failpoint in src/ for a test, and the defect has no SQL-observable consequence in either ordering, so the oracle is the sanitizer arms and the test header says so.
3 ⚠️ The test is not safe to re-run in a shared database: leftover helper table, leftover Iceberg directory, and drops the stress runner may ignore AGREE, fixed @ 660af13, widened @ dc5452e clickhouse-test skips the per-test database drop when --database is passed and the stress runner passes one for every odd worker, so a second run failed with Table paths already exists. Widened after a second pass: DROP TABLE leaves Iceberg files behind (iceberg_delete_data_on_drop defaults to false, measured as six data files before the drop and the same six after), the EXIT trap is skipped when a timed-out test is killed by process group, and ignore_drop_queries_probability=0.2 can turn any cleanup drop into a no-op or a TRUNCATE. Both objects now carry per-run unique names and the directory is removed before the CREATE; the old file fails on a second run in one database while the new one passes three times, and the builders still meet with an 802 ms arrival overlap after the rename.
4 ⚠️ "No other test in the tree reaches this pair" was asserted, not measured AGREE, fixed @ dc5452e 05043_object_storage_path_virtual_column_empty_namespace.sh filters _path with a subquery on an IcebergLocal table, and none of the three legs is cluster-specific: the manifest producer thread is spawned unconditionally and runs its prepare callback before any manifest work (IcebergIterator.cpp:200, :252-258), the only ObjectIteratorWithPathAndFileFilter construction sits in createFileIterator which the plain read path also calls (StorageObjectStorageSource.cpp:624, ReadFromObjectStorageStep.cpp:183), and the cloned manifest DAG shares the ColumnSet. Measured with the overlap probe instead of argued: at default settings that test reaches only the ordered builder, on a single thread, because a plain local read finishes the set during analysis and the later entrants find it already created. The unmeasured universal is gone from both places it appeared, the test header and the description above.
5 ⚠️ A query-cache hit could return the expected result without running either builder DISAGREE The mechanism legs hold (sleepEachRow inherits isDeterministic() = true, IFunction.h:284), but a hit needs the identical query inside query_cache_ttl = 60 s and nothing produces that: use_query_cache is not in clickhouse-test's randomizer (its neighbour use_query_condition_cache is a different cache), the only enabler is the stress runner at 1/15 per worker, tests/config/ neither enables the cache nor extends the TTL, the test runs its SELECT once, a suite loop re-reaches a test only after thousands of others, and the retry path fires only for its own message list.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding. Findings on hunks unchanged by a fix round are auto-dropped.

On the deadlock question a lock now held across a pipeline run raises: no cycle is reachable, because
both builders walk external_table_set parent-to-child, one-thread re-entrancy would need a subquery
containing itself, buildSetsForDagImpl holds one set at a time, and DataFileEntriesStream::run()
calls its prepare callback before it schedules any decode or publishes any entry, so the producer can
never hold the mutex while blocked on a full queue.

One randomized knob the earlier rounds had not named was checked in the last pass and needs no pin:
automatic_parallel_replicas_mode = 2 on a quarter of runs forces enable_parallel_replicas = 1 for any
test without the no-parallel-replicas tag, but the second plan build that follows only rebinds
SetAndKey objects so the two plans share them (considerEnablingParallelReplicas.cpp:248-268); the set
is still filled once, when a pipeline runs, so the two builders still meet.

Noted, not blocking: the co-located publication of SetAndKey::set stays unsynchronized, and the test
added here makes the meeting deterministic, so that pointer is what can be reported next, in the order
where the ordered builder wins. This change touches neither the write site (PreparedSets.cpp:757,
inside the mutex) nor the unlocked read (VirtualColumnUtils.cpp:83, before either lock), so it neither
creates nor widens that race. Taking the mutex inside get() was rejected with evidence: a reader would
then block for another thread's whole subquery execution, which contradicts
ConditionSelectivityEstimator.cpp:334's contract of never executing one. It is named in the description
above and raised in the issue thread rather than folded in silently.

Session id: cron:clickhouse-review-slot-48:20260908-172000, cron:clickhouse-review-slot-49:20260908-214900, cron:clickhouse-review-slot-9:20260909-041200

@clickhouse-gh clickhouse-gh Bot closed this Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc5452e]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) ERROR
Timeout FAIL cidb

AI Review

Summary

This PR takes inplace_build_mutex in FutureSetFromSubquery::buildSetInplace and adds an Iceberg regression test intended to exercise the manifest/path-filter two-thread shape. I am not ready to approve it yet, because the same shared FutureSetFromSubquery is still published through set_and_key->set without synchronization, so the Iceberg path can keep reporting a TSan race even after the source handoff is serialized.

Findings

❌ Blockers

  • [src/Interpreters/PreparedSets.cpp:465] The new lock only serializes the source handoff. buildOrderedSetInplace still replaces set_and_key->set on the ordered path, while FutureSetFromSubquery::get() reads that same member unlocked and callers such as VirtualColumnUtils::buildSetsForDAG perform that read on the sibling DAG before deciding whether to build. Because ActionsDAG::clone and ColumnSet::cloneDummy preserve the shared FutureSet, the manifest thread can publish a new SetPtr while the path/file-filter thread is inside the unlocked get() check. Suggested fix: give every read/write of set_and_key->set the same synchronization, or switch that publication to an atomic handoff instead of reassigning the shared pointer.
Final Verdict

❌ Changes requested. The source race is fixed, but a second reachable race on set_and_key->set remains in the same code path.

LLVM Coverage Report

Measured on commit dc5452e.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A cluster read of a local Iceberg table with _path IN (subquery) and a slow subquery: the two in-place builders of one set overlapped on 5 of 5 runs on the base binary.
b Root cause explained? ActionsDAG::clone shares one FutureSetFromSubquery between the Iceberg manifest filter DAG and the path/file filter DAG, so the manifest producer thread and the query thread build it at once; inplace_build_mutex (added by 323aee4fbfe7fa0) is taken by buildOrderedSetInplace only, so buildSetInplace reaches build's std::move(source) unlocked.
c Fix matches root cause? Yes: the missing half of that commit's invariant, one std::lock_guard held across the in-place build. No widened bound, no no-random-* tag, no guard at the reading site.
d Test intent preserved / new tests added? No existing test changed. One new stateless test. The nearest existing candidate was measured, not argued: 05043_object_storage_path_virtual_column_empty_namespace filters _path with a subquery on an IcebergLocal table, and an instrumented run reaches only the ordered builder on one thread (pair_objects = 0), because a plain local read finishes the set during analysis and the later builders find it already created. 04267_iceberg_parquet_in_subquery filters on a data column, so no path/file filter iterator is built; 04669 and 04907 contain no Iceberg; no test uses icebergLocalCluster.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Before: the second builder ran inside the first's 802 ms build and observed isCreated() = 0 with source already taken. After: it waits 801 ms, observes isCreated() = 1, and the critical sections are disjoint. Removing only the lock line and rebuilding brings the overlap back on 3 of 3 runs.
f Fix is general across code paths? The invariant has exactly two carriers and both now hold the mutex. Not guarded, and disclosed in the description instead: the public build()/prepareForDistributedPlan (no overlap with an in-place builder was demonstrated), setQueryPlan (all four sites read, all planning-time), getQueryPlan() (returns a raw pointer), replaceSetAndKey/detachSetAndKey, and SetAndKey::set's unlocked publication.
g Fix generalizes across inputs (params/datatypes/wrappers)? A mutex acquisition has no input matrix: it serialises two functions on one object regardless of element types, subquery shape or settings. The matrix that matters is the four outcomes for two racing builders; two of them are pre-existing and disclosed.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, no SettingsChangesHistory.cpp entry, no serialized format, no layout or signature change, so no caller changes.
i Invariants and contracts preserved? The concurrency contract is the one repaired. Both builders take self-then-external_table_set, which is assigned only in the constructor, so no cycle is constructible. Re-entrancy on one object needs a self-referential subquery; buildSetsForDagImpl visits a set twice only sequentially. Retryability is unchanged because the lock adds no state: the re-test is build's existing isCreated() gate, which is why callOnce stays refused. The external_table_set recursion is byte-identical, so GLOBAL IN external tables are still filled.

Session id: cron:clickhouse-impl-slot-5:20260908-134300, cron:clickhouse-impl-slot-4:20260908-210300, cron:clickhouse-impl-slot-4:20260909-030300

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @yariks5s, could you review this? ActionsDAG::clone shares one FutureSetFromSubquery between the Iceberg manifest filter DAG and the path/file filter DAG, so two threads build the same set at once, and 323aee4fbfe7fa0 guarded only buildOrderedSetInplace. This takes that same mutex in buildSetInplace, which otherwise reaches build's std::move(source) unlocked and destroys the pointer the locked builder is dereferencing.

{
/// `build` below moves `source` out, and `buildOrderedSetInplace` tests and dereferences it under
/// this mutex, so both in-place builders must hold it. Rationale at the other lock site.
std::lock_guard lock(inplace_build_mutex);

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.

This lock fixes the source move/dereference race, but it still leaves a second unsynchronized shared state in the same two-thread Iceberg path: buildOrderedSetInplace can replace set_and_key->set, while plain readers like FutureSetFromSubquery::get() and VirtualColumnUtils::buildSetsForDAG still read that member without inplace_build_mutex. Because ActionsDAG::clone / ColumnSet::cloneDummy keep the same FutureSet shared between the manifest and path/file DAGs, one thread can be publishing the new SetPtr while the other is inside the unlocked get() probe. I think set_and_key->set needs the same synchronization discipline (or an atomic publication) before this race is actually closed.

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.

The mechanism is right, and it is a different race from the one this PR closes.

get() (PreparedSets.cpp:329) reads set_and_key->set with no lock, and buildOrderedSetInplace republishes that pointer at :543 and :758. Neither site changes here: the whole src/ diff is one std::lock_guard in buildSetInplace, and the ordered publication has been inside inplace_build_mutex since 323aee4fbfe7fa0 (2026-08-27), before this PR. So the pointer race is pre-existing, and this change neither creates nor widens it. The description already names it as a separate defect the new test can surface next.

Giving every read of set_and_key->set the same lock would not be a synchronization-only change. get() has 20 call sites in src/; the other writer, CreatingSetsTransform.cpp:143, holds a SetAndKeyPtr and no FutureSetFromSubquery, so it cannot take that mutex at all; and two of the readers are deliberately non-blocking readiness probes, KeyCondition.cpp:2906 under require_ready_sets and LazyFinalKeyAnalysisTransform.cpp:67. A blocking get() would make index analysis wait for exactly the subquery build those two guards exist to skip.

Whether to fold that publication in or keep it separate is already asked in the issue, #118784 (comment). I would rather follow the answer there than widen this PR now.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dc5452e6c with master 602ce8d11 (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

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

Job report

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dc5452e

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / Timeout session-timeout overrun, not a test defect: the shard published 1604 OK + 35 SKIPPED and exactly one synthetic Timeout row whose context is ERROR: session-timeout occurred during test execution, with zero individual test failures. Wall 7433s against the 7200s session_timeout_parallel bound; the five sibling shards of the same run finished in 6179-6711s. #118384 (mine, open)
Mergeable Check aggregator status, red only because of the shard above: its own summary reads Failed: Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) #118384 (mine, open)
PR aggregator status, red only because of the shard above #118384 (mine, open)

Session id: cron:our-pr-ci-monitor:20260909-100059

{
/// `build` below moves `source` out, and `buildOrderedSetInplace` tests and dereferences it under
/// this mutex, so both in-place builders must hold it. Rationale at the other lock site.
std::lock_guard lock(inplace_build_mutex);

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.

At what point the second thread will understand that the set was already built and will bail out? In other words, how do we guarantee that there will be no attempt to build the same set for the second time.

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.

The second entrant does not bail at the top of buildSetInplace; it bails one frame down, in build(), on either of two predicates:

  • PreparedSets.cpp:420 if (set_and_key->set->isCreated()) return nullptr; (the set is already built), or
  • :430 auto plan = std::move(source); with :432 if (!plan) return nullptr; (an earlier in-place build already consumed the plan).

buildSetInplace then returns at :487 on the null plan. If that earlier build consumed source and threw, :427 rethrows the recorded failure instead of silently returning. Nothing ahead of the build() call rebuilds this set either: the statements in between are read-only or isCreated()-guarded (prepareForDistributedPlan, :447), and the external_table_set recursion at :466-467 bails on those same two predicates in its own build().

On the ordered path the same re-check is explicit and first after the lock: :530 if (auto set = get()), get() at :329 testing isCreated(), then :548 if (!source).

Both predicates predate this PR. What the lock adds is that they are now evaluated under the same mutex as the build that invalidates them. Before it, :420 and :430 ran unsynchronized against buildOrderedSetInplace, so two threads could both read "not created, source non-null" and both proceed, which is the reported race on the source handoff. Serialized, the second entrant reads state the first one finished publishing at :757-759.

One re-attempt is intentional: a speculative ordered build can stop without creating the set (subquery timeout with overflow_mode = 'break') while preserving source through a clone, and the next entrant retries it. That is why this is a mutex and not callOnce (:525-527).

The comment I added at the lock states only the source-handoff half, which is narrower than what the lock guarantees. Happy to push this wording instead if you prefer it:

/// Serializes with `buildOrderedSetInplace`: both in-place builders must test "already built"
/// (`isCreated()` in `build`) and consume `source` under the same mutex, or two threads can
/// both decide to build and then race on the `source` handoff.

@nickitat nickitat left a comment

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.

@groeneai isn't #118486 enough to fix the issue?

@nickitat nickitat self-assigned this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

For the race in #118784, yes. #118486 removes the second builder: it deletes the prepare callback that ran buildOrderedSetsForDAG on the manifest producer thread and does that build in IcebergIterator's constructor, before the producer thread exists. That is the PR I pointed the issue author at, and he noted on #115798 that the race is covered by it (#115798 (comment)). It has not merged yet, so if only one of the two lands, that is the one to keep.

This PR is not a second fix for that stack. It closes an asymmetry: inplace_build_mutex is taken by buildOrderedSetInplace (PreparedSets.cpp:528, line numbers from this branch) and not by buildSetInplace, so it serializes one of the two in-place builders. The write left outside it is build()'s std::move(source) at :430, which is the write side of the reported stack; the read it races with is :548, inside the lock.

What #118486 leaves, measured: its constructor build runs over the same manifest_filter_dag that createManifestIterator hands every ManifestFileIterator (IcebergIterator.cpp:363 and :436 on that branch), so the pruners the decode threads build (getOrCreatePruner -> ManifestFilesPruner -> KeyCondition) find those sets already created and return at :530. The exception is the retry the mutex comment itself describes at :525-527: a speculative build that stops without creating the set keeps source, and a decode thread retrying it reads source at :548 while an unlocked buildSetInplace can move it at :430. I have not reproduced that interleaving, which is why this is 4 lines restoring the invariant of 323aee4 ("Serialize FutureSetFromSubquery in-place builds") and not a fix for a second stack.

No behaviour change, and the mutex has two lock sites (PreparedSets.cpp:465 and :528), so there is no new lock ordering. If you would rather keep this to a single change, say so and I will close this PR.

@nickitat

Copy link
Copy Markdown
Member

@groeneai so, we should remove inplace_build_mutex once #118486 lands

@groeneai

groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

Yes, once one more path is closed, and closing it is two lines.

#118486 removes the state, not the sharing. On its head 96d5f29de, createManifestIterator still hands every ManifestFileIterator the same manifest_filter_dag (IcebergIterator.cpp:436), and each decode task builds its pruner key conditions over ActionsDAG::merge(renames, source_dag->clone()) with require_ready_sets = false, so the delete- and data-manifest decode tasks still call buildOrderedSetInplace on the same FutureSetFromSubquery. They stop at the created-set fast path at the top of it only because the constructor built the sets first. The state where they do not stop there is the retry 323aee4fbfe7fa0 names in its own comment: a build that stops without creating the set keeps source (a subquery timeout with overflow_mode = 'break'), and two decode tasks then enter the mutating region together. I have not reproduced that interleaving.

The two lines are require_ready_sets_ = true at the two KeyCondition constructions in ManifestFilesPruner (ManifestFilesPruning.cpp:156 and :180 on master; StatisticsPartPruner.cpp:177 does it for the same reason). tryPrepareSetIndexForIn then returns instead of force-building, in-place builds run only on the query thread, and the mutex has nothing left to serialize. Pruning is unchanged once #118486 prepares the sets in the constructor; only that break state skips manifest pruning instead of retrying the build off the query thread.

So I would drop this PR rather than have it add a lock to a mutex that is going away; close it whenever suits you, or keep it as an interim if you would rather not wait for #118486. Once #118486 lands I will send those two lines plus the removal of inplace_build_mutex and its lock site as one PR against master, or fold both into #118486 if you prefer. #118486 carries 05104_iceberg_path_filter_set_in_subquery, so the _path IN (SELECT ...) shape stays covered.

@nickitat

Copy link
Copy Markdown
Member

@groeneai let's leave a comment in #118486 asking to remove the lock with a proposed additional fix.

@nickitat nickitat closed this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done: #118486 (comment) (removal of inplace_build_mutex and its lock site, the require_ready_sets_ = true proposal at the two ManifestFilesPruner key conditions that makes it dead, and the one state that survives without it).

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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.

2 participants