Skip to content

Read the default of a column that a part does not hold, not a subcolumn of that name - #118242

Open
alexey-milovidov wants to merge 98 commits into
masterfrom
shadowed-subcolumn-default-114588
Open

alexey-milovidov wants to merge 98 commits into
masterfrom
shadowed-subcolumn-default-114588

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

ALTER TABLE ... ADD COLUMN could add a column whose name is also the name of a subcolumn of another column, such as a.size0 next to an Array column a. The parts written before the ALTER hold no such column, and the reader looked its name up among the part's columns and their subcolumns, so it answered with the array's sizes instead of the column's default:

CREATE TABLE t (a Array(UInt64)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ([0]), ([1, 2]);
ALTER TABLE t ADD COLUMN `a.size0` UInt64 DEFAULT 7;
INSERT INTO t (a, `a.size0`) VALUES ([3], 7);

SELECT a, `a.size0` FROM t;
-- [0]    1   <- the array-size subcolumn, where the DEFAULT 7 belongs
-- [1,2]  2
-- [3]    7   <- the stored value, from the part written after the ALTER

A merge then stored those values, so the wrong result outlived the mixed-parts state. Keys, skip indices, projections, statistics and TTL infos of the old parts may also have been computed from the subcolumn, so the name cannot simply change its meaning for them.

Following the review (#118242 (review), option 1), such an ALTER is now refused: ADD COLUMN, RENAME COLUMN, or MODIFY COLUMN from ALIAS, may not give a stored column the name of a subcolumn of another stored column (a.size0 of an Array, t.x of a Tuple, any j.x of a JSON column, s.null of a Nullable). ALIAS columns and CREATE TABLE stay allowed. This rejects an ALTER that worked before.

Parts may still miss such a column: in a table created with it and skip_empty_columns_on_insert, or in a table where an older version added it. Every place that looks up a column in a part (the reader, size estimates, projection and skip index checks, mutation fast paths) now matches a column of the table only by its exact name, so these parts read the column's default. A projection that selects such a column stores it as a column of its own; before, it computed the other column's subcolumn in its place, and with the column in the projection key an insert failed with a logical error. On INSERT, in merges and in mutations, a subcolumn required by a key (of the table or of a projection) or a skip index is taken from the column that the table gives the name (a.x.y from a Tuple column a.x, not from the path x.y of a JSON column a); before, the primary index, a skip index or a projection over it was built from the other column and dropped matching granules. In tables where an older version already added such a column, the old parts now read the default, also for keys, TTL and projections computed from the subcolumn; the values read there were wrong anyway.

Closes: #114588
Related: #113420
Related: #92453

Changelog category (leave one):

  • Backward Incompatible Change

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

ALTER TABLE can no longer add a stored column (or rename one) under the name of a subcolumn of another column, such as a.size0 next to an Array column a or j.x next to a JSON column j: the existing parts returned the subcolumn's values instead of the column's default. Use another name or an ALIAS column. Parts that do not hold such a column (for example, in tables where it was added by an older version) now read its default.

🤖 Generated with Claude Code


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

…mn of that name

`ALTER TABLE ... ADD COLUMN` may add a column whose name is also the name of a
generated subcolumn of another column, such as `a.size0` next to an `Array`
column `a`. The parts written before the ALTER hold no such column, and the
reader looked its name up among the part's columns *and their subcolumns*, so it
answered with the array's sizes instead of the column's default:

    CREATE TABLE t (a Array(UInt64)) ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO t VALUES ([0]), ([1, 2]);
    ALTER TABLE t ADD COLUMN `a.size0` UInt64 DEFAULT 7;
    INSERT INTO t (a, `a.size0`) VALUES ([3], 7);

    SELECT a, `a.size0` FROM t;   -- 1, 2 and 7: one query, two meanings of one name

A merge then stored those values, so the wrong result outlived the mixed-parts
state.

The lookup goes through subcolumns because for a wide part the flattened columns
of a `Nested` column are collected back into one column, whose subcolumns they
become. That answer is now accepted only for a column the part really stores
under its own name, or when a subcolumn is what was requested.

Closes: #114588

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [67bdeab]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
05871_column_shadowing_subcolumn_keys_after_merge FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
05871_column_shadowing_subcolumn_keys_after_merge FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
05871_column_shadowing_subcolumn_keys_after_merge FAIL cidb
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
05871_column_shadowing_subcolumn_keys_after_merge FAIL cidb
05871_column_shadowing_subcolumn_keys_after_merge FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (wasm64) DROPPED
Build (arm_fuzzers) DROPPED
Integration tests (arm_binary, distributed plan, targeted) DROPPED

AI Review

Summary

The PR rejects new column/subcolumn collisions introduced by ALTER TABLE and preserves table column identity in part lookups and several expression paths. Review of 67bdeab83e1d still finds incorrect persisted defaults, ineffective CHECK constraints, and a previously dismissed TTL data-loss case for schemas that remain supported by CREATE TABLE.

Findings

❌ Blockers

  1. Dependent defaults read the wrong source when their parent is omitted. InsertDependenciesBuilder.cpp:1877, createSubcolumnsExtractionActions.cpp:48. For a JSON, physical a.x Tuple(y UInt64), and d DEFAULT toUInt64(a.x.y) / m MATERIALIZED toUInt64(a.x.y), inserting only a = '{"x":{"y":11}}' stores a.x.y = 0 but d = m = 11. Giving a.x an explicit tuple default of 44 instead stores 44, 11, 11. Confirmed for values, select, and materialized-view inserts. The preferred parent is absent from the original input block, and extraction falls through to the JSON prefix. Materialize the actual parent's default before extracting its subcolumn. This persists after the claimed fix in 67bdeab83e1d; the existing thread is reopened with a reproducer.

  2. Constraint checks still use another column's values. createSubcolumnsExtractionActions.h:19, ConstraintsDescription.cpp:184. Constraint extraction omits the optional metadata argument and retains the first-prefix resolution. A table with a JSON, a.x Tuple(y Dynamic), and CHECK toUInt64(a.x.y) = 44 accepts JSON value 44 alongside tuple value 11; selecting a.x.y returns 11. Pass the resolved source column descriptions through constraint extraction and test valid and invalid tuple values. This is a new inline finding.

  3. TTL evaluation can delete an unexpired row. ITTLAlgorithm.cpp:63. [dismissed by author -- https://github.com/Read the default of a column that a part does not hold, not a subcolumn of that name #118242#discussion_r4363924570] The author placed write-time TTL ambiguity outside this PR; it remains a reproducible data-loss path for the colliding schemas this PR explicitly permits. With allow_suspicious_ttl_expressions = 1, create (id UInt64, a JSON, a.x Tuple(y Dynamic)), ORDER BY id, and TTL toDateTime(toUInt64(a.x.y)). Insert (1, '{"x":{"y":1}}', tuple(4102444800::UInt64)). A read shows expiration 2100-01-01 00:00:00, but OPTIMIZE TABLE ... FINAL deletes the row because TTL extraction reads the JSON path 1. Preserve the table's resolved parent throughout TTL calculation, or reject the ambiguous TTL before accepting data. Kept in this summary only; no duplicate inline comment or thread reply.

Tests
  • ⚠️ Extend 05872 with an omitted parent, both with a type default and an explicit DEFAULT, and assert dependent DEFAULT / MATERIALIZED values for values, select, and materialized-view inserts. Its current supplied-parent cases pass while these variants fail.
  • ⚠️ Add a focused stateless constraint regression and a TTL regression asserting that the row with expiration 2100-01-01 survives a merge. All reproductions above used the head's Fast test binary. Existing tests 05229, 05836, 05838, 05871, and 05872 also ran locally and matched their references.
Final Verdict

Status: ❌ Block

Fix omitted-parent default evaluation and constraint extraction, and fix or explicitly track the remaining TTL source mismatch before approval.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 67bdeab83 with master 3dac6f430 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Object file sizes

31 object files changed (+80.42 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.79 MiB 4.84 MiB +51.37 KiB (+1.05%)

716 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

1160 translation units recompiled, 6291 s compile time in total, 1160 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits September 10, 2026 21:52
The `Nested` non-regression cases were far too small to leave `Compact`, so
they never reached the `getColumnsDescriptionWithCollectedNested` branch that
`IMergeTreeReader::tryGetColumnInPart` has to leave alone - the branch that
collects the flattened columns of a `Nested` column back into one column of a
`Wide` part and reads them as its subcolumns.

Force those two tables to `Wide` with `min_bytes_for_wide_part = 0`,
`min_rows_for_wide_part = 0` and `min_level_for_wide_part = 0` - all three,
because a part is `Compact` when any one of the three thresholds is not met -
and assert the resulting `part_type`, so a future default cannot silently take
the coverage away again. Keep the `Compact` shape too, as a third table with an
explicit large `min_bytes_for_wide_part`, so both readers stay covered.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed: merged master (the branch was ~3.4k commits behind) and addressed the review — both Nested cases are now forced to Wide parts with an explicit part_type assertion, plus a Compact counterpart. 05087_column_shadowing_subcolumn_default passes locally, with and without settings randomization.

The two reds on the previous commit are unrelated to this change:

@groeneai

Copy link
Copy Markdown
Collaborator

Already picked up: I filed #113292 and the fix is open as #113515 (Closes #113292), so a separate PR would duplicate it.

That red (STID 3634-43a0) is the issue's exact shape:

SELECT count() FROM (SELECT k FROM mt__fuzz_5 RIGHT JOIN (SELECT toUInt64(toLowCardinality(1000000000)) AS k) AS r USING (k) WHERE k = 1048576)

For a RIGHT JOIN, getSupportingParallelReplicasQueries descends into the left table expression, while buildQueryTreeForShard materializes the left side into a temporary table, so the query is selected for parallel replicas and then has no table left to read. #113515 makes the descent follow the right table expression, so a right side with no eligible table (a constant-only subquery here) is not selected at all.

#113515 is green on 801d300f and has been waiting for review since 2026-08-05.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

I downgraded all four flagged improvements to not_sure, because this PR cannot plausibly speed these queries up: ClickBench Q33 (-9.3%), Q34 (-10.6%), and TPC-H Q1 (-20.0%) and Q7 (-24.7%). The PR is a correctness fix: a table column named like another column's subcolumn (for example a.size0 next to an Array column a) now resolves to the column itself. The new lookups give the same answers as before on tables without that kind of name clash, which covers ClickBench and TPC-H, and they run once per part or column during planning, not per row. All four queries have noisy master history, the two ClickBench medians fall inside master's recent ranges, and the TPC-H deltas are only 13-20 ms, so these improvements are noise, not an effect of the PR.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1134 1028 -9.3% <0.0001 aggregation: The diff only changes how column names are looked up during read planning and part handling. This large GROUP BY reads ordinary physical columns, so nothing it runs per row changed, and 1028 ms falls inside master's recent 962-1202 ms range.
⚠️ 34 not_sure 1140 1019 -10.6% <0.0001 aggregation: The -10.6% shift, with matching CPU drop, sits inside master's recent 964-1177 ms range on a query with noisy history. The PR's lookup changes only take a different path when a table column shares its name with a subcolumn, and ClickBench has no such column.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 52 -20.0% <0.0001 The -20.0% is 13 ms on a 65 ms query with very noisy measurements and noisy history. The PR's per-part setup and PREWHERE sizing changes give the same result when every column is stored in every part, as in TPC-H.
⚠️ 7 not_sure 81 61 -24.7% <0.0001 The -24.7% is 20 ms on an 81 ms join query with noisy history. No changed code path affects join or scan execution for tables that have no column named like another column's subcolumn.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 1f2e0188-504a-4f28-bd9a-8dbc0783f874
  • MIRAI run: 7c89b5b3-9f3a-4b6c-9a63-6e041a8dc889
  • PR check IDs:
    • clickbench_1080610_1791821879
    • clickbench_1080616_1791821879
    • clickbench_1080622_1791821879
    • tpch_adapted_1_official_1080628_1791821879
    • tpch_adapted_1_official_1080644_1791821879
    • tpch_adapted_1_official_1081096_1791821884

alexey-milovidov and others added 2 commits September 18, 2026 22:46
`05087` was taken by `05087_create_view_inferred_suspicious_type` on master while this branch waited.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks — acknowledged, #113515 already covers the AST fuzzer red (#113292), so nothing to duplicate from here. The analysis matches what the report showed: getSupportingParallelReplicasQueries descending into the left table expression of a RIGHT JOIN while buildQueryTreeForShard materializes that side away.

Pushed in this pass: merged master (the branch was ~4.2k commits behind, clean merge) and renumbered the test to 05229_column_shadowing_subcolumn_default — 05087 had been taken by 05087_create_view_inferred_suspicious_type on master in the meantime. Rebuilt on the merged tree and the test passes locally.

Related: #113515

alexey-milovidov and others added 3 commits September 19, 2026 20:44
The reader now fills a column the part does not hold from its default,
even when the part has a same-named subcolumn of another column
(`a.size0` next to an `Array` column `a`). The planning code still asked
`IMergeTreeDataPart::tryGetColumn`, which resolves such a name to the
generated subcolumn, so `estimateReadBytes`, `getColumnSizesForPrewhere`,
`MergeTreeReadPoolBase` task sizing, `MergeTreePrefetchedReadPool` prefetch
budgeting and `MergeTreeBlockSizePredictor` costed a read that never
happens.

Add `IMergeTreeDataPart::tryGetColumnForTable`, which answers a name the
table declares as a column in its own right only with a column the part
stores under that name, and use it in those callers.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118242&sha=98981483a2d9235747ba3026cb90de6f23e65fb1&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 (Logical error: Digest does not match, STID 5007-4c3e, tracked in #114819; #113009 looks like the fix) and provide a fix in a separate PR. If the fix is already in progress, link it here. The Build profile diff red is the CI logs cluster query failing, an infrastructure issue.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix in progress: #117235. #113009 is only the diagnostic: it restores the AST differs for table dump on sanitizer builds, which define NDEBUG (this log has 0 of those lines), so it makes a sighting localizable but does not stop the divergence.

This run's own log confirms the mechanism I wrote up in #114819, on test_5:

03:33:32.170241 [ 6000 ]  DDLWorker(test_5): Processing task query-0000000479
                          (CREATE TABLE test_5.t_shared_offsets_wrapped, run inline on the initiating thread)
03:33:32.480708 [ 11155 ] executeQuery: DETACH DATABASE test_5
03:33:33.288610 [ 11155 ] DatabaseReplicated (test_5): Counting detached table ...
                          (first of 9 in-memory erases that land before the abort)
03:33:34.295517 [ 6000 ]  Digest of local metadata (8364488281718558985) is not equal to
                          in-memory digest (2217816366204845452)
03:33:34.301155 [ 6000 ]  Logical error: 'Digest does not match'

Those 9 lines are logged by DatabaseWithOwnTablesBase::detachTableUnlocked right after tables.erase, with no tables_metadata_digest arithmetic, so the sum checkDigestValid recomputes over tables is short by 9 terms. The entry executing on thread 6000 still holds its ZooKeeperMetadataTransaction, so the "database is probably being dropped" exemption at DatabaseReplicated.cpp:1402 does not cover it. There are 0 is not equal to digest in Keeper lines, so the skew is local only, as in the earlier occurrence.

Nothing here is specific to your change: commitCreateTable is just where the 1-in-16 sampling in assertDigestWithProbability fired, and this signature has 10 sightings in 90 days across 10 unrelated pull requests, none on master.

SYSTEM RESTORE DATABASE REPLICA is a second carrier of the same window: #117399. Both fix PRs are open and unreviewed.

alexey-milovidov and others added 2 commits October 2, 2026 22:09
… of a shadowed column

The test pinned `MATERIALIZE COLUMN m` computing `a.size0 + 1` from the offsets of
the `Array` column `a` (giving 4 and 2), because the part holds `a.size0` only as a
missing-column marker and the reader used to resolve the name to the subcolumn. With
this change the column reads its default `0`, so `m` is `1`, which is also what the
same test already expects after `CLEAR COLUMN`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118242&sha=cddd3845285b476d690cbbac3ac528d104b54e6a&name_0=PR&name_1=Fast%20test
#118242

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai — noted, #117235 is the fix for the Digest does not match red (#114819), so nothing to do for it here.

Pushed in this pass: merged master (~5.5k commits behind, clean merge) and fixed the Fast test red. 05227_mutation_clears_shadowed_column_stream, added on master in the meantime, pinned MATERIALIZE COLUMN m (MATERIALIZED a.size0 + 1) computing from the offsets of the array a (4 and 2), because the part holds a.size0 only as a missing-column marker. That is exactly the behaviour this PR fixes: the column now reads its default 0, so m is 1 — the same values the test already expects after CLEAR COLUMN. Updated the reference; both 05227_mutation_clears_shadowed_column_stream and 05229_column_shadowing_subcolumn_default pass locally on the merged tree.

Related: #117235

… on `ALTER`

A pair of a column `a.x` and a prefix column `a` was considered only when `a`
had the subcolumn `x`, and only the type of that subcolumn had to stay the same.
That missed two ways to move a deeper name such as `a.x.y` from one column to
the other:

- changing the dotted column itself (`MODIFY COLUMN a.x Tuple(y Dynamic)` next
  to a `JSON` column `a`), which introduces a regular subcolumn that takes
  precedence over the dynamic path of `a`;
- adding a prefix column whose subcolumn is under the dotted name without
  being the dotted name itself (`ADD COLUMN a Tuple(x.y UInt64)` next to a
  `JSON` column `a.x`).

Now a pair is detected when the prefix column has the subcolumn `x` or any
subcolumn under `x.`, all those subcolumns with their types must stay the
same, and when the prefix column can resolve names under `x`, the subcolumns
of the dotted column must stay the same as well.

Also mark `ProjectionDescription::providesColumn` as `[[nodiscard]]` for
clang-tidy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 7 commits November 17, 2026 19:51
…to its prefix column

When a prefix column (a `JSON` column `a`, or a `Tuple` column `a` with an element
`x.y`) can resolve names under the name of a column `a.x`, dropping or renaming
`a.x` while `a` stays moved `a.x` and the names of its subcolumns (`a.x.y`) to `a`,
while projections, skip indices and statistics kept values computed from the old
column. Such an `ALTER` is now refused; both columns can be dropped in one `ALTER`.
Dropping the marker column `a.size0` next to an `Array` column `a` stays allowed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `Nested` leaf

A column `a.x.y` of type `Array` is requested as the subcolumn `x.y` of a
`Nested` column `a`. When the part has another kind of column `a` (a `JSON`
column), `IMergeTreeReader::tryGetColumnInPart` accepted any stored column
with a longer prefix of the requested name as evidence that the leaf is in
the part. A stored column `a.x` thus stood in for a missing `a.x.y`, and the
path `x.y` of the `JSON` column `a` was read instead of the default of
`a.x.y`.

Now `getStorageAndSubcolumnNameInPart` also reports the name in the part of
the flattened leaf column (taking pending renames into account), and the leaf
counts as present only if the part stores that exact column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… shorter name

A part holds a `JSON` column `a` and a column `a.x`, but not `a.x.y`; reading
`a.x.y` gives its default rather than the path `x.y` of `a`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…refix` deterministic

The query sorted by the part name, so the order of the columns of the single
part was unspecified and the test failed under randomized settings. Sort by
the column name instead.

CI report: #118242

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…as deeper names

`resolves_deeper_names` in `checkAlterEligibility` looked only at the subcolumn
type and at the listed subcolumn names of the prefix column, so it missed names
that the prefix type generates dynamically: a `Map(String, ...)` column `a`
resolves `a.key_x.y` as the key `x.y`, although `key_x` is a plain `UInt64`.
Dropping or renaming `a.key_x`, or changing its type, then moved `a.key_x.y`
between the two columns while projections and the primary key kept the values
computed from the old source.

Now a name under the subcolumn is probed with `tryGetSubcolumnType`. Add `Map`
regressions for the drop/projection and the type change/key paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118242&sha=daff0bf4f225016aa3e09e8871714205737124d7&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20plan-based%2C%20s3%20storage%2C%20parallel%29 (04839_trivial_group_by_limit_aggregate_projection returns 10 9 instead of 10 0, and failed 77 of 247 reruns with the same randomized settings) and provide a fix in a separate PR. If the fix is already in progress, link it here. This PR only changes how column names resolve when a column is named like a subcolumn of another; the names in this test (k, v, count(), sum(v)) have no dotted prefix, so they resolve the same way as before. I could not reproduce it on x86 with a local parallel_replicas cluster and the same settings (100 concurrent runs), and it passed about 1700 times on master in the ParallelReplicas jobs over the last 30 days, so it may depend on ARM or the S3 storage.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the 04839_trivial_group_by_limit_aggregate_projection failure in the plan-based ParallelReplicas job; I'll follow up here with a fix PR (or the link to the in-progress one) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

This is not caused by this PR. It is #122607, the kept-keys cutoff of the trivial GROUP BY ... LIMIT under plan-based parallel replicas, and the fix in progress is #126139.

applyParallelReplicas clones the AggregatingStep, cutoff included, into the per-replica partial aggregation (applyParallelReplicas.cpp#L595). The remote replicas lose the cutoff when the plan is serialized (AggregatingStep.cpp#L1321), but the local replica runs the clone as is: it keeps the first 10 keys of its own share and drops its rows of every other key. A key that the initiator returns but the local replica dropped carries only the remote replicas' rows, hence 10 9. The aggregate projection does not change that: its pre-aggregated states are merged under the same cutoff.

It only shows when the remote replicas get a share of the marks. Locally the original test never got there (the remote queries were cancelled before reading in 40 of 40 runs), so it passed, which fits your x86 result. With the two inserts scaled to number % 1000003 over 2 x 2M rows (same table, projection and queries), the remote replicas read in every run. 3-replica default_parallel_replicas, plan-based profile, the failing run's randomized settings, debug builds of master 9c91e34:

Build Wrong results
master 20/30 (10 9, 10 8, ...)
master + the #126139 diff 0/30
master, parallel_replicas_plan_based = 0 0/10

#126139's own test 05401_parallel_replicas_plan_based_trivial_group_by_limit_aggregates gives the same 10 9 on master and 10 0 with the fix. 04839 needs no change.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118242&sha=dcf0d5b61acc8949bffc5abfd9dea91679e93863&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%205%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. In compact_part_subcolumns, the fill query INSERT INTO t_json_2 ... fails with Cannot reserve 7.12 GiB, not enough space (NOT_ENOUGH_SPACE) on both the left (master) and the right (PR) server. The runner had 185G free at the start, so the test's space estimate for this compact part looks wrong. This PR does not change inserts or space reservation.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

This is not caused by this PR. It is the disk-space window right after Populate, and the fix in progress is #131429 (mine, green, merges cleanly).

  • The estimate is the block's in-memory size, block.bytes() (MergeTreeDataWriter.cpp#L992), as for every insert: a 65,409-row block of t_json_2 carries 1000 paths of about 100 bytes per row, so 7.12 GiB. Three such blocks were being written at once, so each server needed about 21.4 GiB unreserved. Left server.log: Reserved 7.12 GiB ... having unreserved 21.40 GiB, then 14.24 GiB, then Could not reserve 7.12 GiB at 12:31:15 (right: 21.11, 14.24, then the same).
  • The 185G was measured before the datasets were downloaded (df -h at 12:06). The test started at 12:31:00, 2.5 minutes after Populate, while the hits_100m_single parts replaced by the rebuild's merges were still on disk as Outdated (old_parts_lifetime 480 s plus up to 300 s of cleanup thread sleep). They were removed 13 s (left, Removed 186 old parts) and 18 s (right, 190 parts) after the INSERT failed, and DiskAvailable_default went from 21.4 GiB to 70 GiB, then to about 99 GiB by 12:37.

#131429 sets old_parts_lifetime = 0 on the rebuilt table and waits until it has no Outdated parts before the tests start, so this INSERT would have had at least the 70 GiB measured after the cleanup, against the 21.4 GiB it needs.

alexey-milovidov and others added 3 commits November 22, 2026 23:39
…e's identity

A column of the table whose name is also the name of a subcolumn of another
column (`a.size0` next to an `Array` column `a`, `a.x` next to a `JSON` column
`a`) was still looked up in a part by the raw name in a few places:

- `can_serve_lazy_read` in `optimizeUseNormalProjections` accepted a projection
  that stores only `a` for a lazily read column `a.size0`. It now uses
  `ProjectionDescription::providesColumn`, as the check of the eagerly read
  columns does.
- `haveMutationsOfDynamicColumns` took a column `a.x` that the part does not
  hold for the path `x` of a `JSON` column `a`, which forced a rewrite of all
  columns of the part and disabled the coalescing of row mask updates.
- `MutationsInterpreter` took the old type of such a column from the subcolumn
  before it consulted the recorded missing column.
- `isSerializationDefinedSubcolumn` tried every split of the name; when the
  metadata resolves the name as a subcolumn, only the split through that parent
  counts now.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…names

On `INSERT`, a subcolumn required by the sorting key, the partition key, a skip
index, or the sign / version column of the engine was taken with
`Block::getSubcolumnByName`, which returns the subcolumn of the first column of
the block that offers one. Next to a `JSON` column `a` and a `Tuple` column
`a.x`, the subcolumn `a.x.y` was taken from the path `x.y` of `a`, while reads
and merges take it from `a.x`. A skip index over `toUInt64(a.x.y)` then held
the values of the `JSON` path and dropped granules that match (0 rows with
`use_skip_indexes = 1`, 1 row with 0), and an index over `a.x.y` of another
type failed the `INSERT` with `BAD_GET`.

`ColumnsDescription::getSubcolumnFromBlock` resolves the name as the table
does and extracts the subcolumn from that column of the block.

The test also covers two cases from the review that had no test in the current
tree: a projection computed from the recorded default of a missing column
stays usable (`force_optimize_projection`), and a skip index over a subcolumn
of a missing column returns the same result with and without the index.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…default-114588

Conflicts in `ReadFromMergeTree::getColumnSizesForPrewhere` and
`MergeTreeData::getColumnSizes`: master moved the sizing of the subcolumns
of the parts into `MergeTreeData::addColumnSizesOfParts` and
`IMergeTreeDataPart::getColumnAndSubcolumnSizes`, which resolve the names
with `tryGetColumn`. Both now take the columns of the table and resolve the
names with `tryGetColumnForTable`, so that a column of the table which
shadows a subcolumn of another column is still not taken for that subcolumn
in the parts that do not hold it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
alexey-milovidov and others added 2 commits November 23, 2026 10:10
…lso in projections, merges and mutations

Next to a `JSON` column `a` and a `Tuple` column `a.x`, the table resolves the
subcolumn `a.x.y` as the element `y` of `a.x`. The insert already computed the
sorting key and the skip indices from it, but three places still took the first
column of the block that offers such a subcolumn, which is the path `x.y` of `a`:

- `ProjectionDescription::calculateByQuery` filled the block of a normal
  projection with `Block::getColumnOrSubcolumnByName`, so the key of the
  projection was computed from the path, and
  `addSubcolumnsFromSortingKeyAndSkipIndicesExpression` then found the wrong
  column already in the block. A query answered by the projection missed rows
  and read them in the wrong order.
- `createSubcolumnsExtractionActions`, used by merges, mutations and
  `TTL ... GROUP BY` to compute the sorting key and the skip indices, so the
  primary index and the skip indices written by a merge dropped matching
  granules. It now takes the columns of the table and tries the column that
  the table gives the subcolumn first.
- `getColumnNameInStorage` in `MergeTask`, which chooses the columns to read as
  key columns in a merge.

Addresses the review:
#118242 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
`skip_empty_columns_on_insert` never omits a column with a `DEFAULT` expression,
so the columns `a.size0 DEFAULT 7`, `a.x DEFAULT 7` and `a.x DEFAULT tuple(7)`
were written by the inserts and the cases did not test a missing column.

The columns now have no default expression and each case asserts with
`system.parts_columns` that the part does not hold the column. Every mutation
(`MODIFY COLUMN`, `UPDATE`, `CLEAR COLUMN`, `MATERIALIZE COLUMN`) starts from a
new part without the column; the default expression that `MATERIALIZE COLUMN`
requires is added when the part already exists.

Addresses the review:
#118242 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed f27f71f and 6c917ed, addressing both open review threads:

  • A normal projection, merges, mutations and TTL ... GROUP BY now take a key subcolumn from the column that the table gives the name (a.x.y from a Tuple column a.x, not the path x.y of a JSON column a). New test: 05871_column_shadowing_subcolumn_keys_after_merge.
  • The fixtures of 05838_column_shadowing_subcolumn_lazy_read_and_mutations now use columns without a DEFAULT expression and assert that the parts do not hold them.

The only test failure on the previous head 26d3dd0, Performance Comparison (arm_release, master_head, 3/6) (report), is codecs_float_insert failing with Cannot reserve 8.48 MiB, not enough space on the runner. It is not caused by this PR: it is the same disk-space failure as on 2026-11-20, and its fix is still open in #131429.


for (auto [column_name, subcolumn_name] : Nested::getAllColumnAndSubcolumnPairs(required_column))
auto column_and_subcolumn_pairs = Nested::getAllColumnAndSubcolumnPairs(required_column);

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.

[Blocker] This exact-name / storage-parent rule still does not reach the DEFAULT / MATERIALIZED insert path.

createSubcolumnsExtractionActions only prefers the table's owner column when table_columns is passed, but AddingDefaultsTransform and InsertDependenciesBuilder still call it without metadata (src/Processors/Transforms/AddingDefaultsTransform.cpp:337, src/Interpreters/InsertDependenciesBuilder.cpp:699, src/Interpreters/InsertDependenciesBuilder.cpp:1876), and AddingDefaultsTransform::getColumnOfSubcolumn keeps the same shortest-prefix scan (src/Processors/Transforms/AddingDefaultsTransform.cpp:145).

With a table like:

CREATE TABLE t
(
    a JSON,
    `a.x` Tuple(y UInt64),
    m UInt64 MATERIALIZED toUInt64(`a.x.y`)
) ENGINE = MergeTree ORDER BY tuple();

INSERT INTO t (a, `a.x`) VALUES ('{"x":{"y":11}}', tuple(44));

the insert path still extracts a.x.y from a because Nested::getAllColumnAndSubcolumnPairs tries a before a.x, so m is materialized as 11 instead of 44. Since CREATE TABLE with this collision stays allowed, we still persist wrong computed values for a supported table shape.

Please thread table_columns through the default/materialized evaluation path as well, and switch getColumnOfSubcolumn to the table-aware resolution (ColumnsDescription::tryGetColumnOrSubcolumn(...)) instead of the first matching prefix.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Confirmed and fixed in 67bdeab. Before the change, d UInt64 DEFAULT toUInt64(a.x.y) and m UInt64 MATERIALIZED toUInt64(a.x.y) stored 11 (the path x.y of the JSON column a) on INSERT ... VALUES, INSERT ... SELECT, INSERT ... FORMAT JSONEachRow and on an insert through a materialized view.

  • AddingDefaultsTransform and both places in InsertDependenciesBuilder now pass the columns of the table to createSubcolumnsExtractionActions.
  • getColumnOfSubcolumn resolves the name with ColumnsDescription::tryGetColumnOrSubcolumn instead of the first matching prefix.

New test: 05872_column_shadowing_subcolumn_in_default_on_insert, covering these four insert paths.

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.

[Blocker] The storage-parent issue remains on 67bdeab83e1d when the insert omits the parent column. src/Interpreters/InsertDependenciesBuilder.cpp:1877 passes the original input block to extraction; at src/Interpreters/createSubcolumnsExtractionActions.cpp:48–50 the preferred parent is absent, so extraction continues through a and supplies the JSON path to the dependent defaults.

Reproduced with this head's Fast test binary:

CREATE TABLE t
(
    a JSON,
    `a.x` Tuple(y UInt64),
    d UInt64 DEFAULT toUInt64(`a.x.y`),
    m UInt64 MATERIALIZED toUInt64(`a.x.y`)
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (a) VALUES ('{"x":{"y":11}}');
SELECT `a.x.y`, d, m FROM t;
-- 0, 11, 11; expected 0, 0, 0

With a.x DEFAULT tuple(toUInt64(44)), the result is 44, 11, 11. The same mismatch reproduces with INSERT ... SELECT and an insert through a materialized view; the JSONEachRow path gives the correct values. Resolve and materialize the omitted parent's default before extracting its subcolumn for dependent expressions, and add an omitted-parent case to 05872.

alexey-milovidov and others added 2 commits November 23, 2026 12:55
The test lists the columns of a part from `system.parts_columns` to show that the part does not hold a column.
With the randomized MergeTree setting `enable_block_number_column` (or `enable_block_offset_column`), a mutated
part also lists `_block_number` (`_block_offset`), and the result differed from the reference in every
stateless job. The listing now skips the names that start with an underscore.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118242&sha=6c917ed30002f966bf4b50491578aa20f09bb4cc&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
#118242

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…` expression from the column that the table gives the name

On `INSERT`, `createSubcolumnsExtractionActions` was called without the columns of the table when it prepared
the subcolumns for the default expressions (`AddingDefaultsTransform` and both places in
`InsertDependenciesBuilder`), so it took the subcolumn from the first inserted column that offers it. Next to a
`JSON` column `a` and a `Tuple` column `a.x`, `m UInt64 MATERIALIZED toUInt64(`a.x.y`)` stored the path
`x.y` of `a` instead of the element `y` of `a.x`. The columns of the table are now passed in these places,
and `getColumnOfSubcolumn` in `AddingDefaultsTransform` resolves the name with
`ColumnsDescription::tryGetColumnOrSubcolumn` instead of the first matching prefix.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 522e079 and 67bdeab.

  • CI on 6c917ed was red only because of the test of this PR, 05838_column_shadowing_subcolumn_lazy_read_and_mutations (report): with the randomized MergeTree setting enable_block_number_column, a mutated part also lists _block_number in system.parts_columns. The listing now skips the names that start with an underscore. Reproduced locally with enable_block_number_column = 1, enable_block_offset_column = 1, and it passes after the change.
  • The open review thread about the DEFAULT / MATERIALIZED insert path is addressed in 67bdeab, with the new test 05872_column_shadowing_subcolumn_in_default_on_insert.

const Block & available_columns,
const Names & required_columns,
const ContextPtr & context,
const ColumnsDescription * table_columns = nullptr);

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.

[Blocker] Apply the storage-parent rule to constraint evaluation too.

Leaving this metadata argument optional keeps ConstraintsDescription::getExpressions on the old lookup (src/Storages/ConstraintsDescription.cpp:184 calls this helper without metadata). Consequently a CHECK over a regular subcolumn still checks another column's JSON path and accepts rows that violate the declared constraint.

Reproduced with the Fast test binary for 67bdeab83e1d:

CREATE TABLE t
(
    a JSON,
    `a.x` Tuple(y Dynamic),
    CONSTRAINT c CHECK toUInt64(`a.x.y`) = 44
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('{"x":{"y":44}}', tuple(11::UInt64));
-- Succeeds: the constraint checks the JSON value 44.
SELECT `a.x.y` FROM t;
-- 11: the stored value violates the constraint.

CREATE TABLE with this pair remains supported, so the ALTER rejection cannot protect this path. Have constraint extraction use the same resolved parent as table reads (the source column descriptions are available there), and cover both acceptance of a valid tuple value and rejection of an invalid one.

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

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

3 participants