Skip to content

Read and checksum the UNIQUE KEY dense-index SST through IDataPartStorage - #114777

Merged
murphy-4o merged 21 commits into
ClickHouse:masterfrom
JingYanchao:johnjing/refactor-sst-readbuffer
Sep 10, 2026
Merged

murphy-4o merged 21 commits into
ClickHouse:masterfrom
JingYanchao:johnjing/refactor-sst-readbuffer

Conversation

@JingYanchao

@JingYanchao JingYanchao commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Part of #103486

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Allow the UNIQUE KEY to work on encrypted and remote disks by reading and writing its dense-index SST through the part storage abstraction; the SST is now recorded in checksums.txt.

Description

The per-part UNIQUE KEY dense index (unique_key_index.sst) was opened and written by local filesystem path, which only worked on local disks and left the sidecar outside the part's checksum accounting.

This PR drives the SST through IDataPartStorage using a custom RocksDB Env(a read-only FileSystem over IDataPartStorage::readFile for the reader, a WriteBuffer-backed one for the writer), so encrypted and remote disks work as well. The SST is now recorded in checksums.txt, so it is transferred by backup/fetch like any other part file and validated by checkConsistencyBase: a missing or wrongly-sized SST fails the standard consistency check and the part is detached as broken, while size-preserving corruption is caught at load time by ensureValidDenseIndex (RocksDB block-checksum + entry-count validation), which removes and rebuilds the index. On readonly storage a corrupt or absent SST fails the load closed instead of activating an unprobeable part.

The previous restriction that UNIQUE KEY tables must reside on local-only storage policies is removed.


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

Version info

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

@murphy-4o murphy-4o added the can be tested Allows running workflows for external contributors label Aug 14, 2026
@murphy-4o murphy-4o self-assigned this Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f427e1]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

The PR moves the UNIQUE KEY dense-index SST onto IDataPartStorage, records it in checksums.txt, and adds load-time validation/rebuild logic plus S3/local integration coverage. The direction is correct, but I still see blockers around unsupported disk types, the unversioned on-disk layout change, and a remaining readonly load path that still detaches missing-SST parts before the new fail-closed logic can run.

PR Metadata

Changelog category: Improvement is reasonable for the intended change.

Changelog entry: required and present, but it overclaims encrypted-disk support. UniqueKeySSTProbe still rejects any storage whose readFile() buffer lacks readBigAt(), which includes encrypted disks today, so the current entry is not accurate.

Exact replacement:
Allow the \UNIQUE KEY` dense-index SST to be read and written through `IDataPartStorage`, and record it in `checksums.txt`, so it participates in part validation, backup, and fetch; remote disks with positional reads now work.`

Findings

❌ Blockers

  • [src/Storages/MergeTree/UniqueKey/UniqueKeySSTProbe.cpp:145-148] The PR removes the local-only storage restriction, but the new reader still hard-fails on any IDataPartStorage::readFile() result without readBigAt(). That leaves encrypted disks today (and other backends such as Web or HDFS-with-pread disabled) unsupported even though the PR body and changelog say they work. Suggested fix: either reject unsupported disks in CREATE / ALTER until a positional-read implementation exists for them, or narrow the claimed support and keep the old guard for those backends.
  • [src/Storages/MergeTree/UniqueKey/SSTIndexWriter.cpp:341] Writing unique_key_index.sst into checksums.txt changes the part-file contract without any version bit or transition reader. Newly written or rebuilt parts will therefore stop loading on older binaries that still treat the SST as a file-without-checksums, breaking downgrade / mixed-version ATTACH / restore once the first post-upgrade part is created. Suggested fix: version this layout change, or teach readers to accept both manifests during the rollout window.
  • [src/Storages/MergeTree/MergeTreeData.cpp:2648, 3140-3141] The new readonly contract still misses the "file absent" case. table_readonly = 1 is only consulted in the later ensureValidDenseIndex() call, but a local-disk part with a missing unique_key_index.sst and a checksum entry is already marked broken inside loadColumnsChecksumsIndexes(..., !part_disk_ptr->isReadOnly()) and detached before that branch runs. Suggested fix: thread table-level readonly into the earlier consistency decision (or special-case the SST there) so missing and corrupt SSTs both fail the load closed instead of detaching the part.

⚠️ Majors

  • [src/Storages/MergeTree/IMergeTreeDataPart.cpp:1820-1839, src/Storages/MergeTree/MergeTreeData.cpp:2648] Pre-existing UNIQUE KEY parts that already have unique_key_index.sst on disk but no checksums.txt entry are still treated as broken on writable load / ATTACH: the SST is no longer whitelisted in getFileNamesWithoutChecksums(), and consistency runs before any migration logic can backfill the checksum entry. Suggested fix: keep legacy SSTs ignored until after a checksum-backfill pass, or backfill checksums.txt before consistency checking.
  • [src/Storages/MergeTree/UniqueKey/UniqueKeyDenseIndexOps.cpp:145-168] [dismissed by author -- https://github.com/Read and checksum the UNIQUE KEY dense-index SST through IDataPartStorage #114777#discussion_r3794489539] A valid legacy SST with no checksum entry still never gets migrated on readonly storage: this branch returns immediately on Valid, so the part stays forever outside checksums.txt, size accounting, and transfer coverage. I still think this matters because the PR description explicitly calls out the “written before the sidecar was checksummed” path, but that path is not actually repaired here. Suggested fix: when the SST validates but its entry is missing from part->checksums, add the file to the checksum map and rewrite checksums.txt.
Tests
  • ⚠️ Add a focused encrypted-disk (or more generally supportsReadAt() == false) test, or a negative DDL test proving unsupported disks are rejected up front. The current suite only demonstrates S3/local paths.
  • ⚠️ Add a table_readonly = 1 plus missing unique_key_index.sst ATTACH test. The current readonly coverage only corrupts the file without removing it.
  • ⚠️ Add a compatibility test for pre-checksum parts and/or a mixed-version restore / ATTACH test if the new checksums.txt entry is intended to be rollout-safe.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 0f427e1.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 359/397 (90.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0f427e119 with master a05aaa178 (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

10 object files changed (+59.48 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/UniqueKey/UniqueKeySSTProbe.cpp.o 114.29 KiB 211.77 KiB +97.48 KiB (+85.29%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/UniqueKey/UniqueKeyDenseIndexOps.cpp.o 269.80 KiB 225.49 KiB -44.31 KiB (-16.42%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/UniqueKey/SSTIndexWriter.cpp.o 257.87 KiB 277.05 KiB +19.18 KiB (+7.44%)

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

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

Job report

@JingYanchao
JingYanchao force-pushed the johnjing/refactor-sst-readbuffer branch from 600ab79 to 7f82272 Compare August 17, 2026 06:57
@JingYanchao
JingYanchao force-pushed the johnjing/refactor-sst-readbuffer branch from e5831c2 to 4d05663 Compare August 17, 2026 14:35
@JingYanchao
JingYanchao force-pushed the johnjing/refactor-sst-readbuffer branch from 06d9f77 to 6b0a832 Compare September 2, 2026 13:55
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@JingYanchao
JingYanchao force-pushed the johnjing/refactor-sst-readbuffer branch from c2b37da to e10a674 Compare September 7, 2026 11:48
@murphy-4o
murphy-4o enabled auto-merge September 10, 2026 03:04
@murphy-4o
murphy-4o added this pull request to the merge queue Sep 10, 2026
Merged via the queue into ClickHouse:master with commit d8d2f99 Sep 10, 2026
342 of 345 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@JingYanchao @murphy-4o — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

murphy-4o added a commit to murphy-4o/ClickHouse that referenced this pull request Sep 12, 2026
…e local-only gate

Follow-up to the link index in the previous commit, which is already pushed and
untouched here.

## A bitmap naming a target nobody can parse no longer loads

`loadPart` logged and skipped such a file, so its kills left the index and the rows
they mark came back on the next restart. It throws CORRUPTED_DATA now and the
part is detached.

CORRUPTED_DATA and not LOGICAL_ERROR: the latter aborts under debug and sanitizer
builds, which would stop the caller ever reaching the detach and would put the test
behind `#ifndef DEBUG_OR_SANITIZER_BUILD` like the two beside it.

The call sits above `setState`, with the other two `mark_broken` paths of that
function: `loadDataPartsFromDisk` promotes a broken part's covered children only
while it does not read as Active. Review caught a first attempt that sat below it,
where a part broken by the bitmap load was detached and its replacements never
loaded.

The duplicate-part path leaves its links registered. The index is keyed by part
info, which a duplicate shares with the part already there, so `dropPart` would
erase the live part's links -- the same lost-kills failure this change closes.
Review caught that too, in a first attempt that tried to clean up after itself.

## The local-only storage restriction is gone

It was an interim guard held while the dense-index SST read still opened a local
filesystem path. That port landed upstream as ClickHouse#114777, which is in this branch's
master base, so every SST open in `UniqueKey/` goes through
`openSSTReaderFromStorage`, the bitmap file ops take an `IDataPartStorage`, and no
local-path primitive is left in the directory. Keeping it also failed two of this
module's own integration tests against the configuration they exist to cover:
`test_unique_key_sst_roundtrip_on_s3` and `test_unique_key_on_s3_survives_restart`
were red with SUPPORT_IS_DISABLED, and both pass with it removed.

## Two tests the index change left uncovered

`AStagedVersionResolvesIntoTheMiddleOfTheOrder` straddles a staged link with carried
3, 7 and 12 so the re-key lands between existing entries, which a two-entry case
cannot reach.

`AStagedLinkIsSweptOnceItsVersionResolves` pins the ordering inside
`removeObsoleteBitmaps`: it asks `versionAt` for the floor first, which resolves the
link, so a staged version below the floor is swept like any other rather than
surviving at the top. Written expecting the opposite; the code was right, and
nothing is lost because the surviving floor subsumes it.

A third, two staged holders of one target, is not here: both resolve to the same
prehistoric csn, so only one can win a read and "both links present" has no
observable consequence. It passed with the dedup deliberately broken.

## Verification

Build clean, 132/132 UNIQUE KEY gtests, 9/9 `unique_key` stateless, 5/5
`test_unique_key_sst` integration, `check_cpp.sh` silent.

Oracles run: appending instead of inserting in order fails
`AStagedVersionResolvesIntoTheMiddleOfTheOrder`; resolving nothing fails
`AStagedLinkIsSweptOnceItsVersionResolves`; restoring the log-and-skip fails
`ABitmapNamingAnUnparseableTargetRefusesTheLoad`. The detach is checked end to end:
plant `delete_bitmap_for_not_a_part_name.rbm`, DETACH, ATTACH -> 0 active parts, 1
detached `broken-on-start`, 0 rows readable.

Known, and not from this change: UNIQUE KEY INSERT on `metadata_type =
plain_rewritable` aborts at `IMergeTreeDataPart::assertHasVersionMetadata` -- the
part reaches the transaction commit before its version metadata is visible. Object
storage with the default metadata type dedups, deletes and merges correctly.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-unique-key Unique key in MergeTree: uniqueness enforced on insert through a key index (SST / dense index), d... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-unique-key Unique key in MergeTree: uniqueness enforced on insert through a key index (SST / dense index), d... 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.

5 participants