Repository navigation
Conversation
`CancellationBudget` (added by ClickHouse#116335) lives in `src/Functions/`, but its `makeCancellationCheck` is compiled into `clickhouse_functions_obj` (`src/Functions/CMakeLists.txt:2,74`), and `dbms` does not link `clickhouse_functions`, so a storage cannot call it. Move that one translation unit into the `DBMS_FUNCTIONS` escape hatch, whose stated purpose at `:6-7` is exactly making `dbms` self-contained, and move the header alongside it. The helper itself is unchanged and its twelve existing callers in `src/Functions/` keep compiling and linking. Co-Authored-By: Claude Opus 5 <[email protected]>
A `Stress test (amd_msan)` hung check found four already-cancelled queries on
CPU for 620 s to 1944 s against `max_execution_time = 10`, every one a
`merge(REGEXP(...), ...)` read with `read_rows: 0`. The deadline watchdog had
fired on all four, which is why they report `is_cancelled: 1`; the loop the
thread was in never looks at the flag.
`StorageMerge::getColumnsDescriptionFromSourceTablesImpl` calls
`ColumnsDescription::add` (or `modify`, which re-walks the widened supertype)
once per column per matched source table, and each of those runs
`IDataType::forEachSubcolumn` over that column's entire substream tree.
Nothing on that path consults the query: before this commit
`checkTimeLimit`, `checkIfNotCancelled` and `CancellationBudget` appear nowhere
under `src/DataTypes/` or in `ColumnsDescription.cpp`, and the source-table loop
has no check either. The walk is super-linear in nesting depth because both
`Tuple` elements recurse, measured on a debug build at 0.012 / 0.052 / 0.287 /
0.685 / 1.580 s for `Array(Map(String, Tuple(a T, b T)))` nested 6 / 8 / 10 /
11 / 12 deep. MSan is the amplifier rather than the cause: every allocation in
the walk goes through `__sanitizer::StackDepotBase::Put`, the artifact's top
frame.
Give `forEachSubcolumn` an optional `CancellationBudget *`, forwarded by
`ColumnsDescription::add`, `modify` and `addSubcolumns`, and supply one from the
Merge structure inference. The budget is charged once per substream node, and
`units_per_check / 256` makes it poll once per 256 nodes: that constant is
calibrated for the cheapest possible loop, while one node here constructs
several serializations. Measured overshoot past a 1000 ms deadline afterwards is
1.7 ms, against 2830 ms before.
The parameter is opt-in rather than always-on because part loading reaches the
same walk, through `IMergeTreeDataPart::loadColumns` ->
`SharedPartColumns::buildSerializationGroup` and through the
`ColumnsDescription` built in `MergeTreeData::getSharedPartColumnsForColumns`.
`TIMEOUT_EXCEEDED` is not in `isRetryableException`, so `loadDataPart` would
classify it as corruption and `renameToDetached("broken-on-start")` the parts:
an always-on version of this checkpoint was measured to turn a 40-part table
with one nested column into an `ATTACH TABLE` that succeeds with 0 rows and 40
parts in `detached/`, under an ordinary profile `max_execution_time`. Part
loading, background merges and mutations, DDL, backup and RESTORE, part fetch,
projection checks and the readers all pass no budget, so none of them can
observe a new exception at all. `loadColumnsChecksumsIndexes` already installs
`MemoryTrackerBlockerInThread` with the comment that memory must not be limited
during `ATTACH TABLE`; opt-in keeps that exemption.
The check throws in every overflow mode, unlike the guarded sibling loop
`ReadFromMerge::createChildrenPlans` a few hundred lines below, which breaks and
keeps the plans it built. That asymmetry is deliberate: truncating child plans
returns fewer rows, whereas truncating a schema returns a wrong structure, and
`InterpreterCreateQuery` writes the inferred structure into the normalized
CREATE query, so `CREATE TABLE ... AS merge(...)` would persist it.
`makeCancellationCheck` already converts `checkTimeLimit`'s `break`-mode `false`
return into a throw for the same reason. Before this commit, a `merge()`
structure inference under `timeout_overflow_mode = 'break'` ignored the deadline
entirely and returned the complete structure.
Where no budget is passed the added work is one pointer test per callback and no
thread-local access, which matters because `SerializationObjectPool::getOrCreate`
on this chain is a reported hot spot (ClickHouse#116971). Measured on the largest single
walk that fits the default `max_query_size`, median of seven in-process runs:
1.490 s before, 1.498 s after, inside a per-binary spread of 1.489 to 1.625 s.
Co-Authored-By: Claude Opus 5 <[email protected]>
Modelled on `04763_kill_query_merge_table_plan.sh`, which covers the guarded sibling loop in the same file. Every arm matches exactly ONE source table, so a checkpoint that only ran between source tables could not satisfy any of them. The fixture nests `Array(Map(String, Tuple(a T, b T)))` ten deep, which polls 19 times inside that single column's walk; depth 6 polls only once, which is not enough for the "must not poll again" oracle. It carries no data, because structure inference reads metadata only and one row of that type occupies about 7900 stream files. Arm 1 pauses the walk at a `PAUSEABLE` failpoint placed inside the checkpoint, issues `KILL QUERY`, resumes, and requires that the walk not reach a later poll, then that `system.query_log` records `exception_code = 394`. Arm 2 does the same under `timeout_overflow_mode = 'break'`, where the pause is what makes the elapsed time exceed the deadline without relying on timing, and requires the client to fail with 159 and the message naming the Merge inference. Arm 3 is an in-range control whose full `describe_include_subcolumns = 1` output is pinned. Arm 4 requires that an `ATTACH` not reach the failpoint at all, and that the table come back with all of its parts, which is the regression guard for the part-loading exposure described in the previous commit. The failpoint is reached only through `CancellationBudget::chargeUnits` from `forEachSubcolumn`'s callback, so the pauses cannot come from another site. Deliberately reddened each arm before shipping: dropping the cancellation call from the check, charging one unit per node instead of `units_per_check / 256`, and passing no budget from `StorageMerge` each fail arms 1 and 2, while passing a budget from `SharedPartColumns::buildSerializationGroup` fails arm 4 alone. Arm 3 stayed byte-identical under all four. 50 randomized runs pass. `no-parallel` because `SYSTEM WAIT FAILPOINT ... PAUSE` and `SYSTEM NOTIFY FAILPOINT` address a process-global channel, so two concurrent instances would cross-wake each other. `no-fasttest` because two deterministic 10-second waits and a 4-second sleep are most of a test that runs in about 30 seconds. Co-Authored-By: Claude Opus 5 <[email protected]>
`ISerialization::enumerateStreams` invokes the stream callback only at a leaf; `SerializationTuple` and `SerializationNamed` push a path element and recurse without calling it. A type whose substream tree is one long path therefore yields exactly ONE callback, so a budget charged once per callback never polls: measured on `Tuple(a Tuple(a ... Int32))` at depth 100, the walk built all 100 subcolumns without observing the query a single time. The contract this change set out to give the Merge structure inference did not hold for plain nested `Tuple` DDL, and behaviour there stayed at the between-items granularity that a per-source-table guard would have had. `createFromPath` reapplies every creator preceding a prefix, so one subcolumn costs `prefix_len` pooled serialization constructions. Charging that inside the branch which performs the prefix walk covers both shapes: the unary depth-100 column now polls 17 times, and a branching depth-10 column 944. The charge sits in a branch that already builds a name, a serialization and a path copy, so the cost where no budget is passed is unchanged (one depth-12 walk, median of seven: 1.508 s before, 1.513 s after, inside the unpatched spread). `cancellation_units_per_substream` keeps its value; the overshoot past a 1000 ms deadline is 0.003 ms to 4.7 ms. The kill arm of the test moves to the unary type, which is the shape that reddens if the accounting is per callback, and the `break`-mode arm to a two-table set whose shared column enters the union as `Int32` and is widened by the deep table, so the walk happens under `ColumnsDescription::modify`. That leg was previously never executed: with a single matched table `res.has` is always false, so the widening branch never ran and removing its budget argument reddened nothing. Reverting either charge now reddens exactly one arm, and removing the budget from `modify` alone reddens the `break` arm alone. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115378&sha=061f77e9e3e30a44f4cc70763268e2fe9c8ac1af&name_0=PR&name_1=Stress%20test%20(amd_msan) Related: ClickHouse#115378 Co-Authored-By: Claude Opus 5 <[email protected]>
The runtime is 30.1 s on average over 100 randomized runs (min 29.61, max 30.87), not the 40 s the `no-fasttest` reason claimed; the deliberate waits are 24 s of that, so they are an even larger share than stated. One row of the branching depth-10 type writes 5117 streams (10243 files) in a wide part, not "about 8000 stream files". The claim that a row would dominate the test's cost was also wrong: the insert measures 0.98 s against a 30 s test. The real reason the fixtures hold no data is the first half of that sentence, that structure inference reads metadata only, so the comment now stops there. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewReviewed in two rounds before publishing. Round 1 found one blocker in my own first version, fixed in the Round 1 also found that The checkpoint is opt-in on purpose. An always-on version of it is reachable from part loading, where Measured on 20 tables with one depth-10 column: 2.1 s past a 1000 ms deadline before, 4.7 ms after, and Category is |
|
Workflow [PR], commit [8bb466c] Summary: ❌
AI ReviewSummaryThe PR makes Missing context / blind spots
Findings
Tests
Final Verdict |
|
cc @tavplubix @CurtizJ, could you review this? The |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes328 object files changed (+45.64 KiB total), 1 added.
720 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units
|
`Stateless tests (amd_asan_ubsan, flaky check)` failed this test on its run time, not on an assertion: 4 of 7 runs took 181 s to 208 s against the 180 s per-run ceiling, every failure carrying the same reason, `Test runs too long (> 180s)`. The 50 randomized runs that validated the test ran on a debug build at 30 s each, which says nothing about that job: ASan plus UBSan and runner contention multiply this test by about 6. Three costs go, none of them an assertion: The two negative observations waited 10 s each for a pause that must never arrive. A walk that ignores the cancellation reaches its next poll one poll interval later, measured at 26 ms for a notify-and-repause cycle on an ASan+UBSan build, so 3 s keeps a margin of two orders of magnitude even after the observing client's own 0.5 s start-up. The branching column drops from nesting depth 10 to 8 and the part-loading arm's from 8 to 6, which cuts the substream trees they walk by 4x each. Both keep far more polls than any arm consumes: 181 and 33 against the two that the granularity assertions need, and the widened union in the `break` arm 185. The part-loading arm writes one part instead of three, and its wide part now holds 317 streams instead of 1277. 29 client invocations become 18 by batching statements that were already sequential in one session. Each process costs 0.46 s before it runs a query on this build, and the runner adds its randomized settings to every one of them. Measured with `clickhouse-test --test-runs N` against an ASan+UBSan build of this branch, randomized settings on, the test in the sequential group as its `no-parallel` tag puts it: 68.43 s to 72.18 s over 5 runs before, 32.42 s to 34.63 s over 9 runs after. The debug build goes from 30 s to 12.95 s. The acceptance gate is unchanged and was re-run against the faster test, each mutation built and served with its Build-ID verified: M1 (the check wrapper drops `inner()`) and M3 (StorageMerge passes no budget) redden the kill and `break` arms, M6 (charge once per stream callback) the kill arm alone, M5 (`modify` loses its budget) the `break` arm alone, M4 (part load passes a budget) the part-loading arm alone, and the in-range control reddens under none of them. M2 (one unit per unit of work) now reddens the `break` arm as well as the kill arm: at depth 10 the widened supertype charged enough units to survive a 256x coarser granularity, at depth 8 it does not. Co-Authored-By: Claude Opus 5 <[email protected]>
… tables `getColumnsDescriptionFromSourceTablesImpl` only charged the cancellation budget from `ColumnsDescription::add` and `::modify`, so a table whose columns are all present already took neither branch and was never a checkpoint. Once the schema stops changing, which is the common case for a homogeneous set of children, the traversal therefore kept fetching metadata and comparing columns for up to `merge_table_max_tables_to_look_for_schema_inference` tables after the query had been killed or had passed `max_execution_time`. Measured on a debug build, 100 identical tables holding one depth-10 nested column, `DESCRIBE TABLE merge(...) SETTINGS max_execution_time = 0.25`: `query_duration_ms` was 465/470/596 before and is 267/268/301 now, the exception reporting `elapsed 251.6 ms`. Per-table cost grows with the type's substream count (0.10 ms for 100 flat columns, 0.78 ms at depth 8, 3.70 ms at depth 10), so at the 1000-table default the residual was seconds for exactly the schemas this checkpoint exists for. The per-table checkpoint gets its own pauseable failpoint so that each arm of 05158 can only be stopped by the checkpoint it is about: the deep-column arms still fail if the per-column poll disappears, and the new two-identical-tables arm fails if the per-table one does.
…ructure-inference-observes-query-limits
CI finish ledger - 90a65caEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260910-150249 |
CI finish ledger - e8a055eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this pull request. This workflow was dispatched at 16:38:24Z, about 48 minutes Session id: cron:our-pr-ci-monitor:20260911-010040 |
The per-table checkpoint added for the schema-inference traversal sat at the top of the
predicate, ahead of the SHOW_TABLES filter. A traversal already past its deadline therefore
threw TIMEOUT_EXCEEDED as soon as it reached a table the user is not allowed to see, while a
pattern matching no table at all still reported "no tables". The two outcomes are
distinguishable, so the error code told the user whether tables they cannot see exist, and
03400_merge_storage_underlying_tables_access_validation pins the opposite contract: a table
without SHOW must behave as absent.
Measured on a database of 400 tables the probing user has no grant on, reached through
CREATE TABLE ... ENGINE = Merge:
max_execution_time existing hidden tables no matching table
0.0005 and below TIMEOUT_EXCEEDED CANNOT_EXTRACT_TABLE_STRUCTURE
0.001 and above CANNOT_EXTRACT_... CANNOT_EXTRACT_TABLE_STRUCTURE
At 0.000001 the leak was deterministic over 10 runs. Above ~1 ms the walk over unreadable
tables is too cheap to reach the deadline, which is why it needs a small one to show. Both
callers reach the traversal through the same routine, so merge() exposed it too; only the
error it ends in differs (BAD_ARGUMENTS rather than CANNOT_EXTRACT_TABLE_STRUCTURE).
Moving the check below the visibility filter closes it: both cases now report the same error
at every deadline tested, 10/10 at 0.000001 for either caller, while a user who can see the
same 400 tables still gets TIMEOUT_EXCEEDED at 0.001 and completes normally with no deadline.
The check still runs once per matched table and still precedes getInMemoryMetadataPtr and the
per-column comparisons, so the uncancellable walk it was added for stays covered; it is
skipped only for tables whose iteration ends at the filter anyway.
The new last arm of 05158 asserts the contract, with a guard that the probing user really
sees none of the sources: any grant on a table implies SHOW_TABLES for it, so a
destination-database grant that reached the sources would leave them visible and the arm
would assert nothing. Hoisting the check back above the filter reddens that arm alone
("existing unreadable sources gave Code: 159 but an absent one gave Code: 636") and leaves
the other five byte-identical.
|
|
||
| /// The budget above is only charged when a table contributes a new or a widened column, so once the | ||
| /// schema stops changing it is this check that observes the query's limits. It follows the visibility | ||
| /// filter so that a table the user may not see fails alike whether or not it exists. |
There was a problem hiding this comment.
The per-table check moved below SHOW_TABLES, but tables skipped here never increment table_num either. If the regexp matches only (or many) unreadable tables, this lambda returns before either check_cancellation() or table_num >= max_tables_to_look can fire, so a killed / timed-out schema inference still walks the entire hidden-table set and can finish as CANNOT_EXTRACT_TABLE_STRUCTURE / BAD_ARGUMENTS instead of stopping promptly. 05158's new last arm still passes in that state because it only asserts hidden-vs-absent equivalence after the scan. Can we keep a cancellation checkpoint on the raw candidate-table walk and normalize the hidden-vs-absent result separately?
CI finish ledger - 310e58dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
My own #113242 fixed the Not reachable from this PR: the diff adds a cancellation budget to Merge structure inference Session id: cron:our-pr-ci-monitor:20260911-130041 |
The branch was 14 days behind master and GitHub reported it as conflicting. One conflict, in the `ColumnsDescription::modify` template: master's ClickHouse#121449 added an `invalidateGetCache()` and a guard that skips `addSubcolumns` for ALIAS columns, while this branch threads a `CancellationBudget *` into the same call. Both are kept - the guard and the cache invalidation from master, with the budget passed to the `addSubcolumns` call that survives the guard. Everything else merged without conflicts. The per-table cancellation check in `StorageMerge::getColumnsDescriptionFromSourceTablesImpl` still sits between the SHOW_TABLES visibility filter and the SHOW_COLUMNS check, so the property from the previous round holds: a table the user may not see behaves alike whether or not it exists. Master's new StorageAlias target-privilege check lands after it, unchanged. Master has no cancellation checkpoint in that function and its `forEachSubcolumn` still takes no budget, so nothing in this branch has been superseded.
…erence-observes-query-limits
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Inferring the structure of a
Mergetable, for example inSELECT ... FROM merge(...), now reacts toKILL QUERYandmax_execution_timewhile it walks the source tables and while it enumerates one column's subcolumns, instead of only after each enumeration has finished. Undertimeout_overflow_mode = 'break'such a query now fails rather than ignoring the limit, because a truncated schema would be wrong rather than smaller.Description
A
Stress test (amd_msan)hung check on #115378 caught four already-cancelledmerge(REGEXP(...), ...)queries on CPU for 620-1944 s againstmax_execution_time = 10. Asked for here.The four rows, from the job's
hung_check.logAll four sample in one walk:
SerializationObjectPool::getOrCreate<-ISerialization::pooled<-SerializationNamed::create<-ISerialization::createFromPath<-IDataType::forEachSubcolumn<-a repeating
SerializationArray/SerializationMap/SerializationNamed/SerializationTupleenumerateStreamschain, under__sanitizer::StackDepotBase::Put.Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115378&sha=061f77e9e3e30a44f4cc70763268e2fe9c8ac1af&name_0=PR&name_1=Stress%20test%20(amd_msan)
Log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/115378/061f77e9e3e30a44f4cc70763268e2fe9c8ac1af/pr/stress_test_amd_msan/hung_check.log
The stack ends inside that recursion, so the artifact does not name the caller; locally the walk is reached from
StorageMerge::getColumnsDescriptionFromSourceTablesImpl, which runsIDataType::forEachSubcolumnper column, per source table, consulting the query nowhere. One depth-12 column's walk takes 1.5 s on a debug build, ~2.4x per level.This gives the enumeration an optional
CancellationBudget *, passed only by Merge structure inference. Work is charged per stream callback and per subcolumn prefix step, so a single-path tree still polls. It throws in every overflow mode, unlike the siblingcreateChildrenPlansloop, becauseCREATE TABLE ... AS merge(...)persists the inferred structure: truncating it is a wrong schema, not a smaller one. Opt-in matters: an always-on checkpoint reaches part loading, whereTIMEOUT_EXCEEDEDis not retryable; I measured a 40-part table come back empty, its parts indetached/broken-on-start.A source table whose columns are all present reaches neither
ColumnsDescription::addnor::modify, so the checkpoint also runs per source table, before its metadata is fetched. It runs after theSHOW TABLESfilter: ahead of it, a cancelled walk answeredTIMEOUT_EXCEEDEDfor an unreadable table but "no tables" when none matched, telling the user it was there. 05158's last arm pins it; both now answer alike.On 20 tables with one depth-10 column: 2.1 s past a 1000 ms deadline before, 4.7 ms after; on 100 identical such tables, where only the per-table checkpoint can fire, 465-596 ms past a 250 ms deadline before, 267-301 ms after. No budget, no cost change (depth-12 walk, median of 7: 1.508 vs 1.513 s).
Left alone: the other query-driven callers stay uninterruptible, and
modifystill re-walks the widened type per source table.Workflow [PR]
Sync PR [sync-upstream/pr/119124]