Skip to content

Fix vertical merge nested default corruption - #100330

Open
germiBest wants to merge 70 commits into
ClickHouse:masterfrom
germiBest:fix-vertical-merge-nested-default-corruption
Open

germiBest wants to merge 70 commits into
ClickHouse:masterfrom
germiBest:fix-vertical-merge-nested-default-corruption

Conversation

@germiBest

@germiBest germiBest commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary


Vertical merge gathers columns one at a time. When a column has DEFAULT that references another column which is absent from all source parts and has no DEFAULT itself – that dependency is already expired and won't be in the block during evaluateMissingDefaults. Expression engine substitutes a typeless empty value for it, the resulting column gets wrong outer array dimensions, and this corrupts shared Nested offsets when written to the merged part.

This is challenge (1) from #91127. Fix extends existing column expiration logic to transitively expire columns whose DEFAULT depends on already-expired column. Since these columns were never present in any source part, read path was already computing them on-the-fly with full column context available – so expiring them during merge changes nothing for the end user.

Fixes #86123.

Changelog category (leave one):

  • Bug Fix

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

Fix silent data corruption during vertical merge when a Nested subcolumn added via ALTER TABLE ADD COLUMN has a DEFAULT expression that depends on another missing column without a default.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1c51a87]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR prevents shared Nested offsets from being corrupted when missing defaults are materialized during merges and mutations. The current implementation still changes stored engine control values and leaves TTL metadata stale. Two new blockers were reproduced with the exact PR-head Fast test binary, 1c51a8732422193e03cd5d43734ca5b217766ffa.

Findings

❌ Blockers

  • NestedDefaultsReconciliation.cpp:195: Stored engine control columns remain recomputable. A ReplacingMergeTree version column declared MATERIALIZED is recomputed before deduplication. In the reproduced case, SELECT FINAL chooses the newer row with [30], ['new'], but OPTIMIZE FINAL raises the older row's version from 1 to 2 and permanently keeps [10,20], ['',''] instead. Preserve stored engine control values as well as table keys; cover version, sign, and deletion-marker roles.
  • MergeTask.cpp:1147: Reconciliation invalidates projections/indexes but not inherited TTL bounds. With a TTL expression over length(n.b), reconciliation changes a row's expiration to 2000-01-01, while the finished part retains delete_ttl_info_min = delete_ttl_info_max = 2100-01-01. The expired row survives and the TTL scheduler has no due bound. Recalculate affected TTL metadata for merges and full mutation rewrites, including TTL inputs reached through recomputed MATERIALIZED columns.
  • MutationsInterpreter.cpp:1454 [dismissed by author -- https://github.com/Fix vertical merge nested default corruption #100330#discussion_r4562517347]: Partial materialization still leaves stored MATERIALIZED dependents inconsistent. The author explicitly leaves this unimplemented. Verified on the current binary: after materializing s MATERIALIZED length(n.b), then materializing n.b, row 1 stores n.b = ['',''], s = 1, and length(n.b) = 2. This remains a persisted correctness issue; no new inline comment or reopening of the author's resolved thread.
Tests
  • ⚠️ Add a regression comparing ReplacingMergeTree winners before and after reconciliation during a physical merge.
  • ⚠️ Add a regression that recalculates TTL metadata before merging, then verifies the resulting bounds or expiration when reconciliation changes the TTL input.
Final Verdict

Status: ❌ Block

Preserve stored engine control columns and refresh affected TTL metadata, with focused regression coverage. The acknowledged partial-mutation inconsistency also remains unresolved.

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Mar 22, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
…endent columns (test 02000 behaviour fix) . Update tests to validate behavior with multi-hop transitive dependencies in default values
@germiBest

germiBest commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Failing tests are not from my changes, https://github.com/ClickHouse/ClickHouse/actions/runs/23401354563/job/68075260001?pr=100330 is due to github or the runner is lagging to fetch repo. Kafka integration tests timing out (session-timeout: 7200.0 sec exceeded) because the Docker container was stuck after first test.

CI needs a rerun.

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
alexey-milovidov and others added 2 commits June 22, 2026 01:12
…iring

Address review feedback on transitive expiration of Nested subcolumns
during vertical merge.

The closure that transitively expires a Nested subcolumn when its
`DEFAULT` depends on an already-expired column compared the raw AST
identifiers returned by `collectIdentifierNames` against
`expired_columns`. But `expired_columns` holds physical storage column
names (e.g. `m`), while an identifier may name a subcolumn (e.g.
`m.keys`). A default such as `` `n.b` Array(String) DEFAULT m.keys ``
therefore did not match the expired `Map` column `m`, so `n.b` stayed on
the vertical materialization path and could write Nested offsets
inconsistent with its sibling `n.a`.

Resolve each identifier back to its storage column with
`ColumnsDescription::tryGetColumn` (with subcolumns) and
`getNameInStorage` before the lookup. Identifiers that are not columns at
all, such as lambda parameters, resolve to nothing and are ignored.

Add a regression to `04050_vertical_merge_nested_default_corruption`
where a Nested subcolumn's `DEFAULT` references a subcolumn of an expired
`Map` column, then forces a vertical merge via `OPTIMIZE TABLE ... FINAL`
and asserts the merge completes and the sibling `n.a` survives intact.

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

Copy link
Copy Markdown
Member

Pushed a follow-up commit (3ec2738) addressing the review feedback (the ❌ Block finding at MergeTask.cpp:660 and the corresponding inline thread).

What changed: the transitive-expiration closure compared raw AST identifiers from collectIdentifierNames against expired_columns, but expired_columns holds physical storage column names while an identifier can name a subcolumn. So a default like ``n.b Array(String) DEFAULT m.keys collected `m.keys`, did not match the expired `Map` column `m`, and left `n.b` on the vertical materialization path. The fix resolves each identifier back to its storage column via `ColumnsDescription::tryGetColumn(...).withSubcolumns()` + `getNameInStorage` before the lookup; identifiers that are not columns (e.g. lambda parameters) resolve to nothing and are ignored.

Test: added a regression to 04050_vertical_merge_nested_default_corruption where a Nested subcolumn's DEFAULT references a subcolumn (m.keys) of an expired Map, then forces a vertical merge via OPTIMIZE TABLE ... FINAL and asserts the merge completes and sibling n.a survives intact.

One note: the test deliberately does not SELECT n.b itself. A DEFAULT that references a subcolumn of a missing column (e.g. m.keys) currently fails on read with Not found column m.keys in block — but this reproduces even with merges disabled on a single freshly-written part, so it is a separate, pre-existing read-path limitation independent of the vertical-merge corruption fixed here.

I also verified on current master that the original issue still reproduces (the silent corruption now surfaces as a Logical error in PODArray::operator[] inside SerializationArray::serializeText when reading the merged Nested columns), and that this branch resolves it. Branch merged up to current master.

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
alexey-milovidov and others added 2 commits June 28, 2026 23:01
Address the AI review blocker on transitive expiration of Nested
subcolumns during vertical merge.

The closure that expires a Nested subcolumn when its `DEFAULT`
transitively depends on an already-expired column collected raw AST
identifiers via `collectIdentifierNames`. That has two gaps:

- False positive: `collectIdentifierNames` also collects lambda formal
  parameters, so a default like
  `arrayMap(x -> x + 1, n.a)` treated the lambda-local `x` as a
  dependency. If a physical column `x` was expired, `n.b` was wrongly
  expired even though the default only reads the present sibling `n.a`,
  turning a materialized-at-merge column into a recomputed-at-read one.
- False negative: an `ALIAS` column was never expanded to the physical
  columns it reads, so a default depending on an expired column through
  an alias was not expired and stayed on the corrupting
  vertical-materialization path.

Replace the raw identifier walk with `collectDefaultStorageDependencies`,
which reuses the same scope-aware analysis as default evaluation
(`RequiredSourceColumnsVisitor`, as in `evaluateMissingDefaults`): lambda
parameters are excluded, `ALIAS` columns are expanded recursively to
their physical source columns, and each source is resolved to its
storage column name (so a subcolumn such as `m.keys` resolves to the
`Map` column `m`).

Extend `04050_vertical_merge_nested_default_corruption` with the two edge
cases: a lambda parameter shadowing an expired column (the column must
stay materialized, asserted via `system.parts_columns`) and a `DEFAULT`
reaching an expired column only through an `ALIAS` (the column must be
expired so the merge does not corrupt the shared Nested offsets).

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

Copy link
Copy Markdown
Member

Pushed a follow-up commit (704ba91efc2) addressing the remaining ❌ Block finding at MergeTask.cpp and the corresponding inline thread.

What was still wrong: the transitive-expiration closure discovered a Nested subcolumn's DEFAULT dependencies with collectIdentifierNames, i.e. a raw AST identifier walk. That has two gaps:

  • False positive (lambda parameters). collectIdentifierNames collects lambda formal parameters. A default like `n.b` Array(UInt32) DEFAULT arrayMap(x -> x + 1, `n.a`) collected x; if a physical column x was expired, n.b was wrongly expired even though the default only reads the present sibling n.a — turning a materialized-at-merge column into a recomputed-at-read one.
  • False negative (aliases). An ALIAS column was never expanded to the physical columns it reads (getNameInStorage returns the alias's own name, which is never in expired_columns), so a default depending on an expired column through an alias was not expired and stayed on the corrupting vertical-materialization path.

Fix: replaced the raw walk with collectDefaultStorageDependencies, which uses the same scope-aware analysis as default evaluation (RequiredSourceColumnsVisitor, as in evaluateMissingDefaults): lambda parameters are excluded, ALIAS columns are expanded recursively to their physical source columns, and each source is resolved to its storage column name (so m.keys resolves to the Map column m).

Tests: extended 04050_vertical_merge_nested_default_corruption with the two edge cases the review asked for:

  • a lambda parameter shadowing an expired storage column while the default only depends on a present column — the column must stay materialized (asserted via system.parts_columns, which lists materialized columns but not expired ones);
  • a Nested default that reaches an expired physical column only through an ALIAS column — the column must be expired so the merge does not corrupt the shared Nested offsets and the sibling survives.

Verified locally that both new assertions pass with this change and fail on the previous identifier-walk logic (an expired column returns 0 from system.parts_columns vs 1 for a materialized one).

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
alexey-milovidov and others added 2 commits July 14, 2026 02:07
…ias subcolumn

`collectDefaultStorageDependencies` resolved each identifier read by a
Nested subcolumn's `DEFAULT` to its physical storage column via
`ColumnsDescription::tryGetColumn(...withSubcolumns())`, then expanded
`ALIAS` columns. But `ColumnsDescription` does not register subcolumns of
`ALIAS` columns (`ColumnsDescription::addSubcolumns` skips
`ColumnDefaultKind::Alias`), so an identifier like `m_alias.keys` with
`m_alias ALIAS m` did not resolve and was silently dropped. As a result a
default such as `` `n.b` Array(String) DEFAULT m_alias.keys `` never
expanded through the alias to the physical `Map` column `m`, so `n.b` was
not expired and vertical merge could still materialize the missing Nested
subcolumn against the expired `m`, corrupting the shared Nested offsets of
the present sibling `n.a`.

When the identifier does not resolve directly, fall back to its prefix
(`m_alias`) via `Nested::splitName` and let the existing alias-expansion
path recurse into the alias expression to reach the physical dependency.

Extended `04050_vertical_merge_nested_default_corruption` with a regression
where a Nested subcolumn's `DEFAULT` reads a subcolumn of an alias column
(`m_alias.keys`, `m_alias ALIAS m`) whose underlying `Map` column `m` is
expired, asserting the merge completes into a single part with the sibling
`n.a` intact.

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

Copy link
Copy Markdown
Member

Pushed a follow-up commit (e43665a4ed4, on top of a merge with the latest master) addressing the remaining ❌ Block finding at MergeTask.cpp (alias-subcolumn dependencies) and the corresponding inline thread.

What was still wrong: collectDefaultStorageDependencies resolved each identifier a Nested subcolumn's DEFAULT reads to its physical storage column via ColumnsDescription::tryGetColumn(...withSubcolumns()) and then expanded ALIAS columns. But ColumnsDescription does not register subcolumns of ALIAS columns — ColumnsDescription::addSubcolumns skips ColumnDefaultKind::Alias. So an identifier such as m_alias.keys with m_alias ALIAS m did not resolve and was silently dropped: a default like ``n.b Array(String) DEFAULT m_alias.keys never expanded through the alias to the physical `Map` column `m`, `n.b` was not expired, and vertical merge could still materialize the missing Nested subcolumn against the expired `m`, corrupting the shared Nested offsets of the sibling `n.a`.

Fix: when the full identifier does not resolve directly, fall back to its prefix via Nested::splitName (m_alias.keys → m_alias) and let the existing alias-expansion path recurse into the alias expression, so the physical dependency m is reached. Over-approximation here is safe: an extra dependency only moves a column from materialize-at-merge to recompute-at-read, which always has full context.

Test: extended 04050_vertical_merge_nested_default_corruption with the alias-subcolumn case (``n.b DEFAULT m_alias.keys, `m_alias ALIAS m`, `m` expired). Verified locally that `n.b` is expired after the merge (0 rows in `system.parts_columns`, i.e. the new branch is exercised) and the sibling `n.a` survives intact in a single part.

Also merged the latest master (the branch was ~16 days / 92k commits behind) and rebuilt clickhouse cleanly.

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
alexey-milovidov and others added 3 commits July 21, 2026 21:20
…sure

Two remaining correctness holes in `collectDefaultStorageDependencies`
flagged by review on `MergeTask.cpp`:

- The alias-subcolumn fallback only stripped the first dotted segment, so a
  legal quoted alias name that itself contains dots (e.g. `` `x.y` ALIAS m ``
  referenced as `` `x.y`.keys ``) was reduced to `x` and never expanded,
  dropping the dependency on the expired physical column. Replaced with
  longest-existing-prefix resolution over the actual column names in
  `resolveDefaultDependencyToStorage`.

- The closure only inlined `ALIAS` intermediates. A missing ordinary
  `DEFAULT`/`MATERIALIZED` column that is itself recomputed during the merge
  never propagated its own dependencies, so a chain such as `tmp DEFAULT
  m.keys`, `` `n.b` DEFAULT tmp `` left `` `n.b` `` on the vertical
  materialization path when `m` was absent from all source parts. Now
  dependencies of physical columns absent from every source part are followed
  transitively. Over-approximating is safe: an extra dependency only moves a
  column from materialize-at-merge to recompute-at-read.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two new cases in `04050_vertical_merge_nested_default_corruption`:

- A Nested subcolumn `` `n.b` DEFAULT `x.y`.keys `` where `` `x.y` ALIAS m ``
  is a legal quoted alias name that itself contains a dot. Resolving the
  identifier requires finding the longest existing column-name prefix, so the
  alias is expanded to the expired physical `m` and `` `n.b` `` is expired.

- A chain `tmp DEFAULT arrayMap(v -> toString(v), m)`, `` `n.b` DEFAULT tmp ``
  through a missing ordinary (non-`ALIAS`) default-bearing intermediate `tmp`,
  with `m` expired. The dependency closure follows the recomputed `tmp` down to
  `m`, so `` `n.b` `` is expired and the merge does not corrupt the shared
  Nested offsets of the sibling `` `n.a` ``.

Both assert the merge completes into a single part with the sibling intact.
Verified against the built binary.

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

Copy link
Copy Markdown
Member

Addressed both remaining AI-review findings on the merge-time Nested-default dependency closure in src/Storages/MergeTree/MergeTask.cpp (ebfd4fcc066, on top of a fresh master merge):

  1. Alias names containing dots. The one-segment Nested::splitName fallback is replaced by resolveDefaultDependencyToStorage, which resolves a subcolumn identifier to the longest existing column name that is a dotted prefix of it (iterating over the real column names). A dependency like `x.y`.keys with `x.y` ALIAS m now resolves to `x.y` (not x) and is expanded to the physical m.

  2. Transitive closure through non-ALIAS intermediates. collectDefaultStorageDependencies now follows dependencies through any physical DEFAULT/MATERIALIZED column that is absent from every source part (recomputed during the merge), so a chain such as tmp DEFAULT …m…, `n.b` DEFAULT tmp with m expired now expires `n.b`. Columns present in the parts are read as stored and not followed. Over-approximating is safe: an extra dependency only moves a column from materialize-at-merge to recompute-at-read.

Added two regression cases to 04050_vertical_merge_nested_default_corruption (t_nested_alias_dotted, t_nested_default_chain), each of which stays on the corrupting vertical-materialization path under the old logic. Both, and the full test, pass against a locally built binary.

@alexey-milovidov alexey-milovidov removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Oct 23, 2026
alexey-milovidov and others added 2 commits October 28, 2026 23:10
# Conflicts:
#	src/Storages/MergeTree/MergeTask.cpp
…fix `TTL GROUP BY`

- `IMergeTreeReader::evaluateMissingDefaults`: when the reconciliation with the
  shared `Nested` offsets changes a missing column, fix it to the reconciled
  value and evaluate the defaults again, so that the defaults computed from it
  (e.g. `MATERIALIZED length(n.b)`) see the reconciled value.
- `MergeTask`: in a vertical merge, read such a dependent column in the same
  step as the `Nested` subcolumn it is computed from, when both are missing
  from some source part, because the reconciliation needs the subcolumn to be
  requested.
- `TTL GROUP BY` aggregates every column of the merged block, and its keys,
  aggregate arguments and `SET` expressions do not name storage columns
  (`sum(v)`), so treat all storage columns as required by it instead of
  resolving those names, which threw `BAD_ARGUMENTS`.
- `TTLTransform`: set up `TTLAggregationAlgorithm` with the output header, which
  includes the expired columns added to the block before the algorithms run.
  Otherwise a merge of a table with `TTL GROUP BY` and a column absent from all
  parts threw `NOT_FOUND_COLUMN_IN_BLOCK` (this also happens on master).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 28, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 3 commits November 5, 2026 08:15
# Conflicts:
#	src/Processors/Transforms/TTLTransform.cpp
#	src/Processors/Transforms/TTLTransform.h
#	src/Storages/MergeTree/MergeTask.cpp
…of intermediates

- `IMergeTreeReader::evaluateMissingDefaults`: after a round of reconciliation with the
  shared `Nested` offsets, drop and re-evaluate only the evaluated defaults that depend on
  the columns fixed in that round, instead of re-evaluating every default from scratch.
  A non-deterministic prerequisite (`r DEFAULT rand64()`) is then not evaluated twice, so
  it keeps agreeing with the columns fixed from its first value (`n.b MATERIALIZED [r]`).
- The dependency walk resolves a required name that is a subcolumn (`tmp.size0`) to its
  column before following that column's default, so a dependent reached through a
  subcolumn of an intermediate (`n.c DEFAULT arrayWithConstant(tmp.size0, 'z')`,
  `tmp DEFAULT n.b`) is fixed only after it is recomputed from the reconciled value.
- Fix the `performance-move-const-arg` clang-tidy error reported by `Build (arm_tidy, 2/4)`.

Regression test: `05508_merge_nested_default_reconcile_retry`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100330&sha=latest&name_0=PR&name_1=Build%20(arm_tidy%2C%202%2F4)
ClickHouse#100330

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A mutation may read a missing `Nested` subcolumn only to build something derived from it
(a projection, a skip index, a `MATERIALIZED` column) and leave the subcolumn itself
missing in the mutated part. Reconciling it with the shared offsets made the derived data
disagree with ordinary reads of the part, which still evaluate the default as is. Only
merges, which write every column they read, reconcile now; mutations read the defaults
like a query does. Covered by `05508_merge_nested_default_reconcile_retry`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits November 13, 2026 08:54
`05508_merge_nested_default_reconcile_retry` failed in every CI run with
the randomized `min_bytes_for_full_part_storage`: a mutation of a part with
packed storage (as of a `Compact` part) rewrites every column instead of
hardlinking the untouched ones, so `MATERIALIZE PROJECTION` stored the
missing `n.b` evaluated from its default as is (`['x']`) next to the shared
offsets of `n.a` (two elements), and the part could not be read back:
`Cannot read all array values: read just 1 of 2`.

Such a mutation now reads with the reconciliation, as a merge does
(`MergeTreeSequentialSourceType::MutationOfAllColumns`, decided with the
same `rewritesAllPartColumns` predicate that selects
`MutateAllPartColumnsTask`). Mutations that hardlink the untouched columns
still read the defaults as a query does.

The two cases of the test whose results depend on the part storage pin
`min_bytes_for_full_part_storage = 0`; the packed storage is covered by a
new test.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100330&sha=471e62b5ce9a8944ddb667874acacbb73204843e&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
PR: ClickHouse#100330

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

A merge may reconcile a missing `Nested` subcolumn with the shared offsets
of a source part, which changes the value its default produces. Data derived
from the value as is before the merge then disagreed with the merged part:

- A projection materialized before the merge was merged with the old
  values. Now a projection that reads such a column (directly or through
  a default computed from it) is rebuilt from the merged part instead of
  merged (`getNestedColumnsReconciledInSomePart`).
- A stored `MATERIALIZED` dependent (e.g. `length(n.b)` materialized by
  `MATERIALIZE COLUMN`) kept its stored value. Now a stored deterministic
  `MATERIALIZED` column read by the same step is computed again from the
  reconciled value (`isDeterministicDefaultExpression`), and the vertical
  merge reads it in the same step as its dependency even where it is stored.

Covered by `05628_merge_nested_default_reconcile_stored_dependents` for
both merge algorithms and both part storages.

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

Copy link
Copy Markdown
Member

🕵 Merged master and pushed two commits:

  • af230cf fixes the failure of 05508_merge_nested_default_reconcile_retry in every stateless job. CI minimized the cause to the randomized min_bytes_for_full_part_storage. A mutation of a part with packed storage rewrites every column, so MATERIALIZE PROJECTION stored n.b without reconciling it and the part became unreadable (Cannot read all array values: read just 1 of 2). Mutations that rewrite the whole part now reconcile the same way merges do.
  • 2c9e830 addresses both review threads: projections whose inputs may be reconciled are rebuilt instead of merged, and stored deterministic MATERIALIZED dependents are recomputed. The new test is 05628_merge_nested_default_reconcile_stored_dependents.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
alexey-milovidov and others added 4 commits November 22, 2026 07:13
Conflicts:
- `TTLTransform.cpp`: master moved the construction of the expired columns' defaults before the new `apply_ttl` early return; the dependency ordering of the expired columns from this branch moved there with it, because the fill of the expired columns runs even when TTL is not applied.
- `MutateTask.cpp`: kept both the `setRewritesAllPartColumns` call and master's `recalculate_ttl_only` guard for the updated header.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…s between merges and mutations

The helpers that decide what a reconciled `Nested` default invalidates move from `MergeTask.cpp` to `NestedDefaultsReconciliation`, so that merges and mutations use the same rules:

- A stored `MATERIALIZED` column is recomputed only if `isStoredMaterializedColumnRecomputable` allows it. It excludes the columns of the partition, sorting and primary keys, because a new value would not move the row, and checks determinism on the expression with the `ALIAS` columns expanded, so `length(n.b) + r` with `r ALIAS rand64()` keeps its stored value.
- A merge rebuilds the text indexes instead of merging their segments when one of them reads a column the merge may reconcile.
- `MutateAllPartColumnsTask` rebuilds the projections and skip indexes that read such a column instead of hardlinking them.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…n with the shared offsets

`MATERIALIZE COLUMN` evaluates the default expression in the mutation pipeline, not in the reader, so it wrote a value with other array sizes over the offsets the subcolumn shares with its siblings, which a mutation of some columns does not rewrite. The expression now keeps the evaluated value where its size agrees with a sibling the part stores and degrades to the type-default values of that size elsewhere, as a merge does.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ciled `Nested` defaults

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
…a mutation writes

`MATERIALIZE INDEX` on a wide part records the columns its index reads that the part does not store: it adds a `READ_COLUMN` command for each, so the mutation writes the column from its default expression while hardlinking the siblings. For an array subcolumn of a `Nested` structure this overwrote the shared offsets, the same way `MATERIALIZE COLUMN` did. The stage now uses the same expression as `MATERIALIZE COLUMN`, moved to `reconcileWithStoredNestedSibling`. The values read from a patch part are left as they are.

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

Copy link
Copy Markdown
Member

🕵 Merged master and addressed the five review threads. Head is 67c3e72.

Merge. Two conflicts. In TTLTransform.cpp, master moved the construction of the expired columns' defaults before the new apply_ttl early return; this branch's dependency ordering of the expired columns moved there with it. In MutateTask.cpp both sides are kept.

Review threads (each replied to and resolved):

  • Stored partition, sorting and primary key columns are no longer recomputed.
  • Determinism of a stored MATERIALIZED column is checked with the ALIAS columns expanded.
  • A merge rebuilds text indexes that read a reconciled column instead of merging their segments.
  • A mutation that rewrites the whole part rebuilds the projections and skip indexes that read a reconciled column instead of hardlinking them. The rules are shared with merges in the new NestedDefaultsReconciliation.
  • MATERIALIZE COLUMN of a missing Nested subcolumn keeps the shared offsets. The same fix covers MATERIALIZE INDEX, which writes the missing columns its index reads; I found that path while testing.

Not done: a stored MATERIALIZED column that reads the subcolumn is not recomputed by MATERIALIZE COLUMN or MATERIALIZE INDEX when they change its value.

Tests. New 05843_merge_nested_default_reconcile_keys_indexes_mutations with the reviewer's reproductions plus a sorting-key and a MATERIALIZE INDEX case. It and the seven earlier tests of this PR match their references under clickhouse local with a build of this head. The previous CI run had no test failures; its only red was the unresolved-threads check.

…t a merge recomputes

A vertical merge moved a recomputed stored column and its reconciled `Nested` input into the horizontal read step, but left the other inputs of its expression to be gathered separately. The reader does not inject the inputs of a column the part stores, so the recomputation replaced them by defaults and overwrote the stored value. `MergeTask` now puts the whole transitive input closure into the same step, and the reader keeps the stored value when an input the part stores is not in the block.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
if (!column_default || column_default->kind != ColumnDefaultKind::Materialized || !column_default->expression)
return false;

if (metadata.getStorageColumnsRequiredForKeys().contains(column_name))

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] Preserve stored engine control columns when recomputing dependents

getStorageColumnsRequiredForKeys excludes the partition, sorting, and primary keys, but a ReplacingMergeTree version column can also be MATERIALIZED. Recomputing that stored value before deduplication changes which row survives the merge.

Reproduced with the Fast test binary for 1c51a8732422:

SET optimize_functions_to_subcolumns = 0;
CREATE TABLE t (id UInt32, ver UInt64 MATERIALIZED id, `n.a` Array(UInt32))
ENGINE = ReplacingMergeTree(ver) ORDER BY id
SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0,
    max_bytes_to_merge_at_max_space_in_pool = 1, enable_vertical_merge_algorithm = 0;
INSERT INTO t (id, `n.a`) VALUES (1, [10,20]);
ALTER TABLE t ADD COLUMN `n.b` Array(String) DEFAULT ['x'];
ALTER TABLE t MODIFY COLUMN ver UInt64 MATERIALIZED length(`n.b`);
INSERT INTO t (id, `n.a`, `n.b`) VALUES (1, [30], ['new']);
SELECT id, ver, `n.a`, `n.b` FROM t FINAL;
OPTIMIZE TABLE t FINAL;
SELECT id, ver, `n.a`, `n.b` FROM t;

Before the merge, SELECT FINAL returns 1, 1, [30], ['new']. After OPTIMIZE FINAL, the surviving row is 1, 2, [10,20], ['','']: reconciliation raises the older row's version from 1 to 2, permanently discarding the newer row.

Please exclude stored engine control columns from this recomputation too, checking the version, sign, and deletion-marker roles across the relevant engines. Add a regression comparing the winner before and after a physical merge.

/// recompute the stored `MATERIALIZED` columns that read it. The segments of a text index over
/// such a column were built from the values before the reconciliation, so the index is built
/// from the values written to the merged part instead of merging those segments.
if (!global_ctx->rebuild_text_indexes && (*global_ctx->data_settings)[MergeTreeSetting::share_nested_offsets])

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] Refresh TTL metadata when reconciliation changes its inputs

The reconciliation invalidation now covers projections and text indexes, but the merge still inherits the source parts' ttl_infos and decides whether to run TTL from those old bounds. Reconciliation can change a TTL expression's result, so the finished part can retain bounds that no longer describe its rows.

Reproduced with the Fast test binary for 1c51a8732422, without any dependent MATERIALIZED column:

SET optimize_functions_to_subcolumns = 0;
SET materialize_ttl_after_modify = 0;
CREATE TABLE t (id UInt32, `n.a` Array(UInt32)) ENGINE = MergeTree ORDER BY id
SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0,
    max_bytes_to_merge_at_max_space_in_pool = 1, enable_vertical_merge_algorithm = 0;
INSERT INTO t VALUES (1, [10,20]), (2, [30]);
ALTER TABLE t ADD COLUMN `n.b` Array(String) DEFAULT ['x'];
ALTER TABLE t MODIFY TTL if(length(`n.b`) = 1,
    toDateTime('2100-01-01 00:00:00'), toDateTime('2000-01-01 00:00:00'));
ALTER TABLE t MODIFY SETTING materialize_ttl_recalculate_only = 1;
ALTER TABLE t MATERIALIZE TTL SETTINGS mutations_sync = 2;
OPTIMIZE TABLE t FINAL;
SELECT id, `n.b` FROM t ORDER BY id;
SELECT delete_ttl_info_min, delete_ttl_info_max
FROM system.parts WHERE table = 't' AND active;

Row 1 is now stored with n.b = ['',''], making its expiration 2000-01-01, yet both TTL bounds remain 2100-01-01. The row survives and the normal TTL scheduler has no due expiration to act on. The same mismatch reproduces when the TTL reads a stored MATERIALIZED timestamp that reconciliation recomputes.

Please invalidate/recalculate affected TTL metadata alongside the other derived data, in both merge and full mutation writers, and add a focused regression for a TTL input changed by reconciliation.

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-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Vertical merge of Nested arrays corrupts data

5 participants