Skip to content

Observe the query's limits while inferring a Merge table's structure - #119124

Open
groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:merge-structure-inference-observes-query-limits
Open

groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:merge-structure-inference-observes-query-limits

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Inferring the structure of a Merge table, for example in SELECT ... FROM merge(...), now reacts to KILL QUERY and max_execution_time while it walks the source tables and while it enumerates one column's subcolumns, instead of only after each enumeration has finished. Under timeout_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-cancelled merge(REGEXP(...), ...) queries on CPU for 620-1944 s against max_execution_time = 10. Asked for here.

The four rows, from the job's hung_check.log
log_comment                                          elapsed    is_cancelled  read_rows  merge() call
01318_encrypt.sql-test_2                             1943.80 s  1             0          merge(REGEXP('.*[0-9].*'), 't\0*')
05019_join_shard_by_pk_ranges_pruned_side.sql-test_3 1928.41 s  1             0          merge(REGEXP('t.*'), '.*')
(no log_comment, parseQueryToJSON + alias1869)        1585.81 s  1             0          merge(REGEXP('t.*'), '^')
04692_totime_key_reload_use_legacy_to_time.sql-test_1  620.63 s  1             0          merge(REGEXP('^'), '.*')

All four sample in one walk: SerializationObjectPool::getOrCreate <- ISerialization::pooled <-
SerializationNamed::create <- ISerialization::createFromPath <- IDataType::forEachSubcolumn <-
a repeating SerializationArray/SerializationMap/SerializationNamed/SerializationTuple
enumerateStreams chain, 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 runs IDataType::forEachSubcolumn per 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 sibling createChildrenPlans loop, because CREATE 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, where TIMEOUT_EXCEEDED is not retryable; I measured a 40-part table come back empty, its parts in detached/broken-on-start.

A source table whose columns are all present reaches neither ColumnsDescription::add nor ::modify, so the checkpoint also runs per source table, before its metadata is fetched. It runs after the SHOW TABLES filter: ahead of it, a cancelled walk answered TIMEOUT_EXCEEDED for 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 modify still re-walks the widened type per source table.


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

groeneai and others added 5 commits September 9, 2026 20:50
`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed in two rounds before publishing. Round 1 found one blocker in my own first version, fixed in the
tree above: the cancellation budget was charged once per stream callback, and enumerateStreams invokes that
callback only at a leaf, so a type whose substream tree is a single path (nested Tuple, and Named
wrappers over it) produced exactly ONE callback and never polled at any depth. It is now charged per
subcolumn prefix step as well, because createFromPath reapplies every preceding creator: a unary
Tuple(a Tuple(a ... Int32)) at depth 100 polls 17 times, a branching depth-10 column 944.

Round 1 also found that ColumnsDescription::modify, the second site this PR passes a budget to, was never
executed by the test, because with one matched source table the widening branch never runs. The break-mode
arm now reaches the walk through it, and removing that one argument reddens that arm alone.

The checkpoint is opt-in on purpose. An always-on version of it is reachable from part loading, where
TIMEOUT_EXCEEDED is not retryable, and I measured a 40-part table come back with 0 rows and its parts
renamed into detached/broken-on-start; the test's part-loading arm guards that.

Measured on 20 tables with one depth-10 column: 2.1 s past a 1000 ms deadline before, 4.7 ms after, and
timeout_overflow_mode = 'break' went from silently ignoring the deadline to failing. A mutation reddens
each arm that can fail; the in-range control is reddened by none of the six. 50 randomized runs pass.

Category is Improvement, matching the merged #113415 on the sibling loop in the same file rather than the
Bug Fix used by #116335. Happy to change it if you would rather this one were a bug fix.

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8bb466c]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

The PR makes Merge schema inference observe cancellation and execution deadlines inside subcolumn enumeration and between visible source tables. One previously reported cancellation gap remains in the current head, 8bb466cf0a92fdd2bdf6964f672fc1c8b744e2f8; changes are requested.

Missing context / blind spots
  • ⚠️ The current head's stateless test results are not yet available, and this checkout has no built server for a local run. Completed CI results for 05158_kill_query_merge_table_structure would close this validation gap.
Findings

⚠️ Majors

  • src/Storages/StorageMerge.cpp:338–345: Hidden source tables bypass cancellation. A candidate without SHOW_TABLES returns before both check_cancellation and the table_num increment. When the pattern matches only hidden tables, traverseTablesUntilImpl therefore scans every candidate without consulting the query, regardless of KILL QUERY, max_execution_time, or merge_table_max_tables_to_look_for_schema_inference. It can ultimately report CANNOT_EXTRACT_TABLE_STRUCTURE or BAD_ARGUMENTS after doing all the work. This leaves the promised cancellation behavior incomplete. Poll during the raw candidate traversal and handle expired empty/hidden results consistently so cancellation does not disclose table existence. Existing inline finding; still present, so no duplicate comment was posted.
Tests
  • ⚠️ 05158_kill_query_merge_table_structure.sh:285–299 checks only that hidden and absent sources produce equal error codes. Both probes can ignore the expired deadline and still pass. Require TIMEOUT_EXCEEDED for both expired probes, and cover cancellation during hidden-candidate traversal while preserving their indistinguishability.
Final Verdict

⚠️ Request changes. Make hidden-candidate traversal observe cancellation without exposing table existence, and add the focused regression assertions above.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @CurtizJ, could you review this? The Merge structure inference walked a column's whole substream tree without ever consulting the query, so an already-cancelled merge(REGEXP(...), ...) stayed on CPU for up to 1944 s in a hung check; it now charges a cancellation budget inside IDataType::forEachSubcolumn, per stream callback and per subcolumn prefix step, and only that one caller passes a budget so part loading is unaffected.

@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8bb466cf0 with master 8bbee3d1b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: compile time of recompiled translation units.

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.

Object file sizes

328 object files changed (+45.64 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/CancellationBudget.cpp.o new 35.46 KiB +35.46 KiB

720 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units ⚠️

3185 translation units recompiled, 18069 s compile time in total, 1241 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Formats/FormatFactory.cpp: 50.3 s
  • src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp: 38.0 s
  • src/Functions/array/arrayElement.cpp: 37.6 s
  • src/Functions/polygonsSymDifference.cpp: 33.0 s
  • src/Functions/array/mapPopulateSeries.cpp: 26.4 s
  • src/Functions/polygonsIntersection.cpp: 25.6 s
  • src/Functions/polygonsUnion.cpp: 23.9 s
  • src/Functions/array/arraySort.cpp: 22.6 s
  • src/Functions/FunctionsRound.cpp: 22.2 s
  • src/DataTypes/Serializations/SerializationMap.cpp: 20.4 s
  • src/Columns/ColumnVector.cpp: 20.4 s
  • src/Processors/Transforms/SortingTransform.cpp: 19.9 s
  • src/Dictionaries/RangeHashedDictionaryGetItemsImplOthers.cpp: 19.2 s
  • src/Functions/array/arrayDistance.cpp: 19.2 s
  • src/Functions/polygonsDistance.cpp: 19.0 s
  • src/Dictionaries/RangeHashedDictionaryGetItemsImplInt.cpp: 18.9 s
  • src/Dictionaries/RangeHashedDictionaryGetItemsShortCircuitImplOthers.cpp: 18.8 s
  • src/Dictionaries/RangeHashedDictionaryGetItemsShortCircuitImplInt.cpp: 18.6 s
  • src/Dictionaries/RangeHashedDictionaryGetItemsShortCircuitImplUInt.cpp: 17.6 s
  • src/Functions/lessOrEquals.cpp: 17.1 s
  • ... and 385 more

Job report

`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]>
Comment thread src/Storages/StorageMerge.cpp Resolved
… 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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 90a65ca

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 Not from this PR. The test asserts a stack frame above max(address_end) from system.symbols, which Darwin does not produce. Trunk-wide and first seen today: 130 failures across 117 distinct PRs, 0 on true master #119145 (mine, merged 2026-09-10 10:27Z), picked up here by merging master @ 943ddbf7b4e5
Stress test (amd_asan_ubsan) / S3_ERROR No such key on 05104_s3_plain_rewritable_hard_links Not from this PR. A mutation entry is removed concurrently on a readonly shared directory; 16 distinct PRs plus 3 true-master hits in 30 days #119154 (mine, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) Not from this PR, and not a test failure: the job hit its 9000s budget after 9068s with 0 failing tests, cut off at test 13093 of 13857. 87 rows across 75 distinct PRs plus 11 true-master hits in 14 days #116209 (mine, open), which splits this exact un-batched job into 1/2 and 2/2

Mergeable Check and PR are rollups of the three rows above, not separate failures.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e8a055e

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[local, s3] server abort on the Iceberg pruning path from merged #118606 #119298 (external, merged 17:26:35Z) reverted the cause on master and is NOT in the tree this run built (ledger rule 3c, not 3d); forward fix #119292 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_bucket_partition_pruning.py::test_bucket_partition_pruning[local, s3, azure] collateral of the same abort: the server is gone for the rest of the module #119298 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

Not caused by this pull request. This workflow was dispatched at 16:38:24Z, about 48 minutes
before #119298 merged, so the build predates the revert; a run on a tree that contains it does
not show these failures. The same abort collapsed this module on true master and on many other
pull requests today. PR is the praktika rollup of that single integration job, not a separate
failure. A master merge is owed here to re-run CI on a tree that contains the revert.

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.

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.

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?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 310e58d

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
Stress test (amd_msan) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-3319) trunk bug in the sort-property contract. The AST fuzzer inside the stress run created dist_distinct__fuzz_4 (s UInt256) ENGINE = Distributed(..., t_distinct, rand()) over t_distinct (s String) and ran SELECT DISTINCT s FROM dist_distinct__fuzz_4 ORDER BY s ASC LIMIT 100 SETTINGS optimize_distinct_in_order = 1, so DISTINCT-in-order consumed a stage ordered on the shards' String after the declared-type cast to UInt256 had reordered it (abort at DistinctSortedStreamTransform.cpp:184, leaf ColumnVector<UInt256>). 38 rows on 33 pull requests plus 4 true-master rows in 30 days for this STID; 225 rows on 186 pull requests plus 9 true-master rows for the assertion as a whole. #118445 (external, open)
Mergeable Check, PR workflow-level rollups of the single row above, no independent failure #118445 (external, open)

My own #113242 fixed the Merge side of that order-breaking cast and is already an ancestor of this
head, so it is not the owner here; #118445 is the Distributed sibling for the same defect and is
still open.

Not reachable from this PR: the diff adds a cancellation budget to Merge structure inference
(StorageMerge::getColumnsDescriptionFromSourceTablesImpl, ColumnsDescription::add, the
IDataType substream walk), two failpoints and one stateless test, and touches nothing in the
sorting, read-in-order or DISTINCT paths that abort. Everything else on this head is green:
174 of 174 checks completed, Finish Workflow OK, CH Inc sync OK, and all five flaky-check
arms reported 0 failures.

Session id: cron:our-pr-ci-monitor:20260911-130041

groeneai and others added 2 commits September 25, 2026 12:18
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.

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-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants