Skip to content

Fix use-of-uninitialized-value in direct JOIN over a MergeTree table read with STREAM - #111622

Closed
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-msan-direct-join-stream-uninit
Closed

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-msan-direct-join-stream-uninit

Conversation

@groeneai

@groeneai groeneai commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Improves the stability of experimental STREAM queries that use a direct join against a MergeTree table after ALTER TABLE ... ADD COLUMN.

Description

Found by the AST fuzzer under MSan on PR #111492 (unrelated to that PR's changes). The MSan report itself lost its stack (nested error while writing), so the crashing query was recovered from the fuzzer log:

SELECT l.id, r.value, r.new_col FROM t_left AS l INNER JOIN t_right AS r STREAM ON l.id = r.id

with join_algorithm = 'direct', enable_analyzer = 1, enable_streaming_queries = 1, where r.new_col was added by ALTER TABLE t_right ADD COLUMN new_col String DEFAULT 'default_value'.

Root cause: ReadFromMergeTree::initializePipeline strips data parts from the storage snapshot (for the enable_remove_parts_from_snapshot_optimization / streaming path) by mutating storage_snapshot->data in place. ReadFromMergeTree::clone() copies the storage_snapshot shared pointer, so the original lookup plan and every clone share one StorageSnapshot. A direct JOIN rebuilds its lookup pipeline for each probe block (and the STREAM source rebuilds its sub-pipeline repeatedly), so one pipeline build replaced and destroyed a SnapshotData whose mutations_snapshot was still read by an overlapping build, giving MSan a use-of-uninitialized-value.

Fix: rebind this step's own storage_snapshot to a private clone via StorageSnapshot::clone(...) instead of mutating the shared snapshot in place. The clone keeps the same storage and metadata, only the stripped Data is private, so no build observes another build's destroyed SnapshotData.

CI report (MSan, AST fuzzer (amd_msan)): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111492&sha=1f9f9e0c14bca355fd9cf558efcb722aca37f1b9&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29

Reproduced locally on an MSan build (crash rate about 1 in 8 runs); with the fix it no longer reproduces (0 crashes over many runs) and results are unchanged for plain, LowCardinality, and Nullable added columns. Added a regression test that spawns the streaming direct-join query repeatedly and asserts the server stays alive.

…h STREAM

ReadFromMergeTree::initializePipeline strips data parts from the storage
snapshot by mutating storage_snapshot->data in place. ReadFromMergeTree::clone()
copies the storage_snapshot shared pointer, so the original lookup plan and every
clone share one StorageSnapshot. A direct JOIN rebuilds its lookup pipeline for
each probe block (and the STREAM source rebuilds its sub-pipeline repeatedly), so
one build replaced and destroyed a SnapshotData whose mutations_snapshot was still
read by an overlapping build, which MSan reports as use-of-uninitialized-value.

Rebind this step's snapshot to a private clone instead of mutating the shared one.

Found by the AST fuzzer under MSan on PR ClickHouse#111492 (unrelated to that PR).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes on demand under MSan: setup two MergeTree tables, ALTER t_right ADD COLUMN new_col String DEFAULT, then spawn SELECT l.id, r.value, r.new_col FROM t_left l INNER JOIN t_right r STREAM ON l.id=r.id with enable_streaming_queries=1, enable_analyzer=1, join_algorithm='direct', max_block_size=1 and kill it. Spawn-and-kill loop aborts the MSan server at about spawn #8.
b Root cause explained? ReadFromMergeTree::initializePipeline strips data parts from the snapshot by mutating storage_snapshot->data in place. ReadFromMergeTree::clone() copies the storage_snapshot shared pointer, so the lookup plan and all its clones share one StorageSnapshot. A direct JOIN rebuilds its lookup pipeline per probe block (and the STREAM source rebuilds its sub-pipeline repeatedly), so one build replaces and destroys a SnapshotData whose mutations_snapshot is still read by an overlapping build (MSan origin: "Member fields were destroyed" -> SnapshotData::~SnapshotData).
c Fix matches root cause? Yes: stop mutating the shared snapshot in place; rebind this step's own storage_snapshot to a private clone(...) carrying the stripped Data. Not a symptom guard.
d Test intent preserved / new tests added? New regression test 04545_direct_join_stream_mergetree_added_column.sh added (asserts the plan uses DirectKeyValueJoin, then spawns the streaming query repeatedly and checks the server stays alive). No existing test weakened.
e Both directions demonstrated? Yes. Pre-fix MSan build: test prints server died (server aborts, MSan use-of-uninitialized-value). Post-fix: test prints 1\nalive, server survives 16+30+3x20 runs with zero crashes.
f Fix is general across code paths? Yes: the in-place storage_snapshot->data = mutation was the sole occurrence (grep confirms none remain). The fix is at the snapshot-sharing layer, covering both the enable_remove_parts_from_snapshot_optimization and isStream() branches.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: the fix does not inspect the column type. Verified correct results for String, LowCardinality(String), and Nullable(String) added columns; matched and not-found keys; single- and multi-part inputs.
h Backward compatible? Yes: no setting, format, or behavior change. Pure internal object-lifetime fix; the stripped-snapshot read behavior is identical.
i Invariants and contracts preserved? Yes: clone() keeps the same storage and metadata, replacing only the private Data (exactly the state the old in-place strip produced). No caller relies on the pre-strip snapshot identity across the reassignment; all prior uses in initializePipeline read ->metadata or the ->data we intend to replace.

Session id: cron:clickhouse-author-slot-0:20260723-115200

@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 finding; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Regression test could pass without exercising the concurrent direct-JOIN lookup (query output discarded; omits enable_analyzer=1; randomized max_threads=1 might eliminate the overlap) AGREE in part / DISAGREE in part AGREED and applied: added an EXPLAIN-based assertion that the plan uses DirectKeyValueJoin and pinned --enable_analyzer=1 on the streaming query. DISAGREED on the max_threads claim with evidence: on the pre-fix MSan build the crash reproduces at --max_threads=1 (first spawn) as well as 2 and 3 — the overlap is across the STREAM source's repeated sub-pipeline rebuilds and the direct-join lookup clones, independent of query threads, so no max_threads pin is needed. Re-verified both directions after the change: pre-fix -> test fails ("server died"); post-fix -> test passes ("1\nalive").

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

Session id: cron:clickhouse-author-slot-0:20260723-115200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @antaljanosbenjamin - could you review this? It fixes an MSan use-of-uninitialized-value in a direct JOIN over a MergeTree table read with STREAM: the strip-parts optimization in ReadFromMergeTree::initializePipeline mutated a StorageSnapshot shared across cloned lookup plans, so an overlapping pipeline rebuild read a destroyed SnapshotData. Fix rebinds the step to a private snapshot clone.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6574412]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_llvm_coverage, 6/8) FAIL
test_storage_rabbitmq/test_system_stop.py::test_refresh_runs_once_while_start_keeps_consuming FAIL cidb
Stress test (arm_debug) FAIL
Logical error: Inconsistent KeyCondition behavior (STID: 5182-2f27) FAIL cidb
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
AST fuzzer (amd_debug) FAIL
Logical error: 'Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 6 (STID: 2270-3452) FAIL cidb

AI Review

Summary

This PR fixes a real lifetime issue in ReadFromMergeTree by rebinding the stripped StorageSnapshot to a private clone instead of mutating a snapshot shared across direct-join lookup plan clones. The C++ change itself looks coherent, but I’m requesting changes because the new regression can still pass without reliably proving that the fixed right-side direct-join ReadFromMergeTree path ran.

Tests
  • ⚠️ [tests/queries/0_stateless/04545_direct_join_stream_mergetree_added_column.sh:45-61] The wait loop keys off system.processes.read_rows, which is whole-query progress. In this join, the left/probe side can advance read_rows before DirectKeyValueJoin::joinBlock calls storage->getByKeys, so the loop can still kill a live query and count the iteration as success without ever rebuilding the fixed lookup plan. Please gate on a right-side-specific signal instead, e.g. ProfileEvents['JoinBuildTableRowCount'] > 0 after making the first probe block deterministically match.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 23, 2026
groeneai and others added 2 commits July 24, 2026 09:55
…anging

The regression test added in the previous commit was flaky and could hang CI:
it used only two left parts and killed the client without stopping the
server-side STREAM query, so the use-of-uninitialized-value reproduced on only
about half of the runs, and the streaming queries that outlived their clients
held the table locks. That made the flaky check fail intermittently and left
the query running at the end of the run, so the final DROP timed out and the
end-of-run hung check reported hung queries. Bugfix Validation (which runs the
new test once per arch on master HEAD, including under MSan) also often failed
to reproduce the crash and reported the test as not validating the fix.

Rework the test to trigger the bug on every run and to leave nothing running:
seven probe keys (only key 1 matches), each in its own part, so with
max_block_size=1 many direct-join lookup pipelines are rebuilt over the shared
StorageSnapshot and overlap. Repeat the streaming query 25 times, each under a
one-second client timeout (the bug is hit while the lookup pipeline is built,
so a short window per query is enough). After the loop, KILL any streaming
query that outlived its client and wait for it to leave system.processes before
dropping the tables, so the DROP cannot hang and the end-of-run hung check stays
clean. Assert that the exact STREAM query plans through the direct join and that
the non-STREAM form of it runs and fills the ALTER-added column, so the test
fails loudly if it stops exercising the fixed path. Also tidy the code comment
added by the fix.

Verified under MSan: the pre-fix server aborts on every run and the fixed
server passes with no hang.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…d server

The test is run against master HEAD by Bugfix validation, where the
use-of-uninitialized-value is present and the STREAM direct-join corrupts
the server. The unbounded KILL QUERY ... SYNC and processlist drain then
blocked forever against the dead server, hanging the amd64 Bugfix
validation job to the 18000s run timeout instead of failing cleanly.

Hard-bound and make best-effort the liveness check, KILL QUERY, drain and
DROP steps. On a healthy server every bound is a no-op and SYNC still
confirms the streaming queries are gone before the DROPs, so the fix path
and the flaky check are unchanged; on the pre-fix binary the test now
terminates in seconds while still reproducing the bug.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…died

The previous revision bounded every cleanup step with `timeout ... || true`
unconditionally, so on a live server a genuine failure (KILL SYNC not
completing, the process list never draining, or a DROP blocked on a leaked
STREAM query) was swallowed and the test still printed "alive" and passed.
That weakened the regression contract and could leak the query/table-lock
state the test is meant to clean up.

Gate cleanup strictness on a liveness probe, mirroring clickhouse-test's own
_cleanup_database ("best-effort only when the server is actually dead"): if
the server is up, KILL/drain/DROP must genuinely complete or the test prints
"cleanup incomplete" and fails; only a confirmed-dead server (the pre-fix
binary aborting under MSan during Bugfix validation) skips cleanup and fails
fast via the missing "alive". Every step stays time-bounded, so even a wedged
live server fails in seconds instead of hanging the job to its timeout.

The source fix and the STREAM loop that reproduces the use-of-uninitialized
value are unchanged.
… timeout

The live-server cleanup path set a flag on a timed-out step but kept running
the remaining drain loop and both DROPs, so a wedged-but-live server could
still burn up to 60 + 60*(5+0.5) + 60 + 60 = 510s before printing
"cleanup incomplete". That is the exact case this revision was meant to
bound. Move the KILL/drain/DROP steps into a helper that returns non-zero on
the first bounded step that times out, so the outcome (already doomed to
"cleanup incomplete") is printed immediately and the rest is skipped. The
healthy path is unchanged: every step passes quickly and prints "alive".

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Jul 25, 2026
groeneai and others added 3 commits July 25, 2026 02:04
The regression loop launched each direct-join STREAM query under timeout 1 and
tore it down after one wall-second. On a slow server the client can time out
during handshake or planning, before the query enters
ReadFromMergeTree::initializePipeline (the path this PR fixes), so the test
could go green without ever exercising the bug. Now each STREAM query runs in
the background and is only killed after it registers in system.processes, which
proves it reached execution. The dead-server and wedged-server failure paths are
unchanged and still bounded.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ive server

The wait-for-registration loop exited on three conditions: probe error, the
query registering, or the 30s window expiring. In the last case the query was
never observed in system.processes, yet the iteration still tore the client
down and, on a live server, counted as success. On a slow server that could
let the test reach "alive" without any iteration provably entering
ReadFromMergeTree::initializePipeline, the path this PR fixes.

Track whether the query registered and, on a live server where it did not
within the window, print a distinct line and stop so the diff against the
reference fails the test instead of a silent pass.

Test-only change; the source fix is unchanged.
The wait loop that guards the KILL/tear-down previously exited as soon as the
STREAM query was visible in system.processes. That is not proof it reached the
fixed ReadFromMergeTree::initializePipeline path: ProcessList::insert makes a
query visible before the executor is attached (see
04410_primes_source_cancellation.sh), so an iteration could register and be
killed before the streaming read ever ran, and the test could pass without
exercising the fix.

Gate on an execution-side signal instead: wait for read_rows>0 in
system.processes (the pattern used by 04039_merge_tree_snapshot_teardown_race.sh)
before killing the query, and fail the iteration ("stream query did not start")
if no row is read within the window on a live server. read_rows>0 means the
executor is attached and the MergeTree read is producing rows.

Test-only change; the C++ fix is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
reached=0
q_start=$EPOCHSECONDS
while (( EPOCHSECONDS - q_start <= 30 )); do
rr=$(timeout 5 $CLICKHOUSE_CLIENT -q "SELECT max(read_rows) FROM system.processes WHERE query_id = '$qid'" 2>/dev/null) || break

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.

read_rows here is still query-global progress, not a right-side lookup signal. system.processes / query_log define it as rows read by the whole query, and JoiningTransform::readExecute only calls join->joinBlock after the left probe block has already been materialized. That leaves a live-server window where t_djs_left has bumped read_rows, this loop sets reached=1, and the test kills the query before DirectKeyValueJoin::joinBlock / storage->getByKeys ever rebuild the right-side lookup plan. In that case the iteration still counts as success without touching the fixed ReadFromMergeTree.

Please wait on a lookup-specific signal instead. One workable option is to make the first probe block deterministically match and gate on ProfileEvents['JoinBuildTableRowCount'] > 0 in system.processes; another is any other counter tied specifically to the direct-join lookup build path.

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 pre-fix binary aborts the server while running this exact test: the post-loop liveness probe then prints "server died", which mismatches the "alive" reference and fails the test. A binary cannot abort on a code path it never executes, so the differential (fails on the pre-fix binary, passes on HEAD) is itself proof the loop drives execution into ReadFromMergeTree::initializePipeline; read_rows > 0 only ensures each iteration runs far enough to matter before the KILL.

I already tried gating on JoinBuildTableRowCount > 0 and it is flaky for this fixture: only key 1 of the seven probe keys matches the single right row, so for the other six lookups the counter stays 0, and it does not reliably surface as >0 in system.processes before the query is killed. On a healthy live server that gate false-fails with "stream query did not start". Making the first block deterministically match does not remove that lag, because the counter is observed asynchronously through system.processes. A flaky gate is worse than the current one, which passes the amd_msan / amd_debug / amd_tsan flaky checks on this head.

Keeping the read_rows > 0 gate. Leaving the rest of this test-shape discussion for human review.

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6574412

Every failure below has an owner. The new regression test 04545_direct_join_stream_mergetree_added_column added by this PR now passes across every job it runs in (flaky-check amd_debug/amd_msan/amd_tsan/arm_asan_ubsan, and all regular parallel jobs), so none of the failures below are PR-caused; each is a pre-existing trunk/flaky failure with an open fixing PR.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Invalid number of columns in chunk pushed to OutputPort (STID 2270-3452) trunk bug (15 unrelated PRs, 0 master in 30d) #111401 (ours, open)
Stress test (arm_debug) / Inconsistent KeyCondition behavior (STID 5182-2f27) trunk bug (116 PRs, 8 master in 30d) #109023 (ours, open)
Integration tests (amd_llvm_coverage, 6/8) / test_storage_rabbitmq/test_system_stop.py::test_refresh_runs_once_while_start_keeps_consuming flaky (18 PRs, 1 master in 30d) #111480 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log (Code 27 version-metadata parse / part intersects) upgrade forward-compat error leak #111772 (ours, open)

Session id: cron:our-pr-ci-monitor:20260725-113000

@PedroTadim

Copy link
Copy Markdown
Member

cc @Michicosun

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

This is no longer needed

@PedroTadim PedroTadim closed this Oct 9, 2026
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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants