Skip to content

Add opt-in skipping of type-default columns in MergeTree parts - #98472

Merged
CurtizJ merged 45 commits into
ClickHouse:masterfrom
amosbird:skip-empty-columns
Sep 1, 2026
Merged

CurtizJ merged 45 commits into
ClickHouse:masterfrom
amosbird:skip-empty-columns

Conversation

@amosbird

@amosbird amosbird commented Mar 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds the opt-in MergeTree setting skip_empty_columns_on_insert. When enabled with serialization_info_version = 'with_missing_columns', an INSERT can omit physical storage for columns whose whole block contains only the column type's default value.

Omitted columns are recorded in the part's serialization.json as sorted {name, type} entries. Reads reconstruct the default of the recorded type, so values remain stable if the column later gains or changes a DEFAULT expression. The marker is preserved through merges, mutations, renames, attach/restore, replication, and partition replacement.

The optimization is disabled by default. It does not apply to patch parts or columns with DEFAULT, MATERIALIZED, or ALIAS expressions, and every part retains at least one physical column. Configuring an older serialization_info_version disables omission for rolling-upgrade compatibility.

This also supports partition-local wide schemas: for example, different partitions can use different JSON columns while unused empty JSON columns create no data streams and remain absent after merges.

{
  "missing_columns": [
    { "name": "b", "type": "UInt64" }
  ],
  "version": 2
}

Related: #4968, #92475

Changelog category (leave one):

  • New Feature

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

Added the opt-in MergeTree setting skip_empty_columns_on_insert, which avoids storing columns containing only their type-default value. It requires serialization_info_version = 'with_missing_columns'; keep an older serialization version during rolling upgrades with servers that cannot read the new part metadata.

Documentation entry for user-facing changes

  • Documentation is provided by the MergeTree setting description in source.

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

Version info

  • Merged into: 26.9.1.500 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [938564ef]

Summary: ✅


AI Review

Summary

This PR adds the opt-in skip_empty_columns_on_insert path for MergeTree, persisting omitted type-default columns as missing_columns metadata and carrying that contract through reads, merges, mutations, replication, and lifecycle operations. I rechecked the current diff, the refreshed PR discussion/threads, and the added stateless, integration, and gtest coverage; I did not find a remaining PR-specific correctness or compatibility issue that warrants a new inline review comment in this run.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 938564ef.

Metric Baseline Current Δ
Lines 88.50% 88.40% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 80.80% 80.70% -0.10%

Changed lines: Changed C/C++ lines covered: 596/652 (91.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 2, 2026
@amosbird
amosbird force-pushed the skip-empty-columns branch from facf467 to 92d5f86 Compare March 19, 2026 09:31
@amosbird
amosbird marked this pull request as ready for review March 19, 2026 23:54
@amosbird

Copy link
Copy Markdown
Collaborator Author

Hi @Fgrtue, I noticed you’ve assigned yourself to #92475. Would you be interested in taking a look at this one as well?

@Fgrtue Fgrtue self-assigned this Mar 20, 2026
@Fgrtue

Fgrtue commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

@amosbird thank for letting me know! Indeed, I will take a look.

Copilot AI left a comment

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.

Pull request overview

Adds an INSERT-time optimization for MergeTree to avoid writing data streams/files for columns that are entirely type-default within an inserted block, reducing disk usage for sparse-update patterns.

Changes:

  • Introduces skip_empty_columns_on_insert MergeTree setting and applies it in MergeTreeDataWriter::writeTempPartImpl by filtering all-default columns from the part’s written column list.
  • Adds IColumn::hasOnlyDefaults() (with implementations/overrides for several column types) to efficiently detect all-default columns.
  • Adds a new stateless test and reference output covering several correctness scenarios around missing columns.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/Storages/MergeTree/MergeTreeDataWriter.cpp Filters all-default columns before constructing MergedBlockOutputStream; toggles reset_columns when filtering occurred.
src/Storages/MergeTree/MergeTreeSettings.cpp Documents new MergeTree setting skip_empty_columns_on_insert.
src/Core/SettingsChangesHistory.cpp Records the new setting in settings change history.
src/Columns/IColumn.h / src/Columns/IColumn.cpp Adds and implements (via IColumnHelper) the new hasOnlyDefaults() API.
src/Columns/ColumnVector.h Adds a fast-path hasOnlyDefaults() using memoryIsZero.
src/Columns/ColumnConst.h / ColumnFixedString.h / ColumnDecimal.h Adds hasOnlyDefaults() overrides for common fixed-size representations.
src/Columns/ColumnLazy.h/.cpp, ColumnUnique.h, ColumnCompressed.h, ColumnBLOB.h, ColumnFunction.h, ColumnAggregateFunction.h, IColumnDummy.h Adds required hasOnlyDefaults() overrides/implementations (some throw / return conservative defaults).
tests/queries/0_stateless/04006_skip_empty_columns_on_insert.sql New stateless test cases for the optimization.
tests/queries/0_stateless/04006_skip_empty_columns_on_insert.reference Expected output for the new stateless test.

Comment thread src/Columns/ColumnVector.h Resolved

@Fgrtue Fgrtue left a comment

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.

I wanted to suggest to add custom hasOnlyDefaults() implementation for the following columns:

  1. ColumnString -- if I understand correctly, we could just check that the offsets are all 0
  2. ColumnNull -- probably memoryIsByte could have been used?
  3. ColumnArray -- likely we could also check that offsets are empty (equal to 0), as in case of ColumnString
  4. ColumnSparse -- it seems that only checking the offsets would be enough
  5. ColumnTuple -- at the moment we will call isDefaultAt() NxM times irrespectively if the column inside the tuple have optimized custom version of hasOnlyDefaults(). If we rewrite hasOnlyDefaults() method to just propagating the call to the columns that are stored in tuple, we might get some performance improvement.

Comment thread src/Columns/IColumn.h Resolved
@amosbird
amosbird force-pushed the skip-empty-columns branch from 08e6a6d to ec0cdad Compare March 23, 2026 17:43
@amosbird

Copy link
Copy Markdown
Collaborator Author

@Fgrtue It seems the CH Inc sync requires manual resolution.

@Fgrtue

Fgrtue commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

@amosbird should be done. I wanted to take a second quick look at the PR today, I will update you on the results. Just to make sure, that's the final version so far, right?

@amosbird

amosbird commented Mar 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

Just to make sure, that's the final version so far, right?

Yes. (I mistakenly configured Copilot to force push, which appears to have overridden the existing reviews. Sorry about that.)

@Fgrtue

Fgrtue commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

@amosbird, did you have a chance to see my previous review suggestion about adding optimized hasOnlyTypeDefaults() for ColumnString, ColumnNull, ColumnArray, ColumnSparse, and ColumnTuple? Do you think if would make sense to add them?

@amosbird

Copy link
Copy Markdown
Collaborator Author

Thanks for the tips! I've added optimized hasOnlyTypeDefaults for all five types in the latest push:

  • ColumnString — memoryIsZero on the offsets array (all empty strings ⟹ all offsets are zero)
  • ColumnNullable — memoryIsByte(..., 1) on the null map (all NULL ⟹ all bytes are 1)
  • ColumnArray — memoryIsZero on the offsets array (all empty arrays ⟹ all offsets are zero)
  • ColumnSparse — checks whether offsets is empty (no non-default values stored)
  • ColumnTuple — delegates to each sub-column's hasOnlyTypeDefaults with early exit

Test cases 5, 8, 9, and 10 exercise ColumnNullable, ColumnArray, ColumnTuple, and ColumnSparse respectively. ColumnString is covered by the existing cases (1, 3, 4).

@Fgrtue Fgrtue left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The tests are good. I wanted to suggest to add the following test cases:

  1. Testing for compact parts (i.e. use min_bytes_for_wide_part != 0, min_rows_for_wide_part = 0) for a) skipping column b) merging parts
  2. Could we also add a check for LowCardinality column as this is a pretty often use case?
  3. Regarding merges test, what do you think if we test both type of merges: vertical and horizontal ones?

Comment thread src/Columns/ColumnSparse.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@amosbird

Copy link
Copy Markdown
Collaborator Author

Added 4 new test cases addressing the review:

  • Case 11: compact parts (skip + merge, with min_bytes_for_wide_part = 1000000000)
  • Case 12: LowCardinality(String) (generic isDefaultAt through dictionary)
  • Case 13: vertical merge (enable_vertical_merge_algorithm = 1)
  • Case 14: horizontal merge (enable_vertical_merge_algorithm = 0)

Comment thread src/Columns/ColumnString.h Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

The Can't adjust last granule error in CI is a known issue. The fix is in #101641

@CurtizJ CurtizJ 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.

This introduces an inconsistency: if a user inserts a column with all-zero values and then changes its default expression, the values returned on read will change as well. The same inconsistency already exists for columns added via ADD COLUMN whose default expression is later modified, so this is not a new problem, but it may be worth avoiding in this case.

Maybe we can store a marker in serialization_infos.json that records whether the column was physically written, so the reader can fill in defaults correctly?

@amosbird

Copy link
Copy Markdown
Collaborator Author

Maybe we can store a marker in serialization_infos.json that records whether the column was physically written, so the reader can fill in defaults correctly?

@CurtizJ This might conflict with the proposal in #92475

@amosbird amosbird changed the title Skip writing all-default columns during MergeTree INSERT Add opt-in skipping of type-default columns in MergeTree parts Aug 28, 2026
{
/// Marker-only DROP/CLEAR has the same logical effect as physical data.
String marker_name = nameInPart(command.column_name);
if (part->getSerializationInfos().isMissingColumn(marker_name))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nameInPart() is only used for the marker fallback here, so a part that is behind a metadata-only rename still drops or clears the wrong thing when the column is physical rather than marker-only.

Concrete trace:

  1. ALTER TABLE t RENAME COLUMN a TO b commits metadata, leaving an old part with physical a; only alter_conversions knows that current b maps back to a.
  2. Before that part is rewritten, ALTER TABLE t DROP COLUMN b (or CLEAR COLUMN b) runs as a later ALTER, so this function sees only the current-name command.
  3. The wide/full branch checks part_columns.has(command.column_name) at MutateTask.cpp:676, which is false for the old physical a, and this fallback only checks isMissingColumn(nameInPart(command.column_name)), which is also false for an ordinary physical column.
  4. getColumnsForNewDataPart() has the same assumption in its second pass (serialization_infos.isMissingColumn(original_name) at MutateTask.cpp:842), so the mutated part keeps the old data and the read path still exposes it as b instead of applying the later drop or clear.

The rename-mapped physical column needs to be handled the same way as the marker case: resolve the source-part name before deciding whether the DROP COLUMN / CLEAR COLUMN applies, and use that same mapping when filling removed_columns.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in the latest commit. Mutation planning now resolves DROP/CLEAR commands to the source-part physical name before checking and removing physical columns, and the resulting part metadata tracks both source and current names. Added a physical rename -> drop -> add regression covering pending and materialized states.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Update: I reverted the physical-column rename/drop changes in 938564e because they are broader than missing-column markers and caused regressions in existing rename-chain/swap tests. This physical-column issue is therefore not fixed by the current PR; only marker-specific handling remains. Reopening this thread so its status accurately reflects the current code.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I verified that this physical-column issue is independent of this PR: it reproduces with a normal physical a column, without missing_columns and with skip_empty_columns_on_insert disabled. This PR only adds handling for marker-only columns that have no physical files. Fixing the adjacent physical rename -> DROP/CLEAR lifecycle affects the general rename machinery (rename chains, swaps, wide/compact/packed parts); my attempted broad fix caused existing rename regressions, so I reverted it in 938564e. I suggest tracking and fixing the physical-column issue separately with dedicated coverage, while keeping this PR scoped to missing-column markers.

else if (command.type == MutationCommand::Type::DROP_COLUMN)
{
/// Marker-only DROP/CLEAR must still update metadata and dependencies.
String marker_name = nameInPart(command.column_name);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still misses the physical-column side of the rename case for compact / non-full parts.

nameInPart() is only used for the marker fallback below, but this branch checks part_columns under the current name. If a part still physically stores a, a pending RENAME COLUMN a TO b is applied on read, and a later CLEAR COLUMN b (or DROP COLUMN b followed by ADD COLUMN b DEFAULT 999) arrives before the part is rewritten, this condition is false, so the clear/drop is ignored. The rename-map block below then queues READ_COLUMN b, and the mutation materializes the old a data as the current b instead of clearing or dropping it.

The wide/full branch already has the analogous bug tracked on the open thread at line 692. This compact/non-full path needs the same nameInPart() mapping before deciding whether the source part has the column, plus a compact-part regression for rename -> clear/drop+add of a physical column.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in the latest commit. The compact/non-full branch now resolves the command name through nameInPart() before checking physical/nested columns, and DROP/CLEAR file-removal commands use the source-part spelling. Added a compact physical rename -> drop -> add regression covering pending and materialized states. I also reverted the broader getColumnsForNewDataPart name remapping from the previous commit because Fast test exposed regressions in rename chains/swaps; the fix is now scoped to mutation command splitting.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Update: I reverted the compact physical-column rename/drop changes in 938564e because they are broader than missing-column markers and caused regressions in existing rename behavior. The compact physical-column issue is therefore not fixed by the current PR; only marker-specific handling remains. Reopening this thread so its status accurately reflects the current code.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Same conclusion for compact/non-full parts: this physical-column rename -> DROP/CLEAR issue reproduces without missing-column markers and without enabling this PR’s setting. It belongs to the existing general rename mutation path rather than marker handling. Since a broad fix affected existing rename-chain/swap behavior, I reverted it and suggest addressing wide and compact physical columns together in a separate issue/PR with dedicated rename coverage.

@CurtizJ CurtizJ 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.

LGTM

@CurtizJ
CurtizJ enabled auto-merge September 1, 2026 20:35
@CurtizJ
CurtizJ added this pull request to the merge queue Sep 1, 2026
Merged via the queue into ClickHouse:master with commit 0f3a55d Sep 1, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 1, 2026
alexey-milovidov added a commit to niyue/ClickHouse that referenced this pull request Sep 16, 2026
`MutationsInterpreter` still re-evaluated every `MATERIALIZED` expression of the table once a
`CLEAR COLUMN` made any of them stale, refreshing columns whose expression had been changed by a
metadata-only `MODIFY COLUMN`. Master narrowed this in "Limit clear recomputation to affected
columns" (ClickHouse#98472): only the columns reading the cleared column, directly or through another
recomputed `MATERIALIZED` column, are rewritten, and unrelated columns and their projections and
skip indices are left untouched. The branch kept the old widening, so master's
`04546_ttl_delete_where_recalc_after_update` failed in the Fast test.

Drop the widening and keep the stale closure as the only set of recomputed columns. Restore
`04648_mutation_statistics_type_mismatch` to master's version and rewrite
`04837_clear_column_rematerializes_only_dependents` to assert the narrowed behaviour.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=105045&sha=231b89ca4b9e3d49694b7037d38cf4b414753348&name_0=PR&name_1=Fast%20test
PR: ClickHouse#105045

Co-Authored-By: Claude Fable 5.1 <[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-feature Pull request with new product feature 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.

8 participants