Skip to content

Drop table_disk when the query fuzzer clones a table definition - #119159

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fuzzer-drop-table-disk-from-fuzzed-clone
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fuzzer-drop-table-disk-from-fuzzed-clone

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116473

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

Stress test (arm_release) aborted on master 27ee4ee716b4 with Logical error: 'PartsSplitter expected unique range' (CI report); no issue exists, so that run is the provenance.

The producer is the query fuzzer. table_disk = true points the disk at the table's own data, not the database's. fuzzCreateQuery mutates the column list and key clauses and renames the table to <name>__fuzz_N but left the storage SETTINGS untouched, so the clone read the cloned-from table's parts under a schema they do not satisfy: 29 of 37 clones did. Those reads failed with TYPE_MISMATCH, EXPECTED_END_OF_FILE, and the error above when the surviving mutation was the ORDER BY ... DESC flip: in_reverse_order over an ascending index sorts every RangeEnd before its own RangeStart, so splitPartsRangesImpl sees a duplicate PartRangeIndex.

I drop table_disk in fuzzTableStorage, the one helper both the outer storage clause and every view inner engine (create.targets->getInnerEngines()) pass through, before its !storage.engine early return. disk is kept: without table_disk it only chooses where the clone stores its own data, so it cannot alias. The original table_disk table is still fuzzed; only the mutation of foreign parts is removed.

05166_ast_fuzzer_table_disk_clone asserts that no clone of either carrier keeps table_disk and that disk itself survives, with a per-carrier positive control that the fuzzer did rewrite the CREATE. Removing the two erase_if lines reddens both carriers; clearing the whole SETTINGS node instead reddens the retention lines. 100/100 runs pass.

Merged #116473 closed the ALTER ... MODIFY ORDER BY route to the same state. The engine assertion is unchanged and stays reachable without the fuzzer: two table_disk tables over one object-storage root declaring opposite key directions reach it deterministically. Repairing that means refusing such a table; not folded in here. I also noticed a clone keeps the original's explicit UUID, observed only as a rejected TABLE_ALREADY_EXISTS.


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

groeneai and others added 5 commits September 10, 2026 03:04
`table_disk = true` means the disk's path holds this table's data rather than
the database's. `QueryFuzzer::fuzzCreateQuery` mutates the column list and the
key clauses and then renames the table to `<name>__fuzz_N`, but it left the
storage `SETTINGS` untouched, so the clone mounted the parts of the table it was
cloned from while declaring a schema and sorting key those parts do not satisfy.
Only the engine-replacement branch cleared the settings, and it is not taken for
a MergeTree clone.

Measured on a local object-storage root: 29 of 37 clones the fuzzer created were
reading the original table's parts. Reads of them failed with TYPE_MISMATCH,
EXPECTED_END_OF_FILE on `primary.cidx`, and - when the surviving mutation was
the `ORDER BY ... DESC` direction flip - a LOGICAL_ERROR from `PartsSplitter`,
which is what aborted `Stress test (arm_release)` on master 27ee4ee.
`deriveReverseOrder` returns `in_reverse_order = true` over an ascending index,
`compareValues` inverts, every `RangeEnd` event sorts before its own
`RangeStart`, and `splitPartsRangesImpl` throws on the resulting duplicate
`PartRangeIndex`.

The strip goes in `fuzzTableStorage`, the single helper both the outer storage
clause and every view inner engine (`create.targets->getInnerEngines()`) pass
through, and precedes the `!storage.engine` early return so a storage clause
with no `ENGINE` is covered too. Both `changes` and `default_settings` are
erased and an emptied node is pruned, mirroring `stripQuerySettings.cpp`: the
owner formatter prints `SETTINGS` whenever the slot is non-null, so an empty
node would serialize to a bare `SETTINGS` that fails to re-parse.

`disk` itself is deliberately kept: without `table_disk` it only chooses where
the clone stores its own data, so it cannot alias. The fuzzer still fuzzes
queries against the original `table_disk` table and still wraps it through the
engine-replacement branch.

Co-Authored-By: Claude Opus 5 <[email protected]>
`position(query, 'table_disk')` counted any occurrence of the substring anywhere
in a clone's text, which is not the contract the test asserts. The fuzzer's
corpus is process-global (`getGlobalASTFuzzer` returns a function-local static)
and `collectFuzzInfoRecurse` pools every identifier and literal it sees, so in a
lane that arms `ast_fuzzer_runs` server-wide an unrelated identifier such as
`test_table_disk_requires_disk` from `03355_mergetree_table_disk` can be
substituted into a clone that carries no `table_disk` setting at all. The
negative oracle would then count that clone and the test would fail even though
the strip worked.

Match the setting name as a whole word instead. The character classes are
spelled out rather than using `\b` because inside a bash double-quoted string
`\\b` collapses to `\b`, which the string-literal parser turns into a backspace
byte, leaving a regex that matches nothing. This form has nothing for either
layer to eat, and it matches both `SETTINGS table_disk = true` and the valueless
`SETTINGS table_disk` shorthand that `ASTSetQuery::formatImpl` prints for a
shorthand change.

Both negative oracles also gain `query_kind = 'Create'`, so they cannot count a
sibling oracle statement's own text by accident rather than by statement
ordering, and a liveness control on the seed CREATE is added last: the seed
genuinely carries the setting and is never rewritten in place, so it must match
with and without the strip. A mangled pattern now fails loudly instead of
passing vacuously.

Co-Authored-By: Claude Opus 5 <[email protected]>
It said the mutated column list and sorting key are applied "below" this point.
They are not: `fuzzColumnDeclarationList` and the `ORDER BY ... DESC` arm both
run in the caller, `fuzzCreateQuery`. State the invariant without the location
claim, in three lines instead of four.

Co-Authored-By: Claude Opus 5 <[email protected]>
The oracles only checked that no clone carries `table_disk`. That is half of the
contract: replacing the two selective erases in `fuzzTableStorage` with an
unconditional `storage.reset(storage.settings)` satisfies every one of those
lines while stripping `disk`, `index_granularity` and every other storage setting
from every clone, so the fuzzer would stop exercising the storage clause at all
and the test would not notice. Assert per carrier that `disk = disk(` still
appears in at least one clone.

`count() > 0` rather than a per-clone count, because the wrap arm that turns a
clone into `Distributed`, `Buffer` or `Merge` rewrites its storage clause
wholesale and legitimately drops the setting, so an equality would flake. The
leading boundary class stops `table_disk = disk(` from satisfying the predicate,
and the paren is written `[(]` so that neither bash nor the string-literal parser
sees a backslash to consume.

The file also drops its view and its two tables at the end, like the other tests
on this plain_rewritable chassis. The clones go with the per-test database.

Co-Authored-By: Claude Opus 5 <[email protected]>
The fuzzer's clone registry, original_table_name_to_fuzzed, is keyed by the bare
table name: getOriginalTableName just cuts at __fuzz_ (QueryFuzzer.cpp:1388).
It lives on a fuzzer that is a function-local static, created once per server
process and never recreated (executeQuery.cpp:3334), so an entry another test
left under the name "reader" is still there when this test runs. Seven other
stateless tests create a table called exactly that, and nothing on the server
side erases such an entry: getDropQueriesForFuzzedTables, the only code that
does, has no caller in executeQuery.cpp.

With the key already populated, iteration 1 can take the wrap arm at
QueryFuzzer.cpp:2234, which sets storage.settings = nullptr (:2297) and drops
the column list, so the clone carries no storage clause at all and
table_clones_keep_disk reads 0 while the fix is working. Only iteration 1 is
exposed: from iteration 2 the fuzzer has registered its own clone, and each
iteration fuzzes the previous one's output (base_ast = fuzzed_ast,
executeQuery.cpp:3663), so once the arm is taken every later clone inherits the
wrapper. Measured on a first clone: 5 of 250 executions wrapped with a populated
key, 0 of 249 with a per-database name.

${CLICKHOUSE_DATABASE} is unique per test execution, so a suffixed seed name is
one the fuzzer has never seen and the key is empty at iteration 1. The oracle
becomes deterministic rather than merely probable.

Only the two tables that are actually fuzzed are renamed. writer is created
through a client pinned to --ast_fuzzer_runs=0, so it never enters the registry
and needs no suffix.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 10, 2026
@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; 11 findings across my own cold passes
and the gate; bounded: 1 full pass + 4 delta rechecks + 3 fix rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test asked position(query, 'table_disk') > 0, which matches the substring anywhere in a fuzzed clone, not a table_disk setting (05166_ast_fuzzer_table_disk_clone.sh) AGREE, fixed The fuzzer corpus is process-global (getGlobalASTFuzzer, executeQuery.cpp:3334) and pools every identifier and literal (QueryFuzzer.cpp:8922), which are substituted into the clone's SELECT body (:1806). 03355_mergetree_table_disk.sql alone contributes test_table_disk_requires_disk and two siblings, so in a lane with ast_fuzzer_runs set server-wide the test could fail with the fix working. Both negative oracles now use a boundary-anchored match() plus query_kind = 'Create', with a per-run control proving the pattern still matches a real setting
2 ⚠️ The description claimed the cause was the fuzzer "not the engine", which my own repro contradicts AGREE, fixed Two table_disk tables over one object-storage root with opposite declared key directions reach the same assertion deterministically, hand-written, no fuzzer. The description is now scoped to the producer and states that the engine route stays open and is a separate change
3 💡 The first comment block ran to 4 lines and located the mutations "below", though they happen in the caller AGREE, fixed Rewritten to 3 lines; the column list is mutated at QueryFuzzer.cpp:1713 and the key direction elsewhere in fuzzCreateQuery, both above this helper
4 💡 Nothing covers the branch that detaches an emptied SETTINGS node DISAGREE Not reachable to test on this path, rather than untested: the branch needs table_disk as the sole setting, which MergeTreeSettings.cpp:2552 always rejects, and the server-side fuzzer runs only from a finish callback on the success path (executeQuery.cpp:3756, :4486), so a throwing seed is never fuzzed. Correctness is established by reading instead: IAST::reset throws only for a field absent from children (IAST.h:267), and settings is always registered via set() - by the parser (ParserCreateQuery.cpp:761), by ASTStorage::clone (ASTCreateQuery.cpp:59), and by the fuzzer's own settings helper (QueryFuzzer.cpp:1570), which is the one that can create the node after this prune has removed it. ASTStorage::formatImpl prints SETTINGS whenever the slot is non-null (ASTCreateQuery.cpp:246), which is the hazard being prevented
5 💡 The emptiness check duplicates isEmptySetQuery DISAGREE It is not exported (stripQuerySettings.h declares only removeSettingsFromQuery) and executeQuery.cpp:1471 already keeps its own copy, so a local copy matches the in-tree norm rather than adding a Common to Parsers helper export for three lines
6 ⚠️ The test asserts only that table_disk is gone, never that disk survives, so replacing the two selective erases with an unconditional storage.reset(storage.settings) would pass every oracle AGREE, fixed Keeping disk is part of the stated contract, and a blanket clear would silently strip every storage setting the seed carried (disk, index_granularity, min_bytes_for_wide_part, ...) from every clone - exactly the fuzzer coverage this change exists to preserve. A per-carrier disk = disk( retention control is added, together with a mutation arm demonstrating that the previous five oracle lines all stay green under that blanket clear
7 💡 The test drops its tables only at the start, while all five sibling tests on the same read-only-disk chassis end with explicit drops AGREE, fixed Trailing DROP VIEW/DROP TABLE ... SYNC added; these tables sit on custom table_disk roots
8 ⚠️ Neither seed omits ENGINE, so nothing exercises the engine-less storage clause the strip is deliberately placed above DISAGREE Such a seed cannot discriminate the placement on this path, so the oracle would be vacuous. executeASTFuzzerQueries runs only from the finish/success path (executeQuery.cpp:3756 finish callback, :4486 in onFinish) and is handed the same AST the interpreter already normalized: setEngine (InterpreterCreateQuery.cpp:892) fills the engine into that AST in place through setDefaultTableEngine's storage.set(storage.engine, engine_ast) (:1378-1387), for a partial storage clause (:1656), a temporary table (:1552) and a materialized view's inner To engine (:1570) alike. Its only early exits (:1535, :1561) are dictionaries, ordinary views and externally-targeted views, none of which own MergeTree parts. A clone built from such a seed would therefore already read ENGINE = MergeTree, so a strip moved below the early return would behave identically and the new oracle would stay green under the very mutation it targets. The placement stays as it is: it costs nothing, and the client-side fuzzer mutates the AST before the server normalizes it
9 ⚠️ The new disk retention oracle can read 0 with the fix working: if the very first mutation wraps the clone in another engine, that diskless clone becomes the base every later mutation is built from AGREE, fixed Confirmed at each step and wider than reported. The fuzzer chains successful mutations (base_ast = fuzzed_ast, executeQuery.cpp:3663), the wrap arm erases the whole settings node (storage.settings = nullptr, QueryFuzzer.cpp:2297, one of only two settings-clearing sites in the file), an Alias over an absent target still creates successfully, and once the base is a non-MergeTree engine fuzzTableStorage returns before any settings work, so no later clone regains disk. The arm's one precondition is a non-empty clone registry for the seed's bare table name (:2234-2237, keyed via :1388) on a fuzzer that is a per-process static (executeQuery.cpp:3334) - and seven other stateless tests create a table called reader, so in any lane that arms ast_fuzzer_runs server-wide the registry is already populated on a first execution. Both fuzzed seed tables now carry a per-database suffix, which makes the registry provably empty at the first mutation instead of merely usually empty: measured 5 wrapped clones in 250 executions with a generic name against 0 in 249 with the suffix
10 ❌ Erasing table_disk does not disable it when the server's merge_tree config section enables it, and there it turns a seed that explicitly set table_disk = false into an aliasing clone DISAGREE The mechanism is real - registerStorageMergeTree.cpp:731 seeds the settings from getMergeTreeSettings(), which already includes the merge_tree config section (:966), the query's changes apply on top, and MergeTreeData.cpp:525-529 reads the effective value - but every route to the harm needs a server forcing table_disk = true in that section, and in such a server the outcome is the baseline rather than a regression. validateTableDisk has exactly one call site (MergeTreeSettings.cpp:2610), gated on a local flag set only from the query's own changes (:2597), so a config-level value is never checked for a disk, for object storage, or for random blob paths, and every MergeTree table that does not explicitly opt out is placed at its disk root with an empty relative_data_path - all of them already alias each other, with no fuzzer and no clone involved. No configuration in this repository sets it: <table_disk> appears in no .xml or .yaml outside contrib/, while <merge_tree> overrides are otherwise common under tests/config/config.d/. Under the shipped default the strip is strictly better for a table_disk = true seed and byte-identical for a false seed or for none. Not changed here, and the smaller alternative is on the record: erase only entries whose value is truthy, which preserves an explicit false and needs no test change, at the price of evaluating a Field of arbitrary type inside the fuzzer. I am happy to make that change if you run such a configuration
11 ⚠️ The disk retention oracles use count() > 0, so they pass even if every clone but one lost disk, although view clones cannot take the wrapper arm that motivated the weak form DISAGREE The per-clone universal is already there for the property this change establishes: both *_with_table_disk lines are a raw count() against a reference of 0, quantified over every matched clone. The *_keep_disk lines are controls in the opposite direction, and the stronger form adds no detection power over the mutation space of these 14 lines - dropping the two erases reddens *_with_table_disk (25/29/25 and 25/25/25 measured), clearing the whole node reddens *_keep_disk in either form (0/0 measured). What it would add is an assertion about fuzzer arms this change does not touch: QueryFuzzer.cpp:1745-1751 already deletes an entire inner engine for any create with more than one target, so a clone of a TimeSeries SAMPLES/TAGS/METRICS, or of an MV carrying both TO and INNER, legitimately holds no inner-engine disk. The universal holds for this fixture because it has a single target, which is a property of the fixture rather than of the fix, so pinning it would let a later fixture or a new arm redden a correct change

Also noticed, no change made: this test deliberately does not carry no-random-settings, unlike the
five sibling tests on the same chassis, where the tag comment records it as a workaround adopted
without root-causing. 50 runs with randomization and 50 with it disabled pass, and one randomized run
drew merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 0.59,
the setting that put the failing CI query on the split path in the first place. It also carries no
no-fasttest, unlike the three existing tests that set ast_fuzzer_runs: allow_feature_tier
defaults to 0, which permits changes to settings of every tier, and nothing here sets it, so the
experimental tier of ast_fuzzer_runs restricts nothing. One run takes 1.8-2.0 s.

Also noticed, no change made: the oracles select a carrier's clones by substring over the whole
logged query, so a clone of one carrier that substituted the other carrier's clone name into its
SELECT body is counted by both. It cannot mask the failure the lines guard against - a blanket
clear of the storage settings reddens both carriers regardless - and the per-database rename above
narrows the names further.

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.

Session id: cron:clickhouse-review-slot-8:20260910-065300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on the FIRST attempt, no rate involved. A writer with table_disk = true over a local plain_rewritable object-storage root (4 parts, SYSTEM STOP MERGES), a second table over the same root declaring ORDER BY key DESC, then SELECT count(), sum(key) with merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 1, max_threads = 8. Debug build stops at PartsSplitter.cpp:530; the same input reaches the throw at :547 in a release build, which is the reported failure. Frame 4 is ReadFromMergeTree.cpp:1792, the same frame as the CI stack.
b Root cause explained? table_disk = true means the disk's path holds this table's data rather than the database's. fuzzCreateQuery mutates the column list and the key clauses and renames the table to <name>__fuzz_N, but left create.storage->settings untouched (only the engine-replacement branch cleared them, and it is not taken for a MergeTree clone), so the clone read the parts of the table it was cloned from under a schema and sorting key those parts do not satisfy. With the DESC arm surviving, deriveReverseOrder reports in_reverse_order over an ascending index, compareValues inverts, every RangeEnd sorts before its own RangeStart, parts_ranges[0] is a RangeEnd, and the matching RangeStart collides with the pre-seeded PartRangeIndex.
c Fix matches root cause? Yes, at the producer. The fuzzer no longer emits a clone that claims to own another table's data root. No engine change, no guard at the failing site: primary-key index analysis already compares boundary tuples in the declared order before PartsSplitter runs, so declining the split could not have made such a table correct. Merged #116473 refused the equivalent ALTER ... MODIFY ORDER BY route for the same reason.
d Test intent preserved / new tests added? New 05166_ast_fuzzer_table_disk_clone.sh. No existing test weakened, no tag added, no bound widened, no dataset reduced. Each carrier has a positive control (*_clones_attempted), and the two contract lines match the setting as a whole word under query_kind = 'Create' rather than as a substring, so an unrelated corpus identifier containing table_disk cannot redden them. Two further lines assert the other half of the contract, that disk itself survives the strip, so a version that cleared the whole SETTINGS node cannot pass. A seventh line asserts the pattern still matches the seed CREATE, so a mangled pattern fails loudly instead of passing vacuously. The two fuzzed seed tables carry ${CLICKHOUSE_DATABASE} in their names, which makes the retention lines deterministic rather than merely probable: the fuzzer's clone registry is process-global and keyed by the bare table name, so a generic name lets iteration 1 wrap the clone around a target another test left behind and erase the storage clause these lines measure. Measured on a first clone: 5 of 250 executions wrapped under a generic name, 0 of 249 with the per-database name. The engine-level reproducer is deliberately NOT shipped: it asserts a LOGICAL_ERROR this PR does not fix.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (server buildId() asserted equal to the binary before every verdict), with two independent mutation arms reddening different halves of the contract. Pristine d1b2fc09: 24 clones carry table_disk. Arm A 8ddedf58, only the two erase_if lines removed: both carriers redden on *_with_table_disk (tens of clones per run; the exact count varies with the fuzzer seed) while the retention lines stay green. Arm C 8531424d, the whole settings node cleared unconditionally: *_keep_disk goes to 0 on both carriers while all five other lines stay green, which is what shows the retention assertion is load-bearing rather than bookkeeping. Fix deb60c5c: all seven lines match, test OK. The deeper metric moves too: clones reading the original's parts go from 29/37 and 11/11 to 0. 121/121 runs pass on the fix: 1 single, 50 randomized, 50 with randomization disabled, and 20 more re-run after both arm servers had used the same data directory.
f Fix is general across code paths? fuzzTableStorage is the single helper every storage-clause mutation flows through, with exactly two call sites, both in fuzzCreateQuery: the outer create.storage, and create.targets->getInnerEngines(), which covers the materialized-view TO/INNER and TimeSeries SAMPLES/TAGS/METRICS carriers. One edit, both carriers, both measured red then green. The client-side fuzzer uses the same class. The engine-replacement branch already cleared the settings; the CREATE DATABASE branch never calls this helper; the other producer of the same engine state is already refused by #116473.
g Fix generalizes across inputs? Not a type-dispatch fix, so there is no wrapper matrix: the edit keys on a setting name in an AST node, independent of column types and values. Both spellings are erased, changes for table_disk = <v> and default_settings for table_disk = DEFAULT, which is also what makes the empty-node prune reachable. Shapes exercised: ENGINE = MergeTree, no ENGINE clause (default engine), view inner engine, read-only and read-write disks, and a table_disk = false create.
h Backward compatible? Yes. No new or changed setting, no default moved, no SettingsChangesHistory.cpp entry owed, no serialization or version gate. ast_fuzzer_runs is documented as testing-only and not suitable for production, so the change is confined to test tooling.
i Invariants and contracts preserved? The ASTStorage/ASTSetQuery contract: both settings lists are erased and the node is detached only when changes, default_settings and query_parameters are all empty, mirroring isEmptySetQuery in stripQuerySettings.cpp. The prune is required because the owner formatter prints SETTINGS whenever the slot is non-null, so an emptied node would serialize to a bare SETTINGS that fails to re-parse. Ordering: the strip precedes every mutation arm, so no arm sees a half-stripped node, and precedes the !storage.engine early return, so no reachable storage clause escapes it. The later injection lambda re-creates the node when absent, so pruning leaves no dangling pointer. No lock, concurrency or data-structure invariant is touched.

Session id: cron:clickhouse-impl-slot-5:20260910-061501

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [866bbc5]


AI Review

Summary

This PR strips table_disk from AST-fuzzer cloned CREATE storage clauses and adds a stateless test that inspects the logged clone text. The code change itself is narrow and coherent, but it currently turns a real table_disk correctness signal into a CI green-up instead of preserving coverage for the supported feature, so I would request changes.

Findings

⚠️ Majors

  • [src/Common/QueryFuzzer.cpp:1417] Dropping table_disk here removes the only automated reproducer for a still-open table_disk bug that remains reachable through ordinary user DDL. The feature docs describe table_disk = true as the supported one-writer/many-readers shared-storage mode, yet readonly readers still skip part-consistency checks and can read the same root under an incompatible ORDER BY, producing wrong results or LOGICAL_ERROR according to the repro already documented in this PR discussion. The new test only proves the fuzzer no longer emits that state.
    Suggested fix: either add the engine-side validation/regression in this PR, or link a follow-up issue and keep a dedicated test that continues to exercise the user-visible table_disk path.
Tests
  • ⚠️ Please keep a focused regression for the supported table_disk reader path itself (for example, two tables on the same shared root with incompatible sorting metadata), not only the AST-fuzzer text rewrite. Otherwise this PR removes the last automated signal for the remaining bug.
Final Verdict

Status: ⚠️ Request changes

  • Do not merge this as a pure CI green-up. Either fix or guard the engine-side table_disk mismatch path here, or at minimum link the follow-up issue and preserve an automated reproducer for that path.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @qoega @PedroTadim, could you review this? The fuzzer renames a CREATE into a __fuzz_N clone and mutates its column list and sorting key, but it left table_disk = true in the storage SETTINGS, so the clone read the parts of the table it was cloned from under a schema those parts do not satisfy, which is what produced Logical error: 'PartsSplitter expected unique range' on master. I drop the setting in fuzzTableStorage and keep disk, so the clone stores its own data.

@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 10, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai are you sure this is the right fix? Maybe we should throw an error in an invalid setting combination

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ad24984b8 with master b671cb9e0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 7d76bcdf0; 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, 17 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

It is the right fix for the producer, but you are right that it is not the whole story.

I do not think the combination can be caught from the settings, though. validateTableDisk (MergeTreeSettings.cpp:2549) already refuses table_disk without disk, non-object-storage disks, and disks whose blob paths are random, and the fuzzed clone passes all three: an explicit disk(...), object storage, plain_rewritable, read_only = true. Two table_disk tables over one root is also the documented one-writer/many-readers setup (registerStorageMergeTree.cpp:2500), so the clone's storage settings are indistinguishable from a legitimate reader's. What is invalid is the declared metadata against the parts that are already at that root, and loadFromQuery sees the settings and the disk, but neither the sorting key nor the parts.

The engine half is real without the fuzzer, and I think it matters more than the CI abort. Hand-written DDL:

CREATE TABLE writer (key Int32, val UInt32) ENGINE = MergeTree ORDER BY key
SETTINGS table_disk = true, disk = disk(name = repro1_writer, type = object_storage,
    object_storage_type = local, metadata_type = plain_rewritable, path = 'disks/repro1_engine/');
SYSTEM STOP MERGES writer;   -- then 4 inserts of 50 rows, so 4 parts, all written ascending

CREATE TABLE reader (key Int32, val UInt32) ENGINE = MergeTree ORDER BY key DESC
SETTINGS table_disk = true, disk = disk(read_only = true, name = repro1_reader,
    type = object_storage, object_storage_type = local, metadata_type = plain_rewritable,
    path = 'disks/repro1_engine/');

SELECT count(), sum(key) FROM reader SETTINGS
    merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 1,
    max_threads = 8, use_query_condition_cache = 0;

That aborted the server on the first attempt at PartsSplitter.cpp:530, the debug chassert one line above the throw that fired on master, through the same frames (ReadFromMergeTree.cpp:1792 -> PartsSplitter.cpp:1210). The same parts read through the ASC-declared table return all 200 rows with no error.

The abort is the lucky case, which is what stopped me treating this as a CI-only problem: the chassert at PartsSplitter.cpp:618 is a no-op in release, so a range end that sorts before its own start without being the global minimum reaches the operator[] at :627/:658 and reads MarkRange{0, ...} out of a default-constructed entry, i.e. wrong results with no error at all.

Where such a throw can live: not in PartsSplitter. markRangesFromPKRange already takes the key order from the declared sorting key (MergeTreeDataSelectExecutor.cpp:2006-2008) before the splitter runs, so declining the split cannot make the table readable; that is why #116473 refused the ALTER ... MODIFY ORDER BY flip instead of degrading the reader. It has to be at table load, where the declared key and the parts' own index are both available.

I have that repro, so I can send the load-time check as a separate PR if you want it. For this PR: keep the strip, or close it in favour of the engine-side check? I lean to keeping it, since a clone that mounts another table's data root yields no useful fuzz signal either way (on a pristine build the same clone also produced TYPE_MISMATCH and Index file all_1_1_0/primary.cidx is unexpectedly long from the mutated column list), but it is your call.

@groeneai

Copy link
Copy Markdown
Collaborator Author

One correction to what I just wrote, since it is the part that decides the shape of an engine-side fix: the load-time check cannot be derived from the parts. I planned exactly that (verify each part's primary index is non-decreasing under the declared key) and then measured it dead: with index_granularity_bytes = 0 every 50-row part has marks = 1, so there is nothing in the index to compare, and WHERE key > 190 still answers 0 instead of 9. Reading a part's first key rows catches that fixture but says nothing when the leading key values tie or when a part has one row. The direction flip is also not the only instance: a writer with ORDER BY (a, b) against a reader declaring ORDER BY (b, a), both ascending, over one root answers 0 for WHERE b > 990 where the writer answers 40, and that index is monotone in the declared order. Order information that is not in the data cannot be recovered from it: the root holds only format_version.txt (MergeTreeData.cpp:588), no part file records the sorting key, and check_consistency is !part_disk_ptr->isReadOnly() (:2652), i.e. off for exactly this reader.

For pricing the decision, this is the same fixture at default settings (4 ascending parts, keys 0..199; control is the same reader declaring ORDER BY key):

query control reader declaring ORDER BY key DESC
SELECT count() WHERE key > 190 9 0
SELECT max(key), min(key) 199, 0 150, 49
SELECT key ORDER BY key DESC LIMIT 3 [199,198,197] [150,151,152]
SELECT count(), sum(key) (full scan) 200, 19900 200, 19900
SELECT count() FINAL (ReplacingMergeTree) 200 LOGICAL_ERROR

The full scan is the only one of those that never calls getIndex(), and the only one that is right. FINAL needs no special setting to reach the assertion.

So three mechanisms survive, and each asks for a call I do not think I should make alone on a shipped on-disk contract:

  1. persist a structure descriptor at the root and compare it on open: sound, and it closes the column-order instance too, but an exact-structure comparison would refuse legitimate web-disk mounts that declare a narrower column list, and roots written by older versions carry no descriptor, so the legacy policy (trust, warn, refuse) is a second decision;
  2. refuse a reverse sorting key when table_disk = true: metadata only, zero cost, closes the whole direction family, but a table_disk table that wrote its own descending parts is correct today and could not be ATTACHed after the upgrade (table_disk shipped in 298b431aa7721, 2025-02-09);
  3. treat table_disk as trusting the user and document it, in which case only the LOGICAL_ERROR has to go.

I lean to (2) if that compatibility break is acceptable, otherwise (1) with a sorting-key-only descriptor that refuses on mismatch and trusts descriptor-less roots. I am happy to implement whichever you or the owner of the feature prefer. One input for the decision: merging this PR removes the only automated detector CI currently has for the state.

@PedroTadim PedroTadim self-assigned this Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ad24984

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
Fast test (arm_darwin) / 05076_error_trace_file_offsets Darwin-only red present on every PR head, not caused by this branch: CIDB over 3 days gives 36 failures and 0 passes across 36 distinct PRs on Fast test (arm_darwin) for this test, while Fast test on Linux is 119 passes and 0 failures #119145 (mine, merged 2026-09-10T10:27:13Z). It was not an ancestor of ad24984b (behind by 229), so I merged master @ 866bbc53bb7f50f913b0809b9a9135456b3ad454 to re-run CI with it
Mergeable Check aggregator roll-up of the row above, no independent failure #119145 (mine, merged), merged master @ 866bbc53bb7f
PR aggregator roll-up of the row above, no independent failure #119145 (mine, merged), merged master @ 866bbc53bb7f

No other check failed on this head: 151 SUCCESS, 20 SKIPPED, 0 queued or running at the time of measurement.

Session id: cron:our-pr-ci-monitor:20260910-130137

/// sorting key its caller applies. Without the setting the clone stores its own data.
if (storage.settings)
{
std::erase_if(storage.settings->changes, [](const SettingChange & change) { return change.name == "table_disk"; });

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 narrows the fuzzer surface, but it also removes the only automated detector for a still-supported table_disk failure mode. The docs treat table_disk = true as the supported one-writer/many-readers shared-storage setup, and the current engine still accepts a readonly reader over the same root with incompatible metadata: MergeTreeData::loadDataPart skips part-consistency checks on readonly disks (loadColumnsChecksumsIndexes(..., !part_disk_ptr->isReadOnly())), so a reader declaring a different ORDER BY can still return wrong results or hit LOGICAL_ERROR, as in the repro already captured in this PR discussion. After this line lands, CI goes green because the fuzzer no longer emits that state, not because the feature is guarded. I think this needs either the engine-side validation/regression in the same change, or at least a linked follow-up issue plus another test that keeps the user-visible table_disk path covered.

@PedroTadim

Copy link
Copy Markdown
Member

🕵️

On the engine bug this leaves open — I'd argue for validating against the parts rather than against a descriptor or a sibling table.

The three symptoms you measured (TYPE_MISMATCH, EXPECTED_END_OF_FILE, and the splitter throw) are one omission: a MergeTree mounting a table_disk root reads whatever parts it finds without checking they satisfy its own schema and sorting key. A part is physically sorted by the key it was written with, and that is observable from primary.idx — one primary-key value per granule in part order, so ascending is monotonically non-decreasing and descending non-increasing. Comparing that against the declared direction, plus the part's column list against the declared columns, closes all three at load with one legible error.

Why I'd prefer it to the alternatives that have come up:

A sibling-table check needs the sibling to exist. Parts outlive tables — create A ascending, drop it, create B descending, and B mounts incompatible parts with nothing to compare against. Same for DETACH, and same when the other table is on a different server, which is the normal case for a web root. It also makes the outcome depend on creation order, and it needs the same root registry a path check would, so it isn't cheaper.

Forbidding two tables per root would refuse configurations that work today. The setting's own docs list web/web_index, and N servers mounting one published dataset is the point of web. #96818 added table_disk for plain_rewritable under one-writer-per-disk, which is a concurrency constraint rather than one-table.

A persisted structure descriptor is sound in principle but cannot reach the cases that matter. initializeDirectoriesAndFormatVersion only writes format_version.txt when !disk->isReadOnly() && !disk->isWriteOnce() (:581-583), and the setting's description calls web/web_index read-only, so a descriptor can never be written for them — the no-descriptor branch is permanent behaviour there, not a migration window. Since "refuse on missing descriptor" would break every existing root, the legacy policy has to be trust-or-warn, which means the bug stays open for most configurations. I estimated ~350-550 lines including the setting, the SettingsChangesHistory entry and object-storage tests, for coverage of new s3_plain_rewritable roots only.

The part check needs no new file, no new setting, no migration policy, and works on read-only roots, on roots written by any version, and on the ALTER ... MODIFY ORDER BY route that #116473 had to close separately.

Separately and worth landing first either way: PartsSplitter.cpp:547 throws LOGICAL_ERROR for a state your own two-table repro reaches from a user configuration. LOGICAL_ERROR asserts an internal bug and aborts under sanitizers, so the code is wrong regardless of the larger fix — it should be a BAD_ARGUMENTS-class exception naming the part and the mismatch. A few lines, and it stops the abort while the rest is decided.

And since there's no issue for the engine bug yet, it would be worth filing one with the deterministic two-table repro from your description, so it doesn't live only in a merged CI-fix PR.

@groeneai can then go with option 3 in a new PR?

@PedroTadim PedroTadim closed this Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, sending option 3 as a new PR.

Scope I plan, so you can veto early:

  • PartsSplitter.cpp:547 and :585 (same loop, both LOGICAL_ERROR for a state a user configuration reaches) become one user-facing error naming the part and saying its ranges disagree with the declared sorting key. I would use INCORRECT_DATA rather than BAD_ARGUMENTS, since the query arguments are fine and the parts are not; say if you prefer BAD_ARGUMENTS.
  • :618 is the same state on the RangeEnd branch and is a release no-op, and the lookups right after it (:653, :658) insert a value-initialized MarkRange (begin = end = 0, MarkRange.h:20-26 has no in-class initializers), so that branch degenerates instead of erroring. I would convert it in the same PR; say if you want the :547-only minimum.
  • table_disk documented as trusting the user about the parts already under the root, plus the deterministic two-table test asserting the new error instead of the abort.

Agreed on landing that first, and closing #119159 does not delay CI. Measured over 30 days, this state reaches CI by two independent routes: the AST fuzzer (13 rows, last 2026-09-08) and, as of today, the stress lanes (3 rows: amd_msan 09:36Z, arm_tsan 10:03Z, amd_tsan 12:33Z), plus the :547 throw on master itself in Stress test (arm_release) (27ee4ee716b4, 01:02:42Z today, the only release-build occurrence). The fuzzer strip would have closed the first route only, so I am not re-proposing it.

On validating against the parts: it is the strongest available check, and it does catch a multi-granule part written with the opposite direction. It does not close all three, and here are the two misses I measured (outcomes only, detail in the 09:37 comment above):

  • One granule per part. With index_granularity_bytes = 0, 50-row parts have marks = 1, so there is a single index value and monotonicity holds in both directions. The DESC reader still answers count() WHERE key > 190 = 0 where the writer answers 9.
  • Column permutation. Writer ORDER BY (a, b), reader ORDER BY (b, a), both ascending, identical column list: the index is monotone in the declared order and the column check passes, yet WHERE b > 990 answers 0 where the writer answers 40.

So it converts some silent wrong answers into a legible error without making the root safe. Happy to send it as its own PR if you want it as a best-effort check; your call.

On the issue: agreed, and with option 3 the wrong-answer half stays by design, so the issue is the only public record of it. I will file it with the deterministic two-table repro and the default-settings numbers (count() WHERE key > 190 9 vs 0, max/min 199,0 vs 150,49, read-in-order LIMIT 3 [199,198,197] vs [150,151,152], count() FINAL aborting), and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Option 3 is up as #119295.

One deviation from the scope I posted above, so it is not a surprise in review: instead of converting
:547, :585 and :618, it adds a single INCORRECT_DATA check earlier in the same loop, where the
two index values are already materialised, and leaves those three as internal assertions.

The reason is measured. The chassert at :530 fires before :547 in every build with assertions,
and all 16 CI rows for this state in the last 30 days are assertion-enabled builds (12 AST fuzzer
amd_debug, 1 arm_asan_ubsan, 3 stress tsan/msan, 0 release), so converting :547 alone would
leave every one of them aborting and no test could assert one error across build flavours. :585 is
not converted either: intersecting_parts is read before the emplace at :545, so reaching :585
needs a map that holds exactly one entry beforehand and two after, and the scan at :578 then always
finds the other one.

Both alternatives are still yours to take: the literal :547-only change if you prefer the minimum,
and BAD_ARGUMENTS instead of INCORRECT_DATA if that reads better.

clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 2, 2026
… key

A part's marks are physically ordered by the sorting key the part was written
with. `table_disk` mounts whatever parts are already under the disk root, and
nothing records that key, so a table can declare the opposite direction over
parts written ascending - two tables over one root is a documented shape.

`splitPartsRangesImpl` then sorts each range's RangeStart/RangeEnd events by the
primary index value at the range's begin and end mark, compared in the declared
order. With the opposite direction every RangeEnd sorts before its own
RangeStart, so parts_ranges[0] is a RangeEnd, the pre-seed inserts that range's
PartRangeIndex, and the matching RangeStart fails to emplace: LOGICAL_ERROR at
:547, or the chassert at :530 one line earlier in builds with assertions. When
the violating range is not the global minimum nothing fires at all and the
part_index_start_to_range lookups read a default-constructed MarkRange.

Check each range against the declared order where the loop already has both
values, and report the invalid input instead. The check is placed before the
sort rather than at :547 because the chassert fires first in every debug and
sanitizer build, which is where most of the CI occurrences are; converting the
throw alone would leave those aborting. With the precondition established,
:530, :547 and :618 become internal assertions unreachable from a user
configuration and stay as they are.

`splitIntersectingPartsRangesIntoLayers` is deliberately not guarded: it derives
its borders from interior mark values, which an endpoint check does not
constrain, and it cannot abort, so its failure mode is wrong results.

Requested by PedroTadim in ClickHouse#119159.

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

Copy link
Copy Markdown
Collaborator Author

Filed as #126409, with the two-table repro re-measured on 26.9.19.9 and on master after #119295 and #124298: the wrong answers are unchanged, and the FINAL case now reports INCORRECT_DATA on master instead of LOGICAL_ERROR.

@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-testing Test content only (no production code). labels Nov 22, 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-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants