Skip to content

Open-source packed part storage - #108118

Merged
Algunenano merged 69 commits into
ClickHouse:masterfrom
Algunenano:packed-parts-oss
Jul 22, 2026
Merged

Algunenano merged 69 commits into
ClickHouse:masterfrom
Algunenano:packed-parts-oss

Conversation

@Algunenano

@Algunenano Algunenano commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

This open-sources packed part storage, a well established feature in our private fork, as part of our ongoing commitment to open source.

Packed storage keeps all of a data part's files inside a single archive (data.packed) instead of one file per stream. For small parts this significantly reduces the number of object-storage and Keeper requests, both on write and on parts load.

Notes on this first step:

  • The feature is disabled by default: the min_bytes_for_full_part_storage, min_rows_for_full_part_storage and min_level_for_full_part_storage thresholds default to 0, which means "always use Full storage". This matches the private default, where packed storage is turned on via configuration rather than via the setting defaults. It keeps the change backward compatible (for compatibility purposes there is no default behavior change). Enabling it by default in the settings, for both public and private, can come in a future release, or after merging support.
  • There is no allow_experimental_* gate because this is not an experimental feature: it is a well established storage format in the private fork. The only user-visible consequence of turning it on is a compatibility one, called out in the changelog entry below: once a table writes data.packed parts, older server versions cannot read them, so downgrading is no longer possible.

Changelog category (leave one):

  • New Feature

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

Added "packed" data part storage for MergeTree tables, which stores all of a part's files in a single archive (data.packed) instead of a file per stream. It is controlled by the min_bytes_for_full_part_storage, min_rows_for_full_part_storage and min_level_for_full_part_storage settings and is disabled by default. Compatibility note: once a table writes packed parts, older server versions cannot read them, so enabling this format prevents downgrading the server.

CheSema and others added 9 commits June 19, 2026 10:44
Introduce `DataPartStorageOnDiskPacked`, a data part storage that keeps
all of a part's files inside a single archive instead of a file per
stream. Add the supporting `IDataPartStorage` hooks (`isPackedPartStorage`,
`setPreferredFileOrder`, `getProjectionNoInitialize`) and
`PackedFilesReader::getFileOffsetAndSize`.

Co-authored-by: Raúl Marín <[email protected]>
Co-authored-by: Azat Khuzhin <[email protected]>
Co-authored-by: Antonio Andelic <[email protected]>
Co-authored-by: Konstantin Bogdanov <[email protected]>
Co-authored-by: alesapin <[email protected]>
Co-authored-by: Anton Popov <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Select packed storage in `MergeTreeData::choosePartFormat` based on the
`min_bytes_for_full_part_storage`, `min_rows_for_full_part_storage` and
`min_level_for_full_part_storage` settings, build it through
`MergeTreeDataPartBuilder`, and compute the preferred on-disk file order
(`getPreferredFileOrder`) so the archive is laid out for efficient reads.
Thread it through merges (`MergeTask`), inserts (`MergeTreeDataWriter`) and
mutations (`MutateTask`).

Co-authored-by: Raúl Marín <[email protected]>
Co-authored-by: Anton Popov <[email protected]>
Co-authored-by: Alexey Milovidov <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a `part_storage_type` column reporting whether a part uses `Full` or
`Packed` data part storage.

Co-authored-by: Raúl Marín <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `min_bytes_for_full_part_storage`, `min_level_for_full_part_storage`
and `min_rows_for_full_part_storage` settings now take effect outside
ClickHouse Cloud, so drop the "Only available in ClickHouse Cloud" note
from their descriptions.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Stateless tests covering packed selection, data correctness, refcounts and
column modification time, plus an integration test exercising packed parts
on local and S3 disks.

Co-authored-by: Alexander Gololobov <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Tidy the constructor parameter lists and the `build` / `getPartStorageByType`
call sites in `MergeTreeDataPartBuilder` after enabling packed storage.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The cached `skp_idx.packed` reader was reset on rename/changeRootPath while a
concurrent query could be reading its index, causing a data race and
use-after-free. Make `PackedFilesReader` a path-independent, shared, immutable
index: `readFile` now takes the archive's current disk and path from the
caller, so relocation no longer needs to free the reader.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Bring the open-sourcing branch up to current master, including the packed
skip-indices data-race fix and related follow-ups already merged upstream.
`cloneAndLoadDataPart` writes `metadata_version.txt` after freeze when
`metadata_version_to_write` is set (e.g. `REPLACE`/`MOVE`/`ATTACH PARTITION`
into a `ReplicatedMergeTree` table). Packed part storage needs an active
transaction for `writeFile`, so the bare write threw `NOT_INITIALIZED`. Wrap
the write in a packed transaction and commit it before loading the part.

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

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e47ad6]

Summary: ✅


AI Review

Summary

This PR open-sources packed part storage and wires it through inserts, merges, mutations, fetch, and the packed-io tooling. Most of the earlier packed-clone and packed-fetch correctness issues are fixed in the current head, but there is still one new correctness regression around Quantize('pq', ...) projections, plus two surviving behavior/policy gaps, so the change is not ready to merge as-is.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:5616] choosePartFormat(..., &projection) now inspects projection->metadata->getColumns(), but projection metadata strips column codecs when it is built in ProjectionDescription::fillProjectionDescriptionByQuery (src/Storages/ProjectionsDescription.cpp:507-529). A projection that actually materializes a Quantize('product', ...) column therefore sees column.codec == nullptr, stays Compact, and violates the same per-part codebook invariant this guard is meant to enforce. Suggested fix: preserve source codecs in projection metadata for pass-through columns, or compute the pq check from the projection outputs before codec metadata is dropped.

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeData.cpp:5623] storage_type = PartStorageType::Full is still forced only on the “would otherwise be Compact” pq path. That means small Quantize('product', ...) tables silently ignore min_*_for_full_part_storage, while larger pq parts can still end up Wide + Packed. The current behavior is therefore neither the “part type and storage type are orthogonal” contract documented in the new KB article nor a consistent “pq requires Full storage” rule. Suggested fix: either keep the computed storage_type and only promote part_type, or enforce/document/test Full for all pq parts consistently.

  • [src/Storages/MergeTree/MergeTreeData.cpp:5599] [dismissed by author -- https://github.com/Open-source packed part storage #108118#discussion_r3454634876] Packed storage is still enabled through ordinary min_*_for_full_part_storage thresholds without an allow_experimental_* gate even though this PR introduces a new on-disk part layout with irreversible downgrade impact once users turn it on. The defaults keep it off, but the ClickHouse rollout rule for new on-disk formats is still unmet as soon as those thresholds are raised. Suggested fix: require an explicit experimental gate for packed-part creation until the format is treated as GA in OSS.

Tests
  • ⚠️ Add a regression where a projection actually stores a Quantize('product', ...) column (for example PROJECTION p (SELECT id, vec ORDER BY id) with min_bytes_for_wide_part = '10G') and assert that system.projection_parts.part_type is Wide. The existing 04603 only proves the false-positive side of the new projection-column check.
Final Verdict
  • Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 22, 2026
Drop `filecmp` and `helpers.test_tools.TSV`, which were imported but unused
(flagged by the `ruff` style check).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`system.parts` gained the `part_storage_type` column, so the `SHOW CREATE`
schema snapshot in 02117_show_create_table_system needs the new column.

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

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes packed-part storage (freeze/clone, checksum-on-fetch verification, a packed-io CLI tool), build files, and docs — none of which is on the ClickBench query-execution path, and ClickBench parts use Full storage since the packed settings default to 0. Both flagged clickbench queries show flat CPU time (Q4: 2660.8 vs 2645.8 ms; Q15: 2585.4 vs 2593.6 ms) despite ~20% wall-time deltas, so these are measurement variance rather than real effects. Q4 was correctly suppressed as within master's variance band; Q15's flagged improvement is downgraded to not_sure for the same reason. No genuine performance signal is attributable to this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 243 189 -22.2% <0.0001 cache: ClickBench doesn't exercise packed-part storage (packed settings default to 0), and CPU is flat (2585.4 vs 2593.6 ms), so the -22.2% is run-to-run variance, not PR-caused.

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

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: ebbb4b24-ce58-4f68-acbf-374a0c0d0814
  • MIRAI run: 5724b8d1-d082-41ef-8231-97ed52aeedeb
  • PR check IDs:
    • clickbench_64479_1784660609
    • clickbench_64492_1784660609
    • clickbench_64498_1784660609
    • tpch_adapted_1_official_64504_1784660609
    • tpch_adapted_1_official_64515_1784660609
    • tpch_adapted_1_official_64526_1784660609

Algunenano and others added 2 commits June 22, 2026 17:58
02497 measured S3PutObject from query_log, but the part upload runs on the
object-storage writer pool, so the event is not attributed to the INSERT query
in the open-source build (it stays 0). Count the part's physical objects via
system.remote_data_paths instead: a packed part is a single archive object,
far fewer than full storage's one-object-per-file. Rename the test accordingly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace the S3PutObject query_log check (the upload runs on the object-storage
writer pool, so the event is never attributed to the INSERT query in the
open-source build) with a count of the part's distinct physical objects: a
packed part is a single archive object, far fewer than full storage's
one-object-per-file. Use the s3_cache policy, which exists in both repos.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Bring the packed archive tooling to public builds: the `packed-io`
clickhouse-disks subcommand and the standalone `clickhouse-packed-io`
program, which list, extract and create ClickHouse packed-format
archives (`data.packed`). The implementation (`PackedFilesOperations`,
`CommandPackedIO`, `programs/packed-io`) only depends on the already
public `PackedFilesReader`/`PackedFilesWriter`, so un-gate it from
`#if CLICKHOUSE_CLOUD`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/packed-io/PackedIO.cpp Resolved
Comment thread src/IO/PackedFilesOperations.cpp Resolved
These tests assert behavior that is specific to full (non-packed) part
storage. With packed storage now active in public builds, the CI random
MergeTree settings can pick a large `min_bytes_for_full_part_storage`,
switch the part to packed and break them. Pin the setting to 0 in the
table definitions, matching the existing fix in the private repository.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Algunenano and others added 2 commits July 21, 2026 17:02
…nking

In DataPartStorageOnDiskPacked::freeze the single-archive branch checked
external_transaction before copy_instead_of_hardlink. Detached clones always
arrive with an external transaction, so a zero-copy detached clone (which sets
copy_instead_of_hardlink so it gets an independent blob) still hardlinked
data.packed. The zero-copy bookkeeping does not record hardlinks in that case,
so removing the source could delete the only blob the detached clone
references. Decide copy-vs-hardlink before transaction-vs-direct, matching the
generic Backup path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
assertOutputNotInsideInput rooted local operands at disk->getPath() assuming it
is absolute. That holds for clickhouse-disks, but the standalone
clickhouse-packed-io builds DiskLocal("./"), so a relative root mixed with an
absolute operand (e.g. -i /abs/part -o ./out run from inside the input tree)
left one side relative and one absolute, and lexically_relative returned empty,
silently accepting a self-recursing create/extract. Anchor both operands with
fs::absolute so they are comparable and reflect where files actually land.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
StorageMetadataHandle table_metadata;
if (!projection)
table_metadata = getInMemoryMetadataPtr(getContext(), false);
const auto & columns = projection ? projection->metadata->getColumns() : table_metadata->getColumns();

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.

projection->metadata->getColumns() no longer carries parent codecs: ProjectionDescription::fillProjectionDescriptionByQuery rebuilds those columns from sample_block with ColumnDescription(name, type) only (src/Storages/ProjectionsDescription.cpp:507-529), so every column.codec here is nullptr for projection parts.

That fixes the false positive from the base-table scan, but it introduces the opposite bug: a projection that actually materializes a Quantize('product', ...) column now slips past this guard and can still be written as Compact, violating the same per-part codebook invariant this branch is supposed to enforce. Please preserve the source codec metadata for projected columns (or derive the check from the projection outputs before codecs are dropped) and add a regression that selects the pq column into the projection itself.

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.10% +0.10%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 861/1135 (75.86%) · Uncovered code

Full report · Diff report

@Algunenano

Copy link
Copy Markdown
Member Author

Both AI reviewer comments are related to the Quantize findings, which was done by design

@Algunenano
Algunenano enabled auto-merge July 22, 2026 13:26
@Algunenano
Algunenano added this pull request to the merge queue Jul 22, 2026
Merged via the queue into ClickHouse:master with commit e7ff414 Jul 22, 2026
525 of 528 checks passed
@Algunenano
Algunenano deleted the packed-parts-oss branch July 22, 2026 14:27
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 22, 2026
alexey-milovidov added a commit that referenced this pull request Jul 22, 2026
…pe-and-timeseries-irate

Master merged the same column via #108118 (commit dcf06b2, "Expose part_storage_type in system.parts");
resolved the conflict in StorageSystemParts.cpp by keeping this branch's comment wording
(names wrapped in inline code). This branch still adds the docs entries, the test, and pulls in
the fix for the unrelated test_check_table red (#111353).

Co-Authored-By: Claude Fable 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 27, 2026
The test counts the six extra fsyncs a merge performs for a `text` index's
three streams, read as the `OPTIMIZE` `FileSync` delta from `system.query_log`.
It never pinned `min_bytes_for_full_part_storage`, which `tests/clickhouse-test`
randomizes with `threshold_generator(0.3, 0.3, 0, 512Mi)`, so the drawn value is
non-zero in roughly 70% of runs.

Packed part storage was wired into part creation in OSS master by ClickHouse#108118. With a
non-zero draw both of the test's small parts are `Packed`, and a packed part is a
single blob: it has no per-stream index files to fsync, so the whole part costs
one fsync instead of fifteen and the delta reads 0 even though the merge is
correctly synced. Measured on the same fixture with only that setting varied:
`Full` storage gives 15 fsyncs for the `OPTIMIZE`, `Packed` gives 1.

Pin the setting to 0 in the three `CREATE TABLE` statements, the same one-line
idiom 104 other stateless tests already use (for example
`02346_text_index_part_format.sql`). An explicit table-level value is
authoritative against the runner's injection: `ClientBase::addMergeTreeSettings`
only adds a setting `if (!storage_settings.changes.tryGet(change.name))`.

This replaces the previous `no-flaky-check` / `no-random-merge-tree-settings`
tags, which suppressed a real and deterministic failure instead of fixing it, and
the retry loop that motivated the `.sh` form: the failure is per-run
deterministic given the drawn setting, so retrying could never help. The test
returns to the `.sql` form with the assertion unchanged.
@RinChanNOWWW

Copy link
Copy Markdown
Contributor

The packed writer holds all the data of the part in memory. Will there be a spill strategy in the near future? We cannot hold such huge data in memory obviously.

scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
The test counts the six extra fsyncs a merge performs for a `text` index's
three streams, read as the `OPTIMIZE` `FileSync` delta from `system.query_log`.
It never pinned `min_bytes_for_full_part_storage`, which `tests/clickhouse-test`
randomizes with `threshold_generator(0.3, 0.3, 0, 512Mi)`, so the drawn value is
non-zero in roughly 70% of runs.

Packed part storage was wired into part creation in OSS master by ClickHouse#108118. With a
non-zero draw both of the test's small parts are `Packed`, and a packed part is a
single blob: it has no per-stream index files to fsync, so the whole part costs
one fsync instead of fifteen and the delta reads 0 even though the merge is
correctly synced. Measured on the same fixture with only that setting varied:
`Full` storage gives 15 fsyncs for the `OPTIMIZE`, `Packed` gives 1.

Pin the setting to 0 in the three `CREATE TABLE` statements, the same one-line
idiom 104 other stateless tests already use (for example
`02346_text_index_part_format.sql`). An explicit table-level value is
authoritative against the runner's injection: `ClientBase::addMergeTreeSettings`
only adds a setting `if (!storage_settings.changes.tryGet(change.name))`.

This replaces the previous `no-flaky-check` / `no-random-merge-tree-settings`
tags, which suppressed a real and deterministic failure instead of fixing it, and
the retry loop that motivated the `.sh` form: the failure is per-run
deterministic given the drawn setting, so retrying could never help. The test
returns to the `.sql` form with the assertion unchanged.
alexey-milovidov added a commit that referenced this pull request Aug 1, 2026
The `#108118` changelog entry in `docs/resources/changelogs/oss/2026.mdx` also said
packed part storage stores *all* of a part's files in a single `data.packed`
archive. Aligned it with the corrected wording so every published English page
describes the same contract.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…thmetic

`reserveOrThrowTooManyTypes` relied on `std::vector::reserve` throwing
`std::length_error` to catch a corrupted `num_dynamic_types`. But the call
site computed `num_dynamic_types + 1` before reserving, so a corrupted
count equal to `SIZE_MAX` wraps around to `0` and bypasses the check
entirely. Validate `num_dynamic_types` against
`ColumnDynamic::MAX_DYNAMIC_TYPES_LIMIT` before the `+ 1`, and update the
`04307_dynamic_flattened_too_many_types` V2 fixture to encode `SIZE_MAX`
so it exercises exactly this case.

Also add the `no-parallel` tag to `03057_private_attach_disk_web`, matching
`03355_mergetree_table_disk` and `03823_table_disk_cache_key_collision`:
without it, CI runs multiple copies of the test concurrently, which collide
on the test's hardcoded table UUID (`TABLE_ALREADY_EXISTS` "UUID collision").

Drop `02790_packed_parts_refcount` and `04401_packed_skip_indices_concurrent_read_long`:
packed part storage (`min_bytes_for_full_part_storage`) isn't wired up on
master yet, so these currently don't exercise what they claim to, and both
paths are already being ported together with the feature itself in ClickHouse#108118.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

7 participants