Skip to content

AST fuzzer: do not create a view that duplicates a non-parallel sink - #114599

Open
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:ast-fuzzer-no-duplicate-non-parallel-sink
Open

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:ast-fuzzer-no-duplicate-non-parallel-sink

Conversation

@groeneai

@groeneai groeneai commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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 an INSERT stuck in
StorageLog::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 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 that target. LogSink holds the table's exclusive lock from pipeline build until
onFinish, so the second sink waits out lock_acquire_timeout and throws Code: 159; the INSERT
re-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 only
towards skipping: safe shared-target fuzzing keeps running, and a sole writer of a non-parallel target is
unaffected. Buffer and Distributed end a branch, since the write they forward runs as an INSERT of
their 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 ProfileEvents make both outcomes
attributable; 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 CREATE has executed, the fuzzer
reserves 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 is
user-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):

topology wedges pre-fix skipped
src -> mv -> tgt(TinyLog) yes yes
src -> mvA -> mt(MergeTree) -> mvB -> lg(TinyLog) yes yes
Alias-hidden: mv TO Alias(mt), mt -> mv2 -> lg yes yes
deep cascade mt1..mt8 -> lg yes yes
Alias(MergeTree) -> view -> Memory no no
directly shared Buffer no no
directly shared Distributed no no
stale edge (MODIFY QUERY away from mt) no no
shared MergeTree no no

Plus the hazard behind a lazily loaded table (lazy_load_tables, wedges pre-fix, skipped) and its
MergeTree counterpart (skipped in neither).

Through the real carrier (--ast_fuzzer_runs=40 --ast_fuzzer_any_query=1): pre-fix the INSERT fails
Code: 159; with the fix the hazardous arms are skipped, the insert completes, and the safe arms are
untouched. 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_sink states each claim against its own fixture's
query_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]

groeneai and others added 10 commits August 12, 2026 09:10
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 7 rounds; 5 findings ship unfixed and are listed here

Independent cold review plus a second-model gate each round, adjudicated against recorded evidence.
Findings that survived earlier rounds are fixed in this branch. The review budget for this change is now
spent, so the five remaining findings ship unfixed rather than being quietly dropped. All five bound a
safeguard this PR adds; none is a regression against current master, where the hazard is unguarded.

Fixed in earlier rounds

# Finding Verdict
❌ A lazily loaded target is reached through a proxy that renames the wrapped storage to the proxy's own id, so re-entering by id read the hop as a cycle and reported the graph safe AGREE, fixed
❌ Root exemption for queue engines (Kafka/FileLog/NATS/RabbitMQ) skipped the dependent-view walk, but the background consumer's insert does push those views AGREE, fixed
❌ The new view's branch was not walked when the source had no sinks yet, and duplication inside that branch collapsed in a set AGREE, fixed
❌ Multiplicity collapsed where two live parents converge on one subtree: the builder attaches the shared view under both parents and creates two sinks AGREE, fixed
❌ A duplicate already proven was discarded when a later branch threw while materializing a lazy storage AGREE, fixed
⚠️ An undecided verdict was read as safe; it is now a distinct counted outcome that executes the query AGREE, fixed
⚠️ Test could not survive two Stress test randomizations (--replace-log-memory-with-mergetree, ignore_drop_queries_probability) AGREE, fixed
⚠️ Counter assertions were server-global; four of six now count this fixture's own executed clones out of query_log AGREE, fixed
⚠️ A stranded DETACHed table left the next run undroppable AGREE, fixed (DROP instead)
💡 Comment volume and the API contract on the new predicate AGREE, trimmed; mechanism moved to the commit messages
⚠️ Asked to model a Buffer/Distributed destination DISAGREE: both report supportsParallelInsert() == true and forward through a separate INSERT; the shapes a clone can produce measured safe on both binaries, so modelling them would skip safe topologies

Shipping unfixed

❌ The reservation does not span asynchronous DDL. With distributed_ddl_task_timeout = 0 an
ON CLUSTER statement returns as soon as it is enqueued (executeDDLQueryOnCluster.cpp:207), while the
(source, target) reservation is scoped to one fuzz-loop iteration, so several renamed views could be
approved before the first dependency is registered. Narrower than it reads: the fuzzer never assigns
ASTCreateQuery::cluster, so a fuzzed CREATE MATERIALIZED VIEW is ON CLUSTER only if the seed
statement already was, and a Replicated-database internal re-execution is excluded upstream. Narrow is
not zero.

❌ A convergent topology is not serialized by a pair-scoped key. If targets a and b each have a
dependent view writing one TinyLog, two simultaneous fuzzed views onto a and b take different keys.
The in-source comment claiming "two views from one source onto different targets never share a sink" is
therefore too strong, and should be read as scoped to the reservation rather than to the sink graph.
The sequential case is covered, since the predicate proves the duplicate against the sinks the source
already reaches, so the gap is confined to two simultaneously unregistered views. Three independent
oracle designs failed to produce it: over 82 clone CREATE MATERIALIZED VIEW statements with spare
targets present, 0 were retargeted, because fuzzTableName only rewrites a name to a clone of the same
original.

⚠️ The proof-precedence fix has no in-tree test. The committed test cannot cover it: its lazy section
resolves successfully and its undecided section never first proves a duplicate. It was validated by a
declared synthetic three-line getNested throw in a scratch build (live arm 0 -> 37 skips, 0 on both
binaries in the throw-only control), because every candidate engine constructs fine and throws only on
read, which this predicate never performs. The mutation is not in the committed tree.

⚠️ Two assertions still read a server-global counter. undecided_counted and
queue_source_clone_skipped compare against server-wide event deltas, so a concurrent fuzzing process
can supply an event this fixture did not generate; and queue_source_safe_target_not_skipped is a strict
> between two stochastic counts (measured margin 29-30 of 30 against 1-7 of 30, wide but not
structural).

⚠️ The DETACH/ATTACH DATABASE pair can still strand a database. ATTACH can fail while loading
tables, and a detached database is invisible to DROP DATABASE IF EXISTS with no SQL-level recovery. The
vulnerable interval was reduced from a 30-run fuzz loop to two adjacent statements with nothing fallible
between them. Reaching it needs a second run of this file in one fixed database, which only the retry
loop produces.

What the test does establish

30/30 green under a deliberate concurrent adversary on the exact shipped text (sha256 pinned before and
after, adversary liveness asserted), 50/50 randomized green, 32 consecutive runs in one database with
nothing left behind, eight mutations each flipping exactly their own assertion, and a hard failure with
the skip removed (Code: 159) or the proxy hop reverted.

Session id: cron:clickhouse-review-slot-9:20260813-061700

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe51aca]

Summary: ❌

job_name test_name status info comment
Style check FAIL
catch_all FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Four statements, no concurrency, no load, no fuzzer: two materialized views TO one TinyLog over a shared source, then INSERT. With lock_acquire_timeout = 5 it fails in ~5 s with Code: 159 Lock timeout exceeded: while writing to target table ... of materialized view .... Round 3 adds a second, distinct deterministic repro for the convergent shape: mt0 -> {mv_a, mv_b} -> mt1 -> mv_c -> lg(TinyLog), where INSERT INTO mt0 fails the same way naming mv_c.
b Root cause explained? Yes. Fuzzing a CREATE MATERIALIZED VIEW renames the view (create.setTable) but nothing writes ASTCreateQuery::targets, so the new view keeps the original external TO and shares source and target with it. One INSERT then builds two sinks for that target. StorageLog::write takes an exclusive lock that LogSink holds as a member from pipeline build until onFinish, so sink 2 cannot acquire it while sink 1 lives: it waits out lock_acquire_timeout, throws, and the INSERT re-arms, so the processlist never empties and the hung check fails.
c Fix matches root cause? Yes. It stops the fuzzer creating the duplicating view. Not a widened bound, a no-random-* tag, a data reduction, or a guard at the failure site.
d Test intent preserved / new tests added? Yes, and no test is weakened or removed. tests/queries/0_stateless/04876_ast_fuzzer_skips_duplicate_non_parallel_sink.sql is added, modelled on 04305_ast_fuzzer_skips_backup_restore: it snapshots both new ProfileEvents from system.events, asserts the hazardous clone is skipped and the INSERT completes, carries a positive control (two views on one MergeTree target keep being fuzzed and the skip counter stays put, proving the counters are live), and covers the lazily-loaded-storage and undecided paths. The undecided section counts its own fuzzed clones out of system.query_log, keyed by currentDatabase(), a log_comment token and a server-side boundary timestamp captured immediately before the fuzzed CREATE, rather than comparing two server-global counters: a withdrawn clone is never logged and an executed one always is, so a concurrent fuzzing process can only move the comparison in the safe direction, and the boundary keeps an earlier run of this same file against a fixed --database out of the count. Round 6 removes the last server-global claims: all four counter comparisons now read this file's own query_log rows, keyed on the database, a per-section log_comment and a server-side boundary, and compare the safe section against the hazardous one (measured margin 1-7 of 30 against 29-30 of 30), so no foreign process can move either side. Every fixture a fuzzed statement can touch was moved into a second database the file drops at both ends, because a clone survives its own statement under a name no fixed DROP list can spell: a single clean pass left 8-17 such views behind and the second run in one database used to fail with UNKNOWN_TABLE; 32 consecutive runs in one database now pass with nothing left behind. It passes 50/50 with randomized settings, holds 30/30 under a concurrent fuzzing process on the shipped text (sha256 recorded before and after, foreign skip rate 147 per 5 s), and fails on the skip block removed, the proxy hop reverted, the undecided counter misattributed, and eight further mutations that each flip exactly one rewritten assertion with the unmutated text green. It is also verified against the two Stress randomizations it would otherwise have flaked on: it opts out under --replace-log-memory-with-mergetree (which rewrites the very Log/Memory fixtures the oracle needs), and passes 15/15 under ignore_drop_queries_probability=0.2 where the earlier fixture shape failed 11 of 15. Coverage is deliberately preserved, verified by six negative arms that keep fuzzing.
e Both directions demonstrated? Yes. Pre-fix binary: the INSERT fails Code: 159 (both via the deterministic repro and through the fuzzer at --ast_fuzzer_runs=40). With the fix: hazardous topologies are skipped, the INSERT completes, and the skip ProfileEvent is positive. Both assertions are required in both directions, so a run where the fuzzer never cloned cannot pass as a green. The new test reproduces both directions in CI. Two further mutations pin the round-2 changes: restoring the queue-root exemption drops the skip count to 0 and lets 21 duplicating views survive on one target, and restoring the early return plus set semantics drops it from 41-55 to 13-19 across four replicates. Round 3 measures the convergent shape by the harm rather than the counter, because the counter cannot discriminate there (the original view makes the sink already reachable, so both binaries answer hazardous through that limb): on the pre-fix binary 14 fuzzed clones attach to a previously clean retargeted source and 6 of them wedge on INSERT, against 0 and 0 with the fix over five replicates, while the no-convergence control wedges 0 on both. A third mutation restoring the queue-root exemption flips exactly queue_source_clone_skipped from 1 to 0 and no other line, and a fourth bumping the undecided counter on the wrong verdict flips exactly undecided_counted from 1 to 0, so that assertion is measured live rather than assumed.
f Fix is general across code paths? Yes. The server fuzzer's single execution path for a fuzzed CREATE is covered. Considered and excluded with reasons: the client fuzzer (isSuitableForFuzzing needs columns_list, absent on a TO-target view, so it is not a carrier), the VIEW -> MATERIALIZED VIEW flip (gated on !create.storage, yields no TO), the engine-wrap block (gated on !create.isView()), CLONE AS / fuzzTableName (move the source, handled by reading both ids from the dependency extractor on the fuzzed AST), ALTER ... MODIFY QUERY (the fuzzer's ALTER paths never set a TO), window views (the source INSERT writes the view's own inner storage; the external target is written by the separate INSERT from fire), and inner-table views (per-view inner table named from the view's own UUID).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The predicate keys on supportsParallelInsert(), which composes through StorageProxy, StorageAlias and StorageMaterializedView, rather than on an engine-name list that would rot and not compose. Arms cover depth 0, depth 2, depth 8, behind an Alias, behind a proxy, a stale dependency edge, and the three forwarding engines. The fuzzer itself supplied the type-wrapper matrix during the runs (clones with Nullable, LowCardinality, Array(...), String and NOT NULL column lists all appear). Round 1 adds a lazily-loaded storage (a proxy whose StorageID equals its nested storage's, which previously made the whole predicate answer "not hazardous"). Round 2 adds the queue-engine class: all five noPushingToViewsOnInserts() engines were enumerated from source, the two that implement no write() identified as non-carriers, and Kafka measured on both a hazardous and a safe target. Such a root is no longer exempted, because its background consumer's insert does build a sink for every dependent view, so the walk is a superset there and errs only towards skipping, and that path now has committed coverage rather than a scratch measurement. Round 3 adds the converging shapes: two live parents over one subtree, a 6-wide diamond over three levels, a 10-wide diamond over four levels, and a source whose own graph already duplicates a different non-parallel sink.
h Backward compatible? (maintainer-approved exception only) Yes, nothing to break: no setting, no serialization format, no metadata, so no SettingsChangesHistory.cpp entry and no versioning path. The two new ProfileEvents are additive. The whole path is confined to ast_fuzzer_runs > 0, so no production query, storage, planner or parser behaviour changes.
i Invariants and contracts preserved? Yes. The traversal takes no locks of its own and holds no catalog lock across a hop; the cheap AST test runs before any catalog access. It terminates on an edge-keyed set admitted once per path, with a separate node-keyed active set for cycles, checkStackSize() guarding recursion the way the storage accessors do, and a visit bound that fails closed. Counting per path is bounded two ways, each measured necessary: the walk ends as soon as a duplicate is proven, and only the deciding walk counts per path (the first is read for membership alone). Without either, a 10-wide four-level graph exhausts the bound and reports undecided, which executes a view that does wedge; with both, that graph is skipped in less wall time than before the change. Only non-throwing accessors are used, and every undecidable branch (absent id, unresolvable table, cycle, or a throw out of the dependency extractor, which checkAllowedQueries does unconditionally for the PREWHERE/SAMPLE/FINAL shapes the fuzzer injects) falls through to normal execution 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 under the fuzzer lock, the same call its failure path uses; measured, omitting it leaves 345 of 480 later fuzzed queries naming a view that was never created. Round 6 closes two gaps in the contract itself. A proof already reached now outranks a later failure: the walk returns at the first proven re-check inside the dependent-view loop, and the two top-level walks are wrapped so a throw degrades the answer to unknown instead of discarding the proof - previously a lazy proxy throwing in getNested escaped the predicate, was rewritten to Undecided, and ran the hazardous query (measured on an instrumented base binary: 35 completed proofs discarded in one 60-run loop; 0 -> 37 skips with the change, while a control carrying the throw but no provable duplicate stays at 0 on both). Hazardous is still tested before undecided, so nothing-proven still yields Undecided and the fail-open rule is unchanged. And because the answer describes the catalog as of the call, the fuzzer holds a reservation on the resolved (source, target) pair across the decision and the create, released by scope exit at the end of that iteration; it is keyed on the pair so two views from one source onto different targets keep being fuzzed, nothing unbounded is held, and re-entrancy is precluded in code (fuzzed queries run internal, and the loop-starting callback is gated on !flags.internal). The boundary is stated in the header contract for other callers.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai are you sure the solution is on the AST fuzzer itself?

@groeneai

Copy link
Copy Markdown
Collaborator Author

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: Code: 159 on the INSERT, once lock_acquire_timeout expires (default 120s). The reduced shape, two materialized views TO one TinyLog over a shared source, fails 3/3. Both fail identically with this PR applied, because the change stops the fuzzer generating that shape, it does not fix it. So the fuzzer is reporting a real user-reachable defect and this PR suppresses the report, not the defect.

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 Log-family target are refused at INSERT planning time, or the duplicate sinks folded into a single write. Both are user-visible, so I would rather have your call than pick one myself. Happy to close this PR if you want the engine-level fix instead.

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov maybe the solution is to disable more than one materialized view into a single Log table

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 TO one target over a shared MergeTree source, plain INSERT, lock_acquire_timeout = 3:

target engine INSERT
TinyLog, Log, StripeLog Code: 159
Set, Join, Memory, MergeTree completes

So the carrier set is exactly the Log family, and "more than one materialized view into a single Log table" is the right width. Worth noting Set and Join also report supportsParallelInsert() = false and still do not wedge, so keying the refusal on that capability, which is what my PR keys on, would be wider than the defect.

One constraint on where the refusal goes: those CREATEs succeed today and the topology reloads from metadata on restart, so a CREATE-time gate has to stay permissive on ATTACH or it strands tables that already exist. Refusing at INSERT planning time does not have that problem.

I will leave #114599 as is until you decide, and close it if the engine-level fix is what you want.

@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-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. label Sep 4, 2026
…cate-non-parallel-sink

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@clickhouse-gh clickhouse-gh Bot added comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... and removed comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. labels Nov 19, 2026

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-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants