Skip to content

Add new projection storage format - #108443

Draft
arsenmuk wants to merge 51 commits into
masterfrom
arsenmuk/projection-storage-format
Draft

arsenmuk wants to merge 51 commits into
masterfrom
arsenmuk/projection-storage-format

Conversation

@arsenmuk

@arsenmuk arsenmuk commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

New projection storage format - FLAT, when a projection lives in a directory neighbouring to the data part's directory, in opposite to the original storage format, now called LEGACY_NESTED, when a projections lives in a directory nested to the data part. Example:

part dir = all_1_1_0, projection p
LEGACY_NESTED (default) -> store/uuid/all_1_1_0/p.proj
FLAT -> store/uuid/all_1_1_0.p.proj

The projection storage format is controlled via projection_storage_format engine setting (EXPERIMENTAL), and therefore it is table specific. It defines the format for the new parts to be created, so enabling FLAT for an existing table, doesn't modify its parts, but every upcoming inserts mutation, merge or materialization operation will force it for new parts. Both layouts are always supported on read operations; the setting only defines layout for newly-written parts.
FLAT is designed for engines with atomic multi-directory commit. The atomicity for MergeTree on local disks, is ensured via the order of operations: when parts are going live, main data part always goes last - in case of mid-failures, the FLAT sibling projections will be handled as orphans; when part are going off-live, main data part always goes first - preventing FLAT projections to be used since then.

Major changes

  • New projection_storage_format setting (the feature)
  • Projection ownership to a part explicitly comes from checksums+metadata. Disk is used as a source of truth at checksums recovery.
  • Crash-safe multi-directory rename (commit-last)
  • orphan cleanup mechanisms

Other issues fixed

  • loadChecksums drops projection records when checksums.txt missing:
part with p.proj, checksums.txt corrupt/deleted -> loadChecksums recomputes
OLD: rebuilt checksums = data files only, no "p.proj"
NEW: detectProjections + read p.proj/checksums.txt -> "p.proj" record restored
  • RENAME TABLE leaves in-mem projection pointing to the "old" location in Ordinary engine
a) repro
SET allow_deprecated_database_ordinary = 1
CREATE DATABASE mydb ENGINE = Ordinary
CREATE TABLE mydb.hits ( ..., PROJECTION p (SELECT key, id, value ORDER BY id)) ...
RENAME TABLE mydb.hits TO mydb.clicks;

b) side effects
CHECK TABLE mydb.clicks                      # fails with FILE_DOESNT_EXIST
OPTIMIZE TABLE mydb.clicks FINAL      # fails with FILE_DOESNT_EXIST

Improvements

  • IDataPartStorage projection API redesign + centralized naming vocabulary
  • freeze + freezeRemote unified into one freeze(dst_disk)

Changelog category (leave one):

  • Experimental Feature

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

New experimental feature, to set projection storage format with projection_storage_format to one of: 'legacy_nested' (current and default), 'flat'. FLAT stores projections in a separate directory in the same root directory as the main data part.


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

@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2856348]

Summary: ❌

job_name test_name status info comment
Storage memory check FAIL
07_many_parts.sql FAIL cidb

AI Review

Summary

This PR adds the experimental flat projection on-disk layout and threads it through part publish, cleanup, recovery, and tests. The main shape looks right, but I still see one data-loss blocker in the new orphan cleanup path and several correctness / evidence gaps around CHECK TABLE, downgrade guidance, and object-storage merge coverage.

❌ Blockers
  • src/Storages/MergeTree/MergeTreeData.cpp:4260 — clearOrphanProjectionSiblings now decides keep_shared from the current allow_remote_fs_zero_copy_replication value. That is unsafe after a 1 -> 0 toggle: the same file already acknowledges in swapActivePart that remote blobs may remain shared after the setting is turned off again, so startup/background orphan GC can hard-delete blobs still referenced by another replica.
⚠️ Majors
  • src/Storages/StorageMergeTree.cpp:3972 — the checksums-present CHECK TABLE branch still drops the CheckDataPartResult entirely. The public wrapper returns {} on retryable verification failures, so this path still reports success instead of retrying when verification was skipped because of a transient error. I reopened the existing review thread for this.
  • src/Storages/StorageMergeTree.cpp:3955 — the missing-manifest repair path rewrites checksums.txt on disk but never installs the repaired manifests back into the live IMergeTreeDataPart / loaded projection-part objects. Until restart, send/backup paths that read the in-memory checksums can still advertise the stale pre-repair state.
  • src/Storages/MergeTree/MergeTreeSettings.cpp:2444 — the downgrade note is incorrect as written. projection_storage_format is persisted in table metadata, and older binaries still reject unknown MergeTree settings while loading metadata, so rewriting flat parts back to legacy_nested is not sufficient by itself; the setting must also be removed from metadata (RESET SETTING or equivalent).
  • tests/integration/test_projection_storage_format/test.py:3298 — the object-storage merge test stops immediately after OPTIMIZE TABLE ... FINAL. The local-disk merge coverage does a restart, but the s3-specific path never reopens the merged part from disk, so it does not prove the object-storage reopen path this PR is trying to harden.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 2856348.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 1246/1337 (93.19%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 25, 2026
@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch from 2b33155 to 48820b8 Compare June 25, 2026 10:00
@EmeraldShift

Copy link
Copy Markdown
Contributor

Interesting idea! I can't read the private repo issue that this refers to, but I'm curious to learn what the advantages and disadvantages of the flat format are?

@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch from 48820b8 to 79593ba Compare June 26, 2026 09:36
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch from 79593ba to 147250e Compare June 26, 2026 11:50
@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch 2 times, most recently from 720b5c8 to ff85e88 Compare July 6, 2026 16:23
@alexey-milovidov

Copy link
Copy Markdown
Member

Updating the branch to fix the 04001_join_reorder_through_expression test, which was broken today in master.

@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch from e7c6bc9 to 298de31 Compare July 7, 2026 05:29
@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch from 7ffc147 to 653a7bb Compare July 8, 2026 14:03
@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch from 653a7bb to 5f6489f Compare July 9, 2026 11:05
@arsenmuk
arsenmuk force-pushed the arsenmuk/projection-storage-format branch from ac820bd to e8f1a7a Compare July 13, 2026 07:34
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

68 object files changed (+419.30 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/DataPartStorageOnDiskBase.cpp.o 619.17 KiB 777.66 KiB +158.49 KiB (+25.60%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.11 MiB 4.18 MiB +68.22 KiB (+1.62%)
src/CMakeFiles/dbms.dir/Storages/Freeze.cpp.o 153.04 KiB 199.08 KiB +46.04 KiB (+30.09%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/checkDataPart.cpp.o 251.70 KiB 289.29 KiB +37.58 KiB (+14.93%)
src/CMakeFiles/dbms.dir/Core/SettingsEnums.cpp.o 2.16 MiB 2.18 MiB +22.53 KiB (+1.02%)

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

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

@arsenmuk @alesapin What is the point of the new format?
Also, we can name the old one "legacy", because it is the only one working on filesystems.

alexey-milovidov and others added 2 commits August 27, 2026 05:21
…t projection siblings

Two lifecycle gaps of the FLAT projection layout:

1. With \`fsync_part_directory = 1\`, \`freeze\` on the local hardlink path
   only synced \`<to>/<part>\` and its ancestors, while the copied FLAT
   siblings live beside it as \`<to>/<part>.<name>.proj\` -- a crash after
   \`FREEZE\` could persist the shadow parent (whose \`checksums.txt\`
   references the projection) while losing a sibling dentry. The packed
   override inherited the same hole because it disables the child fsync
   and relies on the top-level sync. \`fsyncFrozenCloneTree\` now takes the
   copied sibling trees and syncs them before the shared ancestor chain
   walk; both \`freeze\` overrides pass them via the new
   \`frozenFlatSiblingClonePaths\` helper.

2. The stale-sibling sweep at rename destinations was gated on the moving
   part's own \`flat_projection_storage_in_use\` flag, seeded from the
   current table setting. After \`ALTER TABLE ... MODIFY SETTING
   projection_storage_format = 'legacy_nested'\`, a new nested part reusing
   the final name of an interrupted pre-switch flat publish no longer
   swept the leftover \`<part>.<name>.proj\`; once the parent went live the
   sibling was no longer orphaned, so \`clearOrphanProjectionSiblings\`
   never reaped it. \`MergeTreeData\` now keeps a monotonic per-process
   \`flat_projection_storage_ever_used\` latch (raised at the
   \`getProjectionStorageFormat\` choke point and when a loaded/adopted part
   owns FLAT projections) and the per-part flag is seeded from it, so the
   sweep stays enabled after a downgrade. Residue that outlives a restart
   is parentless and already reaped by the startup orphan GC.

Tests: \`test_residue_swept_after_downgrade\`,
\`test_residue_swept_after_downgrade_and_restart\` (pins the load-time
latch), \`test_fsync_freeze_copies_sibling\`.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 2 commits August 29, 2026 02:14
The style check requires new MergeTree settings to be recorded in the
current version block. The entry was added under 26.8, which has since
been closed by the 26.9 release cycle on master, so move it to 26.9.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108443&sha=94834c7b2914f540daa30b6ad6a45b023274cfca&name_0=PR&name_1=Style%20check
PR: #108443

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@abashkeev abashkeev added the comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). label Sep 4, 2026
alexey-milovidov and others added 2 commits September 16, 2026 04:36
…-storage-format

# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.cpp
#	src/Storages/MergeTree/ReplicatedMergeTreeAttachThread.cpp
#	src/Storages/MergeTree/checkDataPart.cpp
#	src/Storages/StorageMergeTree.cpp
…gh `StorageMergeTree::checkDataNext`

The repair branch of `CHECK TABLE` (the one taken when a live part's `checksums.txt` is gone) threw away
everything `checkDataPart` returns except the parent's recomputed checksums: it compared them against the
stale in-memory `part->checksums`, wrote that stale manifest back to disk, and ignored the regenerated
child projection manifests. A part re-attached after `DROP PROJECTION` still lists the dropped projection in
its in-memory manifest, so the intact part was reported broken (`No file p.proj in data part`), and a
projection whose own `checksums.txt` was also missing never got it back.

Mirror `IMergeTreeDataPart::loadChecksums`: compare against the in-memory manifest minus the `.proj`
entries `checkDataPart` normalized away, persist `computed_projections_checksums` for the children, then
write `computed_checksums` as the parent manifest. `checkDataPart` now also reports the recomputed
checksums of a *loaded* projection whose manifest is missing, so the live-part repair covers that case.

`test_reload_check_table_dropped_projection` is updated to master's semantics (51e9f05): a since-dropped
projection listed in the part's own manifest keeps the part passing `CHECK TABLE`. Two new cases pin the
repair branch: `test_reload_check_table_dropped_projection_missing_manifest` and
`test_recovery_check_table_recompute_missing_projection_checksums`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-improvement Pull request with some product improvements labels Sep 16, 2026
{
auto calculated_checksums = checkDataPart(part, false, noop, /* is_cancelled */[]{ return false; }, /* throw_on_broken_projection */true);
calculated_checksums.checkEqual(part->checksums, true, part->name);
auto result = checkDataPart(part, false, noop, /* is_cancelled */[]{ return false; }, /* throw_on_broken_projection */true);

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 same empty-result contract is still missed here. The public checkDataPart wrapper returns {} when verification was skipped because of a retryable error, but this CHECK TABLE repair path immediately runs checkEqual on result.computed_checksums.

So a transient verification failure is reclassified as UNEXPECTED_FILE_IN_DATA_PART / NO_FILE_IN_DATA_PART, and CHECK TABLE reports a healthy part as corrupt instead of retrying. Please bail out on result.computed_checksums.empty() before checkEqual and let the retryable path retry, the same way the packed-fetch verification does.

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.

🕵 Fixed in f7b314f: both IMergeTreeDataPart::loadChecksums and StorageMergeTree::checkDataNext now check result.computed_checksums.empty() right after checkDataPart and throw a retryable ABORTED (same contract as the packed-fetch verification in DataPartsExchange). Nothing is written back, the part is not marked broken at load (loadDataPart rethrows retryable errors), and CHECK TABLE rethrows instead of reporting a mismatch.

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 is still open in the checksums-present branch. StorageMergeTree::checkDataNext now checks result.computed_checksums.empty() only in the missing-manifest arm, but the normal arm at src/Storages/StorageMergeTree.cpp:3972 still calls checkDataPart(...) for side effects and drops the CheckDataPartResult entirely. The public wrapper still returns {} on retryable verification failures at src/Storages/MergeTree/checkDataPart.cpp:634, so that branch still reports success instead of retrying whenever verification was skipped because of a transient error.

alexey-milovidov and others added 3 commits September 25, 2026 09:01
…-storage-format

Resolved conflicts:
- `StorageMergeTree::startup`: master now skips temporary-directory cleanup for read-only tables;
  kept `clearOrphanProjectionSiblings(0)` inside the same non-read-only block.
- `IMergeTreeDataPart::getProjectionPartBuilder`: kept the PR's read-only builder. Master's new
  `PartDirIntent::Synthetic` caller in `WhatIfProjectionEstimator` now uses a dedicated
  `getSyntheticProjectionPartBuilder`, which never creates or reclaims the directory.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ult` of a skipped recount

The public `checkDataPart` wrapper returns an empty result when verification was skipped because
of a retryable error. `IMergeTreeDataPart::loadChecksums` wrote that as an empty `checksums.txt`
(dropping every `.proj` ownership entry), and `StorageMergeTree::checkDataNext` reported a healthy
part as corrupt. Both now throw a retryable `ABORTED`, like the packed-fetch verification in
`DataPartsExchange`, so the part is not marked broken and the operation is retried.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…history block

The `settings_changes_history` style check requires the new setting under the current version.
The setting has not shipped in a release, so the record is moved rather than duplicated.

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

/// Zero-copy replication may share blobs across replicas invisibly to the local refcount.
bool keep_shared = false;
if (disk->supportZeroCopyReplication() && (*getSettings())[MergeTreeSetting::allow_remote_fs_zero_copy_replication])

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.

keep_shared is keyed off the current allow_remote_fs_zero_copy_replication value here, but the table can still have shared remote blobs after that setting was turned off again. The same file already relies on that invariant in swapActivePart (MergeTreeData.cpp:8704): a replica may still need to keep shared data even when the setting is now 0.

That makes this new cleanup path unsafe for historical zero-copy state. A replicated object-storage table can leave an orphan *.proj sibling while zero-copy is enabled, disable the setting later, and then have startup/background GC hard-delete blobs that another replica still references. Please make orphan/residue projection cleanup fail-safe on zero-copy-capable disks as well, instead of deciding from the current setting.


Both layouts are always read transparently; the setting only controls the layout of newly written parts. It applies to both full and packed part storage (a packed projection sub-part keeps its own `data.packed` archive in either layout).

Downgrade note: a server version without `flat` support loads a `flat` part with its projections marked broken (queries fall back to reading the parent part; projections can be rebuilt with `ALTER TABLE ... MATERIALIZE PROJECTION`), and it never removes the sibling directories, so they remain on disk until a version with `flat` support cleans them up. To downgrade cleanly, set `projection_storage_format = 'legacy_nested'` and rewrite `flat` parts first (for example with `OPTIMIZE TABLE ... FINAL`).

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 downgrade note overpromises. projection_storage_format is persisted as a normal MergeTree table setting, and older binaries still reject unknown MergeTree settings while loading table metadata (MergeTreeSettingsImpl::loadFromQuery still applies the stored settings list). So after MODIFY SETTING projection_storage_format = 'legacy_nested' and rewriting the old flat parts, the table still does not load on a server that predates this setting until the setting is removed from metadata as well (for example ALTER TABLE ... RESET SETTING projection_storage_format).

Please document that metadata-cleanup step, otherwise the advertised rollback path fails before the older server can even get to the “mark projections broken” behavior described here.

}
}

part_mutable.writeChecksums(result.computed_checksums, write_settings);

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.

writeChecksums only repairs the files on disk; it does not install the repaired manifests back into the live part objects. After this branch returns, part->checksums and any already-loaded projection-part checksums still hold the pre-repair state until restart.

That leaks into send/backup paths that read the in-memory manifests. For example, DataPartsExchange::sendPartFromDisk iterates part->checksums, so a stale dropped *.proj entry (or a projection whose own checksums.txt was repaired here) can still be re-advertised even though the on-disk manifests were fixed. Please update the live IMergeTreeDataPart / loaded projection parts in memory after writing the repaired manifests, not just the files on disk.


# merge into a single part; the merged part rebuilds the projection
node.query("SYSTEM START MERGES t_os_merge")
node.query("OPTIMIZE TABLE t_os_merge FINAL")

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 only proves the merged part works before it is reopened. The object-storage failure mode this PR is fixing is about part metadata / transaction state that can look fine immediately after OPTIMIZE TABLE ... FINAL and only break once the merged part is loaded back from disk.

The local-disk merge coverage above does a restart, but the dedicated object-storage merge test stops here, so a broken reopen path on s3 would still ship green. Please restart the server (or otherwise force the merged part to be reopened) before the final proj_query / CHECK TABLE assertions.

This branch was successfully deployed

1 active deployment
staging - docs — 28563483 Deployed Sep 25, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants