Skip to content

Detach a patch part whose index lost its content to a zeroed block - #119585

Merged
alexey-milovidov merged 13 commits into
masterfrom
fix-patch-part-zero-filled-index-116611
Sep 23, 2026
Merged

alexey-milovidov merged 13 commits into
masterfrom
fix-patch-part-zero-filled-index-116611

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

Every patch part created by a lightweight UPDATE persists the index of the parts it patches in source_parts.dat. A zeroed block in that file parses as a valid index: the first byte 0 is the V1 format version, the next eight zero bytes give num_parts = 0, the parse loop is skipped, and nothing checks the bytes that follow. The result is the one corruption shape that bypasses the broken-part contract completely:

CREATE TABLE t (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO t SELECT number, number FROM numbers(5000);
UPDATE t SET v = v + 1000 WHERE id < 2500 SETTINGS enable_lightweight_update = 1;
SELECT sum(v) FROM t;   -- 14997500, acknowledged
# overwrite the patch part's source_parts.dat with zeros of the same size
dd if=/dev/zero of="$SOURCE_PARTS_DAT" bs=1 count="$(stat -c%s "$SOURCE_PARTS_DAT")" conv=notrunc
SELECT sum(v) FROM t;   -- 12497500: the acknowledged update is gone, with no error
-- the patch part is still Active and nothing is detached, so background cleanup deletes it:
-- an empty index reports data version 0, which makes the "materialized everywhere" condition of
-- `clearUnusedPatchParts` trivially true, and the only copy of the update is destroyed

Two invariants close it, and both are about content the writer always produces:

  • PatchPartIndex::readBinary now asserts that the file ends where the index ends. The file holds nothing else, so bytes left over mean its content is not what was written - and for the zero-filled shape those leftovers are exactly what used to be ignored.
  • A patch part that holds rows names the parts it patches, so an index with no source parts and a non-zero row count is rejected on the load path. An empty index stays legitimate for an empty part (the covering parts cloneEmpty creates).

The part is then detached as broken-on-start, like every other part-metadata corruption: the failure is reported, the cleanup cannot drop the part, and the rows stay recoverable from detached/.

Coverage does not corrupt a part's files - it goes through the writer and the parser instead:

  • gtest_patch_part_index_read covers PatchPartIndex::readBinary: a zeroed block of the size the writer produced is rejected, as is any other trailing content, while an index with no source parts on its own stays accepted - that shape belongs to an empty covering part.
  • 05229_patch_part_empty_index_detached covers the load path through the new patch_part_index_write_empty failpoint, which makes the writer persist an index without source parts. The acknowledged UPDATE is visible while the part is in memory, and reloading the table detaches the part as broken-on-start instead of loading it Active with an index that applies to nothing. An uncorrupted patch part still loads and still applies.

The stronger check the issue also mentions - verifying the content hash checksums.txt already records for source_parts.dat on the load path - is not done here: it would cover any corruption of that file rather than this shape, but it changes what the load path verifies for every patch part, which deserves its own change.

Closes: #116611

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fix a patch part whose source_parts.dat lost its content to a zeroed block loading as an empty index, which silently unapplied an acknowledged lightweight UPDATE and then let background cleanup delete the only copy of it. Such a part is now detached as broken.


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

Version info

  • Merged into: 26.10.1.528-master (included in 26.10 and later)
  • Backported to: 26.9.2.24, 26.8.11.27, 26.7.14.50, 26.3.33.153

Every patch part created by a lightweight `UPDATE` persists the index of the
parts it patches in `source_parts.dat`. A zeroed block in that file parses as a
valid index: the first byte `0` is the `V1` format version, the next eight zero
bytes give `num_parts = 0`, the parse loop is skipped, and nothing checks the
bytes that follow. The patch part then loads clean and Active, the acknowledged
update is silently unapplied - an empty index returns no patches for any source
part - and background cleanup finishes the job: an empty index reports data
version 0, which makes the "materialized everywhere" condition of
`clearUnusedPatchParts` trivially true, so the only copy of the update is
deleted. It is the one corruption shape of a patch part that bypasses the
broken-part contract completely: instead of detaching the part for inspection,
the server destroys it. A zero-length or truncated `source_parts.dat` fails
loudly today.

Two invariants close it, both about content every writer produces:

  - `PatchPartIndex::readBinary` asserts that the file ends where the index ends.
    The file holds nothing else, so bytes left over mean its content is not what
    was written, and for the zero-filled shape those leftovers are exactly what
    used to be ignored.
  - A patch part that holds rows names the parts it patches, so an index with no
    source parts and a non-zero row count is rejected on the load path. An empty
    index stays legitimate for an empty part (the covering parts `cloneEmpty`
    creates).

The part is detached as `broken-on-start` after that, like every other
part-metadata corruption, so the failure is reported, the cleanup cannot drop the
part, and the rows stay recoverable.

Closes: #116611
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6a77f57]

Summary: ✅


AI Review

Summary

This PR hardens patch-part loading against the source_parts.dat corruption shape that used to silently unapply an acknowledged lightweight UPDATE: it rejects trailing garbage in the on-disk index file, rejects non-empty patch parts whose index names no source parts, and adds focused parser/load-path coverage. I read the current diff, current code, prior threads, and follow-up discussion on the current merged-forward head, and I did not find a remaining correctness, compatibility, or coverage issue in the patched paths.

Final Verdict

✅ Approved. No new findings.

LLVM Coverage Report

Measured on commit 6a77f57.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). labels Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6a77f5710 with master 36ce602e4 (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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Now LGTM. No tests needed.

@alexey-milovidov alexey-milovidov removed the pr-bugfix Pull request with bugfix, not backported by default label Sep 12, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 12, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

The only flagged query is ClickBench Q5, marked a 12.3% improvement (221 ms vs 252 ms). This PR adds corruption detection for patch-part indexes on the merge-tree part load and write paths (a CORRUPTED_DATA check plus an assertEOF on the index file), touching nothing in the read/scan hot path a ClickBench SELECT runs. CPU time is essentially flat between base and source (2947 ms vs 2851 ms), reinforcing that the wall-clock delta is measurement variance rather than a real PR effect, so Q5 is downgraded to not_sure. No cross-query patterns; nothing else was flagged.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 5 not_sure 252 221 -12.3% <0.0001 This PR only adds patch-part index corruption checks on the part load/write path, which a ClickBench Q5 SELECT never exercises; the -12.3% shift is run-to-run variance.

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: 6082a2fd-ecb5-4916-b62e-8406a3f366ae
  • MIRAI run: c8ef87f1-4689-4292-bc4e-db37c71eecf8
  • PR check IDs:
    • clickbench_1447141_1790137856
    • clickbench_1447147_1790137856
    • clickbench_1447153_1790137856
    • tpch_adapted_1_official_1447164_1790137856
    • tpch_adapted_1_official_1447175_1790137856
    • tpch_adapted_1_official_1447211_1790137856

alexey-milovidov and others added 2 commits September 18, 2026 21:03
The first version of this test corrupted `source_parts.dat` on disk from a shell
script, which is not how a test may reach this code. The coverage is reached
through the writer and the parser instead, and no test touches the files of a
part:

  - `gtest_patch_part_index_read` covers `PatchPartIndex::readBinary`: an index
    round-trips, a zeroed block of the size the writer produced is rejected (it
    parses as `V1` with no source parts, and the leftover bytes are what used to
    be ignored), any other trailing content is rejected the same way, and an
    index with no source parts on its own is still accepted - that shape belongs
    to an empty covering part, and the load path is what rejects it for a part
    that holds rows.
  - `05229_patch_part_empty_index_detached` covers the load path. The new
    `patch_part_index_write_empty` failpoint makes the writer persist an index
    without source parts, which is the content a lost `source_parts.dat` leaves
    behind. The acknowledged `UPDATE` is visible while the part stays in memory,
    and reloading the table detaches the part as `broken-on-start` instead of
    loading it Active with an index that applies to nothing - so the rows stay in
    `detached/` rather than being deleted by `clearUnusedPatchParts`, which finds
    an empty index materialized everywhere. An uncorrupted patch part still loads
    and still applies.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119585&sha=ce4554ece09274a63dc78c57a561ade885c70ad9&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The oracle mismatch is a text-index one and cannot come from this PR (it only adds two integrity checks on the patch-part load path):

Optimized query (count=0): SELECT count() FROM (SELECT toLowCardinality('Test select text + hasAnyTokens:'), text FROM tab__fuzz_0 WHERE hasAnyTokens(text, ['Alick']))
Unoptimized query (count=1): SELECT countIf(hasAnyTokens(text, ['Alick'])) FROM tab__fuzz_0

A candidate for the same root cause is #117077 (the text-index preprocessor being dropped where index analysis does not run, so the same expression answers differently by position); please confirm or open a new issue.

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-improvement Pull request with some product improvements labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed: #117077 is the same root cause, and the fix in progress is #117774. It reproduces on plain master, so it is not from this PR.

The fuzzer synthesized a preprocessor that the seed test (02346_text_index_direct_read) does not have:

CREATE TABLE tab__fuzz_0 (`k` FixedString(4), `text` Nullable(String),
    INDEX idx (text) TYPE text(tokenizer = 'unicode_word', preprocessor = reverseUTF8(text)) GRANULARITY 100000000)
ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 2, index_granularity_bytes = '10Mi';
INSERT INTO tab__fuzz_0 VALUES ('101', 'Alick a01'), ('102', 'Blick a02');

On master 01b8f1c9fb2e1 (26.10.1.1), with the settings from the report:

query result
SELECT count() FROM (SELECT text FROM tab__fuzz_0 WHERE hasAnyTokens(text, ['Alick'])) 0
SELECT countIf(hasAnyTokens(text, ['Alick'])) FROM tab__fuzz_0 1
the same WHERE query SETTINGS use_skip_indexes = 0 1
the same WHERE query SETTINGS query_plan_direct_read_from_text_index = 0 0
the same table without the preprocessor, both positions 1, 1

EXPLAIN actions = 1 shows the asymmetry directly:

  • WHERE: hasAnyTokens(reverseUTF8(text), ['Alick'], 'asciiCJK')
  • SELECT list: hasAnyTokens(text, ['Alick'], 'asciiCJK')

The tokenizer is injected in both positions, the preprocessor only in a filter DAG, because of the is_filter_dag conjunct of apply_preprocessor in src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:757. So the discriminator is the preprocessor plus the position of the predicate, not the direct read.

#117774 by @ ahmadov removes exactly that conjunct, and its new test covers both countIf(hasAnyTokens(...)) in the SELECT list and use_skip_indexes = 0. It is open with changes requested from @ Ergus on 2026-09-14, so I am not opening a duplicate issue or a competing PR; if it stalls, I can carry the fix in a separate PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks for the confirmation — agreed, the oracle mismatch is #117077 and the fix in flight is #117774, both outside this PR.

Status of this branch: merged master (cf5278ebcf07). The only red left was Build (arm_tidy), and it was not from the reviewed change either — it was a readability-duplicate-include on src/Core/tests/gtest_settings.cpp, a duplicate #include <IO/VarInt.h> that came in with the previous master merge and was already fixed on master by 4137c1161c04, so the merge pulls the fix in.

Re-verified locally on the merged tree: PatchPartIndexRead gtests 2/2 pass and 05229_patch_part_empty_index_detached passes.

alexey-milovidov and others added 2 commits September 20, 2026 10:47
`ReadBufferFromString` only stores a pointer and a size into the string it is
given, so constructing it from the temporary `written + String("\0\0\0", 3)`
left the buffer pointing at freed memory: the temporary is destroyed at the end
of the declaration, before `readBinary` reads from it. Keep the concatenated
string in a named local so it outlives the buffer.

Reported by the `Unit tests (asan_ubsan)`, `Unit tests (tsan)` and
`Unit tests (msan)` jobs:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/119585/cf5278ebcf07479465478092795400445a47ef2b/pr/unit_tests_tsan/unit_tests_tsan.log
#119585

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of this branch (head 26b80ab6342b, 3 commits behind master, merge-clean):

The only red left is 05227_storage_settings_unknown_name in Stateless tests (amd_debug, parallel) and Stateless tests (arm_binary, parallel). It is not from this PR — this change only adds two integrity checks on the patch-part index load path, while the failing test asserts where a SETTINGS reset (max_threads = DEFAULT, custom_x = DEFAULT) is stored in a CREATE TABLE definition.

It is fleet-wide on master: the same test failed today on #120906, #112847, #119039, #121181, #121180, #121146 and others. The fix is already in flight as #121163 (by @groeneai), which decouples the test from where a SETTINGS reset is stored; it is not merged yet, so merging master here would not clear the red.

Everything else on this head is green or still running, the AI review verdict is ✅ Approved. No new findings., and there are no unresolved review threads. Nothing to push.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of this branch (new head 46ab0b4c5ecc):

Merged master (the branch was 319 commits behind; the merge is clean, no conflicts). The previous head 3460a0c03f77 had one red, Build profile diff, and it is not from this change — it is the fleet-wide CI-logs-cluster infra failure tracked as #120462 (RuntimeError: CI logs cluster query failed), with fixes already in flight as #121048 and #118708.

master touched IMergeTreeDataPart.cpp, MergedBlockOutputStream.cpp and FailPoint.cpp in the meantime (including SYSTEM DISABLE ALL FAILPOINTS), so I re-verified the merged tree locally: it builds clean and 05229_patch_part_empty_index_detached passes against a server built from 46ab0b4c5ecc. The test already disables patch_part_index_write_empty explicitly, so it complies with the new failpoint hygiene check.

The reviewed diff is unchanged (7 files, +212/-1). No unresolved review threads; AI Review verdict on the previous head was ✅ Approved. No new findings., and the human review is "Now LGTM. No tests needed.". CI is re-running on the new head.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of this branch (head 7927bacd220a, unchanged, merge-clean against master):

Correction to my previous status comment: CH Inc sync is not green on this head. The private sync PR has two red jobs, and neither is from this change (the PR only adds two integrity checks on the patch-part index load path plus a failpoint):

  • Stress test (amd_tsan, SharedCatalog, meta in keeper) - the job died in its smoke check before any stress run: DROP TABLE foo_00234 in 00234_disjunctive_equality_chains_optimization hit Timeout exceeded: maximum: 60000.000 ms (TIMEOUT_EXCEEDED). No patch parts involved; an infra timeout on a TSan server start-up.
  • Stateless tests (amd_msan, distributed cache, meta in keeper, s3 storage, parallel, 2/3) - the only failed test is 01509_check_many_parallel_quorum_inserts_long, failing for "having stderror": a Poco::TimeoutException inside ReadWriteBufferFromHTTP during a part fetch. Again unrelated to patch-part index loading.

I re-ran the two failed private jobs (run attempt 2 is queued) rather than re-merging master, since a merge would only restart the whole CI without changing anything here.

The single public red is still Stress test (amd_tsan): the server abort on Unexpected return type from plus. Expected UInt256. Got Int256. in FillingTransform::interpolate, tracked in #121254 with the fix in #121230 (still open). I will merge master once that fix lands.

Review state unchanged: 0 unresolved threads, AI Review "Approved. No new findings.", Alexey "Now LGTM. No tests needed.". Nothing to push.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (849 commits behind, merge-clean) → new head 6a77f57106e2. The PR's five translation units (FailPoint.cpp, IMergeTreeDataPart.cpp, MergedBlockOutputStream.cpp, PatchPartIndex.cpp, gtest_patch_part_index_read.cpp) recompile clean on the merged tree.

The previous head's only public red was Stress test (amd_tsan): the LOGICAL_ERROR Unexpected return type from plus in FillingTransform::interpolate, tracked as #121254 with its fix in #121230 (still open). It is unrelated to this change. The CH Inc sync status is green. On the private side, the leftover red job fails only on the flaky 01509_check_many_parallel_quorum_inserts_long (a Poco::TimeoutException shows up as "having stderror"), which is also unrelated. 0 unresolved review threads.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
Merged via the queue into master with commit c90b558 Sep 23, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-patch-part-zero-filled-index-116611 branch September 23, 2026 17:19
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 23, 2026
Backport #119585 to 26.9: Detach a patch part whose index lost its content to a zeroed block
clickhouse-gh Bot added a commit that referenced this pull request Sep 23, 2026
Backport #119585 to 26.8: Detach a patch part whose index lost its content to a zeroed block
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
PedroTadim pushed a commit that referenced this pull request Sep 25, 2026
… a zeroed block

Cherry-pick of #119585, re-expressed against this branch.

The branch still calls the index `SourcePartsSetForPatch`, parses it through a member
`readBinary` rather than a static factory, and has no `cloneEmpty` - a default-constructed
set serialises to the same nine bytes. `PatchPartIndex.cpp` does not exist, so the parser's
contract is stated at the declaration instead.

The one hazard worth naming: the rows-count check merges *cleanly* into the position it
holds on master, which is ahead of `loadRowsCount`. Here the index is loaded last, so left
there the check would see an unloaded index and reject every patch part. It is anchored to
the `loadSourcePartsSet` call instead.

Closes: #116611

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim pushed a commit that referenced this pull request Sep 25, 2026
… a zeroed block

Cherry-pick of #119585, re-expressed against this branch.

The branch still calls the index `SourcePartsSetForPatch`, parses it through a member
`readBinary` rather than a static factory, and has no `cloneEmpty` - a default-constructed
set serialises to the same nine bytes. `PatchPartIndex.cpp` does not exist, so the parser's
contract is stated at the declaration instead.

The one hazard worth naming: the rows-count check merges *cleanly* into the position it
holds on master, which is ahead of `loadRowsCount`. Here the index is loaded last, so left
there the check would see an unloaded index and reject every patch part. It is anchored to
the `loadSourcePartsSet` call instead.

Closes: #116611

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 25, 2026
Cherry pick #119585 to 26.7: Detach a patch part whose index lost its content to a zeroed block
PedroTadim added a commit that referenced this pull request Sep 25, 2026
Cherry pick #119585 to 26.3: Detach a patch part whose index lost its content to a zeroed block
robot-clickhouse added a commit that referenced this pull request Sep 25, 2026
robot-clickhouse added a commit that referenced this pull request Sep 25, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 25, 2026
PedroTadim added a commit that referenced this pull request Sep 25, 2026
Backport #119585 to 26.3: Detach a patch part whose index lost its content to a zeroed block
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #119585 to 26.7: Detach a patch part whose index lost its content to a zeroed block
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants