Skip to content

Make ALTER MODIFY COLUMN on named Tuple metadata-only when adding subfields - #107305

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
amosbird:metadata-only-tuple-add-subfield
Aug 14, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
amosbird:metadata-only-tuple-add-subfield

Conversation

@amosbird

@amosbird amosbird commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator

ALTER TABLE ... MODIFY COLUMN <col> Tuple(...) on a named Tuple that only adds new subfields is now metadata-only (no mutation). Gated behind SET allow_metadata_only_named_tuple_alter = 1 (default false).

Subfield additions through Array/Map/nested Tuple wrappers are also handled. Nullable(Tuple(...)) is blocked (null map incompatibility). Removing/renaming subfields or changing types still triggers a mutation.

Key/index/projection guards reject the metadata-only path when primary.idx or skip-index bytes would become invalid (whole tuple in key, or subcolumn whose type changes). Subcolumn references with unchanged types (e.g. ORDER BY t.a when only t.c is added) are allowed.

Changelog category (leave one):

  • Improvement

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

ALTER TABLE ... MODIFY COLUMN <col> Tuple(...) on a named Tuple is now metadata-only when only adding subfields, matching the speed of top-level ADD COLUMN. Gated behind SET allow_metadata_only_named_tuple_alter = 1.

Documentation entry for user-facing changes

  • Documentation is not required (behavioral improvement; semantics unchanged)

Version info

  • Merged into: 26.8.1.1430 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [77a7fe6]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6874) FAIL cidb IGNORED
BuzzHouse (arm_asan_ubsan) FAIL
Logical error: Context has expired (STID: 1805-460a) FAIL cidb IGNORED

AI Review

Summary

This PR adds a lazy metadata-only ALTER ... MODIFY COLUMN path for named Tuple subfield additions behind allow_metadata_only_named_tuple_alter and routes it through the existing MergeTree lazy-conversion checks. The split between byte-identical and lazy conversions is a good direction, but the current guard set still misses stale-projection cases and some of the new remediation guidance points users at unsafe mutation paths, so I would not merge it yet.

PR Metadata
  • Changelog category: Improvement matches the change.
  • Changelog entry is required and otherwise specific enough, but both the description and the changelog entry mention a setting that does not exist: allow_experimental_metadata_only_named_tuple_alter. Replace it with allow_metadata_only_named_tuple_alter.
  • Exact replacement text: `ALTER TABLE ... MODIFY COLUMN <col> Tuple(...)` on a named `Tuple` is now metadata-only when only adding subfields, matching the speed of top-level `ADD COLUMN`. Gated behind `SET allow_metadata_only_named_tuple_alter = 1`.
Missing context / blind spots
  • ⚠️ Praktika only exposed the Build profile diff report for this run; I did not have a Stateless tests / integration report confirming the new 04319_* coverage on CI. A passing runtime test report would close that gap.
Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:5706-5713] The lazy-path rejection for stored MATERIALIZED columns still tells users to disable the setting and rerun as a full mutation, but the fallback READ_COLUMN mutation path never registers MATERIALIZED dependents for recomputation. Following the suggested workaround rewrites t and hardlinks stale bytes for the dependent stored column. Suggested fix: either stop advertising that fallback here and require dropping/recreating the stored column, or teach the READ_COLUMN path to enqueue dependent MATERIALIZED columns before re-enabling that advice.
  • [src/Storages/MergeTree/MergeTreeData.cpp:5740-5769] The projection guard only looks at projection sort keys and WHERE filters. A projection that stores the changed tuple in its output block but sorts by something else, for example PROJECTION p (SELECT t ORDER BY id), still stays metadata-only even though the existing projection part serializes t with the old tuple shape. Reads from that projection will then deserialize stale bytes as the new type. Suggested fix: reject lazy tuple alters whenever any persisted projection output column under that projection changes type, not only when the sort key or WHERE uses the changed subcolumn.
  • [dismissed by author -- https://github.com/Make ALTER MODIFY COLUMN on named Tuple metadata-only when adding subfields #107305#discussion_r3771567679] [src/Storages/MergeTree/MergeTreeData.cpp:5730-5737] The skip-index diagnostic still promises that disabling the metadata-only setting will make a full mutation rebuild the index, but MutationsInterpreter rebuilds READ_COLUMN indices only when index.expression->getRequiredColumns() contains command.column_name exactly. For INDEX idx t.sub ..., disabling the setting still leaves skp_idx_* serialized with the old tuple shape. Suggested fix: either stop advertising the fallback for dotted-subcolumn indices, or make READ_COLUMN t rebuild/drop indices whose required columns are subcolumns under t.

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeData.cpp:5699-5714] The MATERIALIZED-column loop still walks only old_columns_desc. Safe combined alters like MODIFY COLUMN t ... , DROP COLUMN m or MODIFY COLUMN m REMOVE MATERIALIZED are therefore rejected even though the offending stored column does not survive in the final metadata. Suggested fix: gate this check on the final metadata the same way dropped indices and dropped projections are already skipped.
  • [src/Storages/MergeTree/MergeTreeData.cpp:5786-5814] The TTL guard has the same problem: it only inspects TTLs from old_metadata, so REMOVE TTL or per-column REMOVE TTL in the same ALTER is still rejected even though no stale ttl_infos remain after the ALTER finishes. Suggested fix: only reject TTL definitions that survive into the final metadata, or explicitly skip TTLs removed by this ALTER.
  • [dismissed by author -- https://github.com/Make ALTER MODIFY COLUMN on named Tuple metadata-only when adding subfields #107305#discussion_r3643633894] [src/Storages/MergeTree/MergeTreeData.cpp:5745-5759] The same projection gap still leaves the aliased-subcolumn case unguarded: ADD PROJECTION p (SELECT t.sub AS s ORDER BY s) is allowed because the stored projection column is named s, not t.sub, and the current check never looks at persisted projection outputs or projection.required_columns. That still leaves old projection parts storing Tuple(x) while the refreshed projection metadata expects Tuple(x, y). Suggested fix: the projection-output check above should use the persisted projection columns / required source columns, not only the projection key and filter expressions.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 101/128 (78.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 12, 2026
Comment thread src/Storages/AlterCommands.cpp Resolved
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 12, 2026
Run key, index, and projection safety checks for any `MODIFY_COLUMN`
that changes the column's type, regardless of whether the change is
metadata-only or requires a mutation.

Previously these checks were gated behind `isRequireMutationStage`, so
metadata-only conversions (e.g. adding a subfield to a named `Tuple`
whose subcolumn appears in `ORDER BY`) bypassed them, leaving stale
`primary.idx` / partition key bytes that no longer match the new tuple
arity. This was the blocking AI review finding on ClickHouse#107305.

Add regression tests covering:
- a subcolumn of the modified Tuple appearing in `ORDER BY`
- a subcolumn appearing in `PARTITION BY`
- the whole Tuple column appearing in `ORDER BY` (`primary.idx`
  arity would mismatch — caught by `isSafeForKeyConversion`)
- sanity: a Tuple not in any key is still metadata-only ALTER-able
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 13, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 13, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 13, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 13, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Jun 14, 2026
…ERT and merge

When all values of a named-Tuple subfield in a part are type-defaults, the
writer omits that subfield's stream files and narrows the part's columns.txt
Tuple type so it no longer mentions the subfield. Reads see the narrowed
Tuple type and use `CAST(narrowed_tuple, full_tuple)` to materialize defaults,
relying on the metadata-only ALTER work in ClickHouse#107305.

This optimization is most useful for `PARTITION BY` schemes where different
partitions populate different subsets of a wide schema's subfields: the
on-disk part keeps only the substreams whose subfield actually appears in
that partition.

Approach

- Reuse the existing whole-column pruning path
  (`IMergedBlockOutputStream::removeEmptyColumnsFromPart` consuming
  `new_data_part->expired_columns`).
- Extend that path to accept dotted subfield names (`data.c2s.gold`) and
  narrow the column's Tuple type via the new
  `narrowDataTypeByExpiredSubstreams` helper in `DataTypes/Utils`.
- After the prune pass, keep `columns_substreams.txt` consistent with the
  on-disk files via the new `ColumnsSubstreams::removeSubstreams` helper.
- Preserve each kept subfield's `SerializationInfo` (its sparse / default
  kind and per-element `num_rows` / `num_defaults`) when narrowing the
  enclosing Tuple, via the new `narrowSerializationInfo` helper.
- INSERT: `MergeTreeDataWriter` traverses each named-Tuple column with the
  new `IColumn::hasOnlyTypeDefaults` to spot all-default subtrees and
  contributes their dotted paths to `expired_columns`.
- Merge (Sub-case A): `MergeTask::prepare` computes the union of leaf
  substreams across all source parts and marks any leaf absent from every
  source as expired in the merged part. This is monotonic: a merged part
  never re-materializes default values for a subfield that was consistently
  pruned in the inputs.

Why top-level all-default columns are intentionally NOT pruned

If we erased a top-level Tuple column whose value is entirely default, the
part would semantically lose that column ("missing column" — equivalent to a
column that was added by a later `ALTER ADD COLUMN`). A subsequent
`ALTER MODIFY COLUMN ... DEFAULT <new_expr>` would then re-materialize the
column with the NEW default expression on read, retroactively changing
historical data. That is exactly the quirk tracked by ClickHouse#92475
(`ALTER MODIFY ... DEFAULT` rewriting old parts).

This PR sidesteps the problem by leaving top-level columns alone: subfield
pruning only narrows the Tuple type of a column that still exists. The
materialized 0 / '' / `[]` bytes of the kept columns pin the part's
semantics; future `ALTER MODIFY ... DEFAULT` changes apply only to parts
written after the ALTER, matching today's whole-column behavior.

Named-Tuple subfields have no per-subfield DEFAULT expression syntax
(`Tuple(a Int64 DEFAULT 5)` is not a valid type), so pruning a subfield can
only ever fall back to the language's type-default (0 / '' / NULL). This is
also why the optimization composes cleanly with the per-column DEFAULT RFC
in ClickHouse#92475 (comment 4334850399): subfield pruning operates entirely below
the column boundary the RFC will redefine.

What is NOT touched

- Compact parts: early return preserved; pruning only fires for Wide parts.
- Patch parts: skipped (mirrors the existing whole-column behavior).
- Mutate path: not pruned; mutations preserve the existing schema.
- Top-level all-default columns: see note above.
- `PR ClickHouse#98472`'s column-level `skip_empty_columns_on_insert` mechanism: only
  the `hasOnlyTypeDefaults` column primitives are lifted, none of its
  signalling layer (no `WITH_SKIPPED_COLUMNS` serialization version, no
  JSON `skipped_columns` field, no DEFAULT-expression interaction).

Gate

- `enable_tuple_subfield_pruning` (default true) gates the entire feature in
  `MergeTreeSettings`. The history entry is recorded under 26.6.

Compatibility

- No on-disk format change: parts written by this PR are readable by any
  server that has the metadata-only-ALTER work in ClickHouse#107305.

Tests

- `tests/queries/0_stateless/04320_tuple_subfield_pruning.sql` exercises 36
  cases: flat / nested Tuple, Nullable wrap, Array(Tuple) (all-empty and
  non-empty), Map(K, Tuple), `LowCardinality(String)`, deep customer-like
  schema, `PARTITION BY` per-partition narrowing, setting OFF, Compact-part
  preservation, two-part merge variants (both pruned, one pruned, different
  subfields pruned), `INSERT SELECT` / async INSERT / materialized view,
  `ReplacingMergeTree` merge, vertical merge, `LWD`, `ALTER MODIFY ADD
  subfield + INSERT`, `ALTER UPDATE` mutation on narrowed part,
  multi-granule part, `DETACH / ATTACH PARTITION`, top-level column with a
  dot in its name, force-sparse + pruning interaction, subcolumn reads of
  pruned subfields, `CHECK TABLE` on a pruned part, and `bytes_on_disk`
  comparison.

### Documentation entry for user-facing changes

- [x] Documentation is not required.

### Changelog category (leave one):

- Improvement

### Changelog entry:

Automatically prune named-Tuple subfields whose values in a part are
entirely type-defaults: the writer omits their stream files and records a
narrowed Tuple type in `columns.txt`; reads materialize defaults via
`CAST`. Gated by the new MergeTree-level setting
`enable_tuple_subfield_pruning` (default on).
@EmeraldShift

Copy link
Copy Markdown
Contributor

+1 -- We just discovered this is very valuable for e.g. continuous profiling data, because we store the call stack like Array(Tuple(function_name String, address UInt64, ...)) and adding more metadata to each frame is very painful.

@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch from 55b2f40 to aa69de1 Compare June 27, 2026 09:05
@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch 2 times, most recently from 5e31542 to 2a4d8c2 Compare August 13, 2026 06:16
@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch from 2a4d8c2 to 269d4e9 Compare August 13, 2026 07:15
@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch 2 times, most recently from b515cbf to f1cff93 Compare August 13, 2026 08:14
if (column.default_desc.kind != ColumnDefaultKind::Materialized || !column.default_desc.expression)
continue;
if (!ast_uses_changed_subcolumn(column.default_desc.expression))
if (column.default_desc.kind != ColumnDefaultKind::Materialized || !column.default_desc.expression

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This loop only consults old_metadata, so it still rejects safe combined alters that remove the dependent stored column in the same statement. For example, with m String MATERIALIZED toString(t), the following should be safe:

ALTER TABLE test
    MODIFY COLUMN t Tuple(a UInt64, b UInt64),
    DROP COLUMN m;

The same applies to MODIFY COLUMN m REMOVE MATERIALIZED. By the time the ALTER finishes there is no stored MATERIALIZED column left to go stale, but ast_uses_changed_subcolumn(...) still throws here before looking at new_metadata. You already special-case dropped indices/projections via new_indices.has(...) / new_projections.has(...); this needs the same final-metadata check.

&& isLazyMetadataConversion(old_types.at(command.column_name), command.data_type.get(), local_context))
{
/// A lazy metadata-only conversion (JSON type-hint change) has no mutation to rebuild
/// A lazy metadata-only conversion has no mutation to rebuild

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still only checks projection sort-key / WHERE dependencies, not the projection's stored output columns. A legal example is ADD PROJECTION p (SELECT t ORDER BY id) (or SELECT t AS s ORDER BY id): ProjectionDescription::fillProjectionDescriptionByQuery stores t / s in the projection sample block, but uses_changed stays false here because the projection key only depends on id.

After ALTER ... MODIFY COLUMN t Tuple(a UInt64, b UInt64, c UInt64), the existing projection part still serializes the old tuple shape while the refreshed projection metadata expects the new one, so queries that read from the projection will deserialize stale bytes as the new type. This guard needs to reject projections whose persisted output columns under the projection change type, not only projections whose sort key or WHERE changes.

@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch from f1cff93 to 3395561 Compare August 13, 2026 08:43
? "allow_metadata_only_named_tuple_alter"
: "allow_experimental_json_lazy_type_hints";

/// A lazy metadata-only conversion has no mutation to rebuild

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still looks at old_metadata only. If the same ALTER removes the offending TTL (REMOVE TTL or a per-column REMOVE TTL) before it finishes, there is no persisted ttl_infos left to go stale, but this branch still throws before consulting the final metadata. You already special-case dropped indices and projections above; TTLs need the same post-ALTER check so safe combined alters can stay metadata-only.

@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch from 3395561 to ff1cab7 Compare August 13, 2026 11:01
@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch 2 times, most recently from e924bbb to fee8d87 Compare August 13, 2026 14:13
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 77a7fe6e1 with master 0eb658995 (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: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.32 MiB 689.54 MiB -2.77 MiB (-0.40%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

532 object files changed (+1.45 MiB total), 13 added.

Object file Master PR Δ
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemHandlers.cpp.o new 257.14 KiB +257.14 KiB
src/CMakeFiles/dbms.dir/Common/SQLDefinedHandlers/SQLDefinedHandlersMetadataStorage.cpp.o new 177.03 KiB +177.03 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/currentRequestURL.cpp.o new 162.55 KiB +162.55 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/currentHandler.cpp.o new 162.25 KiB +162.25 KiB
src/CMakeFiles/dbms.dir/Common/SQLDefinedHandlers/SQLDefinedHandlerFromAST.cpp.o new 136.72 KiB +136.72 KiB
src/CMakeFiles/dbms.dir/Common/SQLDefinedHandlers/SQLDefinedHandlersFactory.cpp.o new 125.15 KiB +125.15 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTCreateHandlerQuery.cpp.o new 68.53 KiB +68.53 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserCreateHandlerQuery.cpp.o new 63.99 KiB +63.99 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTDropHandlerQuery.cpp.o new 54.66 KiB +54.66 KiB
src/CMakeFiles/dbms.dir/Interpreters/InterpreterCreateHandlerQuery.cpp.o new 39.01 KiB +39.01 KiB
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropHandlerQuery.cpp.o new 36.29 KiB +36.29 KiB
src/CMakeFiles/dbms.dir/Access/ContextAccess.cpp.o 930.83 KiB 952.70 KiB +21.86 KiB (+2.35%)
src/CMakeFiles/dbms.dir/Storages/transformQueryForExternalDatabase.cpp.o 169.55 KiB 190.57 KiB +21.03 KiB (+12.40%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserDropHandlerQuery.cpp.o new 17.27 KiB +17.27 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTLiteral.cpp.o 346.04 KiB 362.09 KiB +16.05 KiB (+4.64%)

737 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

3115 translation units recompiled, 20136 s compile time in total, 3102 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Storages/System/StorageSystemHandlers.cpp: 6.8 s
  • src/Common/SQLDefinedHandlers/SQLDefinedHandlersMetadataStorage.cpp: 6.0 s
  • src/Interpreters/InterpreterDropHandlerQuery.cpp: 5.6 s
  • src/Interpreters/InterpreterCreateHandlerQuery.cpp: 5.6 s

Job report

@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch 2 times, most recently from d06b376 to 1a49e73 Compare August 13, 2026 16:42

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I see some of the comments/exception messages where changed because explicit mutation doesn't rebuild something when subcolumn type is changed, it's being fixed in #112717, so we might keep some promises here as well.

Other than that, looks great

@amosbird
amosbird force-pushed the metadata-only-tuple-add-subfield branch from 1a49e73 to 77a7fe6 Compare August 14, 2026 06:41
@amosbird

Copy link
Copy Markdown
Collaborator Author

I see some of the comments/exception messages where changed because explicit mutation doesn't rebuild something when subcolumn type is changed, it's being fixed in #112717, so we might keep some promises here as well.

Other than that, looks great

I simplified this PR and removed the related fixes, tests, and comment/message changes. This PR now only integrates named Tuple subfield additions into the existing lazy metadata conversion path. The mutation dependency rebuilding behavior is left entirely to #112717.

@Avogar
Avogar added this pull request to the merge queue Aug 14, 2026
Merged via the queue into ClickHouse:master with commit 9507017 Aug 14, 2026
179 of 182 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 15, 2026
…ader

A SELECT ... FINAL whose PREWHERE consumes a column that FINAL needs for
merging (ver, is_deleted, sign), and which does not project that column,
raised a LOGICAL_ERROR:

  Unexpected number of kept output positions after removing unused columns
  from ReadFromMergeTree: expected 3, got 2

removeUnusedColumns() assigns kept_output_positions once, before the read
list is narrowed, so it always holds as many entries as the output header
had at entry. Narrowing then re-adds every column FINAL requires for
merging, and every PREWHERE input column, to all_column_names; a column in
either group that PREWHERE had erased from the output header therefore
reappears in the recomputed header. The header grows, the position vector
does not, and the assertion fires.

The assertion is correct and must stay: addDiscardingExpressionStepIfNeeded
and absorbExtraChildColumns both index kept_output_positions positionally
against their own inputs, so a short vector would pair columns with the
wrong inputs and return wrong results rather than fail.

The correct positions cannot be reconstructed at that point.
ColumnWithTypeAndName carries no source position, and
ActionsDAG::updateHeader matches inputs by name and emits DAG outputs
before pass-throughs, so the new order is not derivable from the old one.
Only a name key would remain, which is what the position-based rewrite
removed.

So refuse the request instead of repairing it afterwards: extend
canRemoveUnusedColumns() to return false when a column required for merging
under FINAL is read but absent from the output header. That is the
necessary condition for the header to grow, so the exclusion is targeted
rather than a bail-out for FINAL in general, and it gates both entry points
at once (tryRemoveUnusedColumns and canRemoveColumnsFromOutput, the latter
via canAllChildrenCanRemoveOutputs). The Graphite early return in the same
function is the existing precedent for excluding an unsupportable shape
here. Leaving the read plan untouched also keeps the columns FINAL needs,
which is the property issue ClickHouse#91849 is about.

The check is name-based, which is safe because it asks only whether a name
is present in a header, not where. It must not be generalised to the
position bookkeeping.

Measured, over 61 in-tree FINAL/PREWHERE tests, by instrumenting the
predicate against the real outcome of each removeUnusedColumns call: 26
prunings happen, all with the predicate false, and there is no call where
the predicate is true and a pruning would otherwise have occurred. So no
currently-pruning query loses the optimization.

Both CI sightings (AST fuzzer on ClickHouse#107305, stress test on ClickHouse#108069) read
through merge(), but the table function is not part of the mechanism: the
failure reproduces on a plain top-level FROM t FINAL, reaching the same
throw from tryRemoveUnusedColumns with no StorageMerge frame.

The new test covers one arm per merging mode, since the set of columns
FINAL requires differs per mode and therefore so does the size of the
mismatch: Replacing(ver, is_deleted) both top-level and through merge(),
Replacing(ver), Collapsing(sign) and VersionedCollapsing(sign, ver). Every
arm fails before this change. The reference asserts the returned rows, not
merely the absence of the exception, and those rows match the same
predicate written as WHERE, which does not take this path.

Related: ClickHouse#91849
@clickgapai

Copy link
Copy Markdown
Contributor

@amosbird @Avogar — title/description suggestions:

Description (currently misleading):

  • Why: The body names the gate as allow_experimental_metadata_only_named_tuple_alter, but src/Core/Settings.cpp:8434 declares allow_metadata_only_named_tuple_alter (no experimental_ infix, tier 0, not EXPERIMENTAL). Copy-pasting the setting name from the description produces UNKNOWN_SETTING. The changelog entry at the bottom of the body already uses the correct name, so the two disagree.

  • Suggested addition:

    Fix the first paragraph to read: Gated behind SET allow_metadata_only_named_tuple_alter = 1 (default false).

Ignore if intentional.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 5, 2026
…ky-check time limit

A single run of 04616_json_lazy_type_hints_key_safety reaches 139,590 ms on
`Stateless tests (amd_asan_ubsan, flaky check)`, 77.6 % of the 180 s per-test
limit `TEST_MAX_RUN_TIME_IN_SECONDS` in `tests/clickhouse-test`, and its p50 on
that lane tripled since 2026-07 (29,910 to 75,340 ms) as the file grew from 142
to 370 lines. On `Stateless tests (amd_msan, parallel, 1/3)`, which does not
enforce the limit, it exceeds 180 s outright at 188,270 ms. Runtime is linear in
the scenario count and the file now holds 31 of them, each needing its own table
because the table shape is what decides whether the `ALTER` is accepted, so the
only lever that preserves every assertion is more files.

Split the series at scenario boundaries, keeping the original file for the key
and index carriers:

- 04616_json_lazy_type_hints_key_safety: 8 scenarios, the sorting key, the
  partition key, the explicit skip index and their `toString` /
  `reinterpretAsString` wrapped forms
- 05076_json_lazy_type_hints_projection_safety: 10 scenarios, projections
  including the aggregate group key and the filtered WHERE, `MATERIALIZED`
  columns, `ALIAS` chains, the implicit auto-minmax index and the two
  plain-column cases
- 05077_json_lazy_type_hints_ttl_safety: 13 scenarios, six TTL kinds, the six
  unrelated-subcolumn allows and the setting-off control

The scenario blocks are moved verbatim: concatenating the three reference files
in file order reproduces the original reference byte for byte.

Two comments changed. The shared read-in-order note now says "in this series"
and "the series disables it" rather than "in this test", because only one
scenario forces a projection and it now lives in
05076_json_lazy_type_hints_projection_safety, so the original wording would be
inaccurate in the other two files. The setting-off banner in
05077_json_lazy_type_hints_ttl_safety said "the same change", which pointed at a
scenario now in 04616_json_lazy_type_hints_key_safety, and names that file
instead. The `-- Tags: no-fasttest` line is copied unchanged into all three
files, so no lane coverage changes.

`-- Tags: long` was rejected as the alternative: it would exempt the test from
the limit through the gate's own conjunct, but `--no-long` makes the LLVM
coverage jobs skip it, and the test currently has 30,784 OK rows and 0 SKIPPED
across five non-per-test `amd_llvm_coverage` lanes in 30 days.

Report of the worst enforcing arm:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107305&sha=fee8d87af6a945cab9dec6f15f045b676a41cbc5&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
ClickHouse#107305

Co-Authored-By: Claude Opus 5 <[email protected]>
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 pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants