Repository navigation
Conversation
Fuzzing a CREATE MATERIALIZED VIEW renames the view but leaves its external TO target untouched (create.setTable in QueryFuzzer::fuzzCreateQuery; nothing in that file writes ASTCreateQuery::targets). The resulting view therefore shares both its source and its target with the view it was derived from, so a single INSERT into that source builds two sinks for the same target. When the target accepts only one write() per INSERT - IStorage::supportsParallelInsert() is false, which for the Log family means StorageLog::write takes an exclusive lock that LogSink holds as a member from pipeline build until onFinish - the second sink cannot acquire it while the first lives. It waits out lock_acquire_timeout and throws Code: 159, and because the INSERT re-arms, the processlist never empties and the stress test hung check fails on it. That red hides whatever the run would otherwise have surfaced. Observed on three build flavours, including a master run: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110166&sha=c890bb8e35d0d9138c1fa770e1fd4a1db05f39bf&name_0=PR&name_1=Stress%20test%20%28arm_release%29 Skip such a fuzzed query instead of creating the view. Whether it is hazardous is a sink-graph question, so it is answered inside InsertDependenciesBuilder, which owns that graph, rather than modelled a second time in the fuzz loop: the new predicate walks the same edges collectAllDependencies follows (a view's own target plus getDependentViews), validates each view hop against a stale dependency the way observePath does, tests capability only on concrete sinks because createSinkImpl never writes to a view, and resolves Alias and proxy hops to their target since supportsParallelInsert already forwards through them. Buffer and Distributed end a branch: both support parallel insert and hand the data to a separate INSERT, so a duplicated branch reaching one of them duplicates no sink of this query. Measured: neither wedges, while the existing forwardedInsert* probes - which answer a deduplication question, not this one - report a hazard for both and for Alias(MergeTree) -> view -> Memory, so delegating to them would have stopped fuzzing safe topologies. The predicate is deliberately precise rather than conservative, so shared-target view fuzzing keeps running wherever it is safe, and a sole writer of a non-parallel target - a supported configuration - is unaffected. Anything the check cannot decide (an absent id, an unresolvable table, a cycle, or a throw out of the dependency extractor, which checkAllowedQueries does unconditionally for the PREWHERE, SAMPLE and FINAL shapes the fuzzer injects) executes normally and is counted, so an undecided answer can never suppress fuzzing. On a skip the clone's recorded name is withdrawn through the fuzzer's existing notifyQueryFailed, since later mutations retarget table references to those names; without it, phantom names reach subsequent queries. Two ProfileEvents make both outcomes attributable: ASTFuzzerSkippedSharedNonParallelTarget and ASTFuzzerSkipCheckFailed. The path is confined to ast_fuzzer_runs > 0, so no production query, storage, planner or parser behaviour changes. Reference points for the mirrored rules: InsertDependenciesBuilder.cpp:1484-1496 (stale-edge validation), :1661-1670 (the two expansion edges), :1871-1875 (a view is never written to), :1084-1085 (views exempt from the capability test). Related: ClickHouse#110166
…ts, add the regression test Review round 1. A lazily loaded table is wrapped in a proxy that renames the storage it wraps to the proxy's own StorageID, so continuing the walk by that id re-entered the node the walk was standing on and was read as a cycle. Since the cycle flag was function-scoped and tested only at the top level, one such table anywhere in the reachable graph made the whole predicate answer "not hazardous" and the guard became a complete no-op for that database. The walk now continues on the already resolved StoragePtr, takes no visited-set entry for that hop, and bounds the hops with max_insert_forwarding_depth, the constant the sibling forwarding probes use. The predicate returns a tri-state instead of a bool, so the exits that cannot answer (a cycle, an unresolvable table, absent dependency edges, the depth cap) are counted through ASTFuzzerSkipCheckFailed like the exception boundary already was, instead of being read as safe. The fail-open behaviour is unchanged: an undecided verdict still executes the query. The dependent-view expansion is skipped at a storage an INSERT itself targets when that storage has noPushingToViewsOnInserts(), matching what createChainWithDependencies builds: those views are written by the background consumer, not by that INSERT. The Buffer and Distributed claim is narrowed to what is proven. Their forwarded write runs synchronously inside this pipeline's sink (BufferSink::consume -> writeBlockToDestination -> InterpreterInsertQuery), so a topology mixing a forwarded and a direct branch into one Log-family table does wedge, and this walk does not model it. Modelling a Buffer's destination was measured and rejected: it would skip three topologies a clone actually produces, all of which are safe, while the mixed shape needs a fixture that wedges without any fuzzing. 04876_ast_fuzzer_skips_duplicate_non_parallel_sink asserts both counters with a positive control, and covers the lazily loaded storage and the undecided path. It fails with the skip removed and with the proxy hop reverted. The undecided assertion compares against the executed count rather than against zero, because that counter also fires when the dependency extractor throws on a shape the fuzzer injected.
…ew branch Round-2 review fixes. The no-push root exemption modelled only the direct-INSERT path. A Kafka-family storage is also the source of its background consumer's insert, which is built with no_destination and does create a sink for every dependent view (createChainWithDependencies takes the createPostSink branch on `|| skip_destination_table`). A clone sharing such a source and one Log-family target therefore wedges exactly as a plain source does, so the exemption opened the hole it was meant to tidy. Taking the views unconditionally makes the walk a superset at such a node: it can cost fuzz coverage, never miss a wedge. The new view's target branch was also not always examined. QueryFuzzer retargets a view's SELECT source to a live clone of the same original table, so the source side can be empty while the target branch alone already converges on one non-parallel sink through two views. The early return skipped that case, and collecting into a set collapsed the two reaches into one entry with nothing to intersect. Both walks now run and the sinks are counted; the edge-keyed memoization admits each live edge once, so two counts are two distinct sinks. The regression test could not have survived the Stress job whose hung check this work exists to fix. --replace-log-memory-with-mergetree rewrites the Log and Memory fixtures the oracle rests on, so the test opts out via log-engine. ignore_drop_queries_probability, which the runner appends unconditionally, turns a DROP of a storage that keeps no data on disk into a TRUNCATE, so the fixture is created once and the setting is pinned. The lazy-load database is parameterized because no-parallel only serializes within one clickhouse-test process while Stress runs several against one server, and no-replicated-database is added for the lazy-load section and the DETACH TABLE.
The walk that decides whether a fuzzed CREATE MATERIALIZED VIEW would make one
INSERT build two sinks on a storage taking a single write() per INSERT admitted
each dependency edge once for the whole walk. Where two live parents converge on
one subtree, that suppressed the subtree's second visit, so its non-parallel sink
was counted once and the view was reported safe - while the builder attaches the
downstream view under both parents and does build two sinks. Reproduced on
mt0 -> {mv_a, mv_b} -> mt1 -> mv_c -> lg(TinyLog), where an INSERT INTO mt0 fails
with TIMEOUT_EXCEEDED waiting out lock_acquire_timeout on lg.
An edge is now admitted once per path, which is what makes a second count a
second sink. Counting per path enumerates paths, so two things bound it: the walk
ends as soon as a duplicate is proven (no later count can change that answer), and
only the deciding walk counts per path - the first walk's result is read for
membership alone, so it keeps the cheaper once-per-walk suppression. Without
either, a graph with ten views per level over four levels exhausts the visit
budget and reports Undecided, i.e. executes a view that does wedge.
Also: a queue engine sets noPushingToViewsOnInserts, so a direct INSERT into it
pushes to no view, but its background consumer inserts with no_destination and
does build a sink per dependent view. Test coverage for that path was missing,
and its absence is what let an earlier root exemption look harmless.
The undecided counter is renamed to ASTFuzzerSharedNonParallelTargetCheckUndecided:
it counts neither a skip nor a query, and an undecided verdict is a designed
outcome rather than a failed check.
The test's claims that a delta is exactly zero are replaced by bounds against the
section's own executed delta. no-parallel serializes within one clickhouse-test
process, while the stress runner drives several against one server, so a foreign
fuzzed query can inflate these server-global counters; measured under a concurrent
fuzzing process the exact-zero form failed 15 of 15 runs and the bounded form
passed 30 of 30.
Co-Authored-By: Claude Fable 5 <[email protected]>
The undecided section compared a server-global undecided counter against a server-global executed counter. Both sides move under a concurrent fuzzing process, so the claim was same-window: a foreign decided query inflated only the executed side. It failed 6 of 15 runs against a second fuzzing process. Count this section's own clones out of system.query_log instead. A withdrawn clone never reaches execution and so is never logged, while an executed one always is, and the rows are keyed by both currentDatabase() and a log_comment token that the fuzzer propagates to every clone. A foreign process can now only raise the left side, which makes the inequality one-sided in the safe direction. undecided_not_skipped measured the same fact through the global skip counter and is dropped. Surviving clone tables cannot serve as the observable here: the fuzzer keeps the original view's UUID clause on every clone, so the clones collide with each other and with the original, and none survives. The predicate's header contract keeps only what a caller cannot read off the signature. The mechanism it carried is documented at each implementation site already, and is recorded here for the reader who wants it in one place: both the graph reachable from the source and the branch the new target starts are walked over the edges collectAllDependencies follows, that is a view's own target plus getDependentViews, validating each view hop against a stale dependency the way observePath does. Dependent views are taken at every node, including one whose noPushingToViewsOnInserts holds and whose views only its background consumer's insert builds, so the walk is a superset there. Capability is tested only on concrete sinks, because a view is written through and never to, and Alias and proxy hops resolve to the storage they hand the write to, which materializes and starts up a lazily loaded one. Undecided covers an unresolvable table, a cycle, and a chain deeper than max_insert_forwarding_depth. The withdrawal comment states the standing invariant instead of describing this change.
The undecided section counted its own fuzzed clones out of system.query_log using current_database and a constant log_comment token. Both predicates separate a foreign fuzzing process, but neither separates an earlier run of this same file: the token is byte-identical on every run, and the case that produces a re-run against one database is precisely a fixed --database, which the stress runner passes for every odd worker and which the retry loop reuses. The second run then counted both runs' clone rows against only its own counter delta, so a transient failure became a hard, non-retryable one. Capture a microsecond boundary from the server immediately before the fuzzed CREATE and require the counted rows to start after it. Measured over 20 paired runs against one fixed database: the unbounded scan held 1, the bounded scan 20. Also drop each materialized view up front. A view does not disappear with its source table, so a run that aborts before its section's unconditional drops leaves the view behind and the next run fails TABLE_ALREADY_EXISTS. Both changes are test-only; the reference file is unchanged.
…iew pair The duplicate-sink predicate read `proven` only at function entry and at the final verdict, so a frame that had already proven a duplicate kept walking: it iterated the remaining dependent views and then reached the `Buffer`/ `Distributed` casts, the `Alias` hop and `StorageProxy::getNested`, which materializes and starts up the storage it wraps and can throw. The escaped exception was rewritten to `Undecided` and the hazardous CREATE ran, against the predicate's stated contract of never erring past a real hazard. The walk now leaves as soon as a proof exists, and the two top-level walks are wrapped so a throw degrades the answer to unknown instead of discarding a proof already reached. `Hazardous` is tested before `undecided`, so nothing-proven still yields `Undecided` and the fail-open behaviour is unchanged. Measured with a base binary carrying a log-and-rethrow probe: in the shape where the throwing proxy is itself the node whose dependent views prove the duplicate, 35 completed proofs were discarded in one 60-run loop. With the change the same fixture skips 37 of 60 while a control fixture carrying the throw but no provable duplicate stays at 0 skips on both binaries. The answer is also derived from the catalog, where a view appears only once its CREATE has executed, so two concurrent fuzz callbacks on one (source, target) pair could each be told the target is reached once and each build one of the two sinks. A reservation keyed on that pair now spans the decision and the fuzzed CREATE; a callback that finds it held withdraws the query exactly as the existing skip path does. Keying on the pair rather than the source keeps two views from one source onto different targets fuzzable. The regression test drops its undecided-arm target instead of detaching it (both make the branch unresolvable, measured 30 undecided of 30 either way), because a detached table is invisible to DROP and survived a failed run, and it drops the lazy-proxy database with SYNC.
Four assertions compared server-global ProfileEvents deltas. The skip event is incremented in the query-finish callback and the loop then continues, while ASTFuzzerQueries is incremented only on the execution path, so a fuzzed query from another process raised the skip side of each comparison without raising the executed side, and a foreign skip could satisfy one outright. `no-parallel` serializes one clickhouse-test process while the stress runner drives several against one server, so the tag does not close that gap. Each of the four now counts this file's own clones out of query_log, keyed on the database, a per-section log_comment and a boundary timestamp taken from the server, and compares the safe section against the hazardous one: a withdrawn clone never reaches execution and is therefore never logged, so neither side can be moved by another process. Measured margin over five trials: 1-7 of 30 logged in the hazardous section against 29-30 of 30 in the safe one. Eight mutations, one per rewritten line plus one per comparison, each flip exactly their own assertion and nothing else, with the unmutated text green. Every fixture a fuzzed statement can touch now lives in a second database that the file drops up front and again at the end. A clone survives its own statement and no fixed DROP list can name it: a single clean pass left 8 to 17 such views behind, and one whose target was later dropped turned the next run's INSERT into UNKNOWN_TABLE. With a fixed --database the runner neither creates nor drops the per-test database, so the second run in one database used to fail; 32 consecutive runs in one database now pass with nothing left behind. Clones are created in the database of the view, so dropping that database removes all of them at once.
The answer describes the catalog at the moment of the call, and a view enters the catalog only when its CREATE has executed, so two creations of the same view that are both still unregistered are each answered as though the other did not exist. The fuzzer caller holds a reservation across that window; any other caller with the same requirement needs one too, so the contract now says so instead of leaving it to be rediscovered.
Internal second-model review - 7 rounds; 5 findings ship unfixed and are listed hereIndependent cold review plus a second-model gate each round, adjudicated against recorded evidence. Fixed in earlier rounds
Shipping unfixed❌ The reservation does not span asynchronous DDL. With ❌ A convergent topology is not serialized by a pair-scoped key. If targets
What the test does establish30/30 green under a deliberate concurrent adversary on the exact shipped text (sha256 pinned before and Session id: cron:clickhouse-review-slot-9:20260813-061700 |
|
Workflow [PR], commit [fe51aca] Summary: ❌
|
Pre-PR validation gate (click to expand)
|
|
cc @al13n321 @davenger, could you review this? Fuzzing a CREATE MATERIALIZED VIEW renames the view but leaves its external TO untouched, so the clone shares source and target with the original and one INSERT builds two sinks for a storage that takes a single write() per INSERT, wedging on lock_acquire_timeout until the stress hung check fires; this asks InsertDependenciesBuilder whether the new view would duplicate such a sink and withdraws the fuzzed query if so. |
|
@groeneai are you sure the solution is on the AST fuzzer itself? |
|
No, I am not sure, and my own measurement argues against it. The #74080 repro still fails on current master with no fuzzer and no concurrency: I should also correct my own PR body. I cited #74080 as the topology having been "answered as unsupported"; that is too strong. It was closed by the reporter after a contributor's reply, not by a maintainer ruling, and the reporter's own comment asks for it to be disallowed instead. If the engine is the right layer, the fork is whether two writers onto one |
|
@alexey-milovidov maybe the solution is to disable more than one materialized view into a single Log table |
|
Measured how wide that rule would have to be, since that is the part I could settle by running it. On unpatched master, two materialized views
So the carrier set is exactly the One constraint on where the refusal goes: those I will leave #114599 as is until you decide, and close it if the engine-level fix is what you want. |
…cate-non-parallel-sink Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Related: #110166
Reported by @ alexey-milovidov there: a
Stress test (arm_release)hung check on anINSERTstuck inStorageLog::write.https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110166&sha=c890bb8e35d0d9138c1fa770e1fd4a1db05f39bf&name_0=PR&name_1=Stress%20test%20%28arm_release%29
It is not lock contention under load. Fuzzing a
CREATE MATERIALIZED VIEWrenames the view but leaves itsexternal
TOuntouched, so the clone shares source and target with the original and oneINSERTbuildstwo sinks for that target.
LogSinkholds the table's exclusive lock from pipeline build untilonFinish, so the second sink waits outlock_acquire_timeoutand throwsCode: 159; theINSERTre-arms, the processlist never empties, and the hung check fails. Reproducible in 4 statements with no
concurrency and no fuzzer, on three build flavours.
This skips such a fuzzed query instead of creating the view. Whether it is hazardous is a sink-graph
question, so it is answered in
InsertDependenciesBuilder, which owns that graph, and it errs onlytowards skipping: safe shared-target fuzzing keeps running, and a sole writer of a non-parallel target is
unaffected.
BufferandDistributedend a branch, since the write they forward runs as anINSERToftheir own whose sinks this walk does not model. Anything the walk cannot decide executes normally and is
counted, so an undecided answer never suppresses fuzzing. Two
ProfileEventsmake both outcomesattributable; the path is confined to
ast_fuzzer_runs > 0.A proven duplicate survives a later branch that throws while materializing a lazy storage. And since the
answer describes the catalog, where a view appears only once its
CREATEhas executed, the fuzzerreserves the (source, target) pair across the decision and the create; the contract states that boundary.
Refusing two writers on one
Log-family target at INSERT planning time is out of scope: that isuser-visible, and on #74080 the same topology was answered as unsupported.
Validation
Ground truth measured on a pre-fix binary by building the duplication by hand, against the predicate's
verdict on the same 9 topologies (agreement is 9/9):
src -> mv -> tgt(TinyLog)src -> mvA -> mt(MergeTree) -> mvB -> lg(TinyLog)Alias-hidden:mv TO Alias(mt),mt -> mv2 -> lgmt1..mt8 -> lgAlias(MergeTree) -> view -> MemoryBufferDistributedMODIFY QUERYaway frommt)MergeTreePlus the hazard behind a lazily loaded table (
lazy_load_tables, wedges pre-fix, skipped) and itsMergeTreecounterpart (skipped in neither).Through the real carrier (
--ast_fuzzer_runs=40 --ast_fuzzer_any_query=1): pre-fix theINSERTfailsCode: 159; with the fix the hazardous arms are skipped, the insert completes, and the safe arms areuntouched. Removing the skip restores the failure; removing the name withdrawal makes 345 of 480 later
fuzzed queries name a view that was never created (0 with it).
04876_ast_fuzzer_skips_duplicate_non_parallel_sinkstates each claim against its own fixture'squery_log rows rather than server-global counters, so a concurrent fuzzing process cannot move them: 30/30
green under a deliberate adversary, 50/50 randomized green, 32 consecutive runs in one database with
nothing left behind, and eight mutations each flipping exactly their own assertion. It fails with the skip
removed (
Code: 159) and with the proxy hop reverted.Workflow [PR]
Sync PR [sync-upstream/pr/114599]