Skip to content

Fix ATTACH AS REPLICATED discarding committed data via stale txn_version.txt.tmp - #108772

Merged
alexey-milovidov merged 8 commits into
masterfrom
fix-attach-as-replicated-tmp-txn-version
Jul 6, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
fix-attach-as-replicated-tmp-txn-version

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

ATTACH TABLE ... AS REPLICATED could discard committed data and resurrect pre-mutation rows when a stale txn_version.txt.tmp was left on a part.

InterpreterCreateQuery::clearTransactionMetadata (run by the conversion) removed only txn_version.txt, leaving any txn_version.txt.tmp behind. A .tmp can legitimately linger on a part: when a mutation clones its source part by hardlinking, a transient .tmp written by an in-flight merge (in storeInfoToDataPartStorage) can be hardlinked onto the mutated part, and on object storage the queued hardlink is committed after the rename. With txn_version.txt removed but the .tmp still present, VersionMetadataOnDisk::loadMetadata treats the part as a rolled-back transaction (creation_tid == Tx::DummyTID, creation_csn == Tx::RolledBackCSN), so it is marked Outdated and discarded. The pre-mutation part is then loaded as active instead.

This is what made 03752_attach_as_replicated_transaction_metadata flaky on Stateless tests (amd_debug, distributed plan, s3 storage, parallel): after a fault-injected merge commit left a .tmp on the mutated part, SELECT count() returned the pre-DELETE count (1271) instead of 0, and the load logged a found file txn_version.txt.tmp warning.

Fix: clearTransactionMetadata now removes both txn_version.txt and txn_version.txt.tmp, so every part loads as plain committed data after the conversion. The temporary file name is promoted to a shared constant VersionMetadata::TMP_TXN_VERSION_METADATA_FILE_NAME. A deterministic regression test injects a stale txn_version.txt.tmp into a part and asserts the row survives ATTACH AS REPLICATED (it fails with count 0 before the fix, passes with count 1 after).

The affected ATTACH AS REPLICATED code path is new and not in a stable release, so this is filed as a CI fix.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=7dda23a8ec1552f04de5601a1fe59708a5406ee1&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.540 (included in 26.7 and later)

…ion.txt.tmp

`InterpreterCreateQuery::clearTransactionMetadata`, run by
`ATTACH TABLE ... AS REPLICATED`, removed only `txn_version.txt` from each
part, leaving any `txn_version.txt.tmp` behind.

A `txn_version.txt.tmp` can legitimately linger on a part: when a mutation
clones its source part by hardlinking, a transient `.tmp` written by an
in-flight merge (during `storeInfoToDataPartStorage`) can be hardlinked onto
the mutated part, and on object storage the queued hardlink is committed after
the rename. With `txn_version.txt` removed but the `.tmp` still present,
`VersionMetadataOnDisk::loadMetadata` treats the part as a rolled-back
transaction (`creation_tid == Tx::DummyTID`, `creation_csn == Tx::RolledBackCSN`),
so it is marked `Outdated` and discarded. The pre-mutation part is then loaded
as active instead, resurrecting deleted data.

This is exactly what made `03752_attach_as_replicated_transaction_metadata`
flaky: after a fault-injected merge commit left a `.tmp` on the mutated part,
`SELECT count()` returned the pre-`DELETE` count (1271) instead of 0, and the
load logged a `found file txn_version.txt.tmp` warning.

Fix: `clearTransactionMetadata` now removes both `txn_version.txt` and
`txn_version.txt.tmp`, so every part loads as plain committed data after the
conversion. The temporary file name is promoted to a shared constant
`VersionMetadata::TMP_TXN_VERSION_METADATA_FILE_NAME`.

Add a deterministic regression test that injects a stale `txn_version.txt.tmp`
into a part and asserts the row survives `ATTACH AS REPLICATED`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=7dda23a8ec1552f04de5601a1fe59708a5406ee1&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29

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

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eafdde8]

Summary: ✅


AI Review

Summary

This PR fixes stale txn_version.txt.tmp handling for ATTACH TABLE ... AS REPLICATED and the related part metadata stripping paths. The prior inline findings about incomplete cleanup coverage and fail-closed removal ordering are addressed in the current code, and I found no remaining blocker or major issue in the changed paths.

Final Verdict

✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 28, 2026
alexey-milovidov and others added 4 commits June 29, 2026 19:51
Master gained several 04416_* tests since this branch was created, so the
existing regression test is renumbered to the next free number (highest was
04488).
…g paths

The previous commit promoted the temporary version file to the shared constant
`VersionMetadata::TMP_TXN_VERSION_METADATA_FILE_NAME` but only handled it in
`InterpreterCreateQuery::clearTransactionMetadata` (the `ATTACH AS REPLICATED`
conversion). Every other path that strips, skips, or removes transaction
metadata still handled only `txn_version.txt`, so the same stale-`.tmp` state
could resurface there.

A part with a stale `txn_version.txt.tmp` but no `txn_version.txt` is read by
`VersionMetadataOnDisk::loadMetadata` as a rolled-back transaction
(`creation_tid == Tx::DummyTID`, `creation_csn == Tx::RolledBackCSN`); since
`DummyTID` is not non-transactional, `wasInvolvedInTransaction` is true and
`MergeTreeData::loadDataPart` marks the part `Outdated` and discards it,
silently losing committed data. The most direct case is
`ALTER TABLE ... ATTACH PART`: it strips the main file
(`MergeTreeData::loadPartAndFixMetadataImpl` -> `removeVersionMetadata`) and
reloads, but a leftover `.tmp` survives and gets the part discarded on the next
full table load.

Clear the temporary file together with the main file in every such path:
- `IMergeTreeDataPart::removeVersionMetadata` (used by `ATTACH PART` reload),
- the `ATTACH PART` pre-load strip in `MergeTreeData::tryLoadPartsToAttach`,
- the backup-restore copy filter in `MergeTreeData::restorePartFromBackup`,
- `DataPartStorageOnDiskBase::freeze` / `freezeRemote` after cloning,
- `DataPartStorageOnDiskBase::clearDirectory` (also avoids the slow recursive
  removal fallback on a non-empty directory).

The hardlink-tracking exclusions in `MergeTreeData::cloneAndLoadDataPart` are
left as-is: the destination part writes its own fresh `txn_version.txt` via
`setAndStoreCreationTID`, so it loads as committed regardless of a hardlinked
stale `.tmp` (which `loadMetadata` removes on load).

Add a deterministic regression test (04490) that injects a stale
`txn_version.txt.tmp` into a detached part, runs `ATTACH PART`, then forces a
full reload and asserts the committed row survives (count 1, not 0). Verified
against the pre-fix binary: the row is lost (count 0) without this fix.

Addresses the AI review "Request changes" finding on
#108772

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=7dda23a8ec1552f04de5601a1fe59708a5406ee1&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29

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

Copy link
Copy Markdown
Member Author

Merged the latest master into the branch (it was 161 commits behind and the only red checks were a known flake). The merge was clean — master had not touched any of the seven source files this PR changes since the merge-base, so the net diff is unchanged (11 files, +187/-7). The two new tests 04489_attach_as_replicated_clears_tmp_txn_version and 04490_attach_part_clears_tmp_txn_version do not collide with anything on master, and all five changed translation units pass -fsyntax-only against the merged tree.

The only failing CI checks were Stress test (amd_tsan) and Stress test (arm_tsan), both failing on Hung check failed, possible deadlock found — the chronic master-wide flake the CI bot itself attributes to #107941 (the query confirms it reproduces on master with pull_request_number = 0). It is unrelated to this change. No unresolved review threads remain, and the AI Review verdict is ✅ Approve.

…irst

Address the AI Review blocker: every path that strips transaction metadata
from a part removed `txn_version.txt` before `txn_version.txt.tmp`. If the
main-file removal succeeded and the subsequent `.tmp` removal then threw (for
example a transient object-storage error), the part was left in exactly the
data-discarding state this PR fixes: no `txn_version.txt` and a stale
`txn_version.txt.tmp`, which `VersionMetadataOnDisk::loadMetadata` reads as a
rolled-back transaction (`creation_csn == Tx::RolledBackCSN`), so the part is
marked `Outdated` and committed data is discarded.

Reorder the removals so the temporary file is deleted before the main file in
`InterpreterCreateQuery::clearTransactionMetadata`,
`IMergeTreeDataPart::removeVersionMetadata`,
`MergeTreeData::tryLoadPartsToAttach`, and both branches of
`DataPartStorageOnDiskBase::freeze` and `freezeRemote`. A failure between the
two removals now leaves a valid `txn_version.txt` (still a committed part) and
the operation stays retryable.

`DataPartStorageOnDiskBase::clearDirectory` is left unchanged: it removes the
entire part directory (with a recursive-removal fallback on any failure), so no
re-loadable tmp-only state can persist there. `restorePartFromBackup` only
filters file names while copying and performs no removal, so ordering does not
apply.

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

Copy link
Copy Markdown
Member Author

Addressed the AI Review ❌ Block (commit 67705ca). The blocker was a fail-close ordering issue: every path that strips transaction metadata removed txn_version.txt before txn_version.txt.tmp, so if the main-file removal succeeded and the .tmp removal then threw, the part was left in exactly the data-discarding state this PR fixes (no txn_version.txt, stale txn_version.txt.tmp → read as Tx::RolledBackCSN by VersionMetadataOnDisk::loadMetadata → marked Outdated). Reordered so the temporary file is removed first in clearTransactionMetadata, IMergeTreeDataPart::removeVersionMetadata, MergeTreeData::tryLoadPartsToAttach, and both branches of DataPartStorageOnDiskBase::freeze and freezeRemote; a failure between the two removals now leaves a valid txn_version.txt and the operation stays retryable. clearDirectory (removes the whole part directory, recursive-removal fallback) and restorePartFromBackup (name filter only, no removal) need no reordering. All four changed translation units pass -fsyntax-only.

CI triage of the remaining red checks — all unrelated to this change:

  • Stateless tests (amd_tsan, parallel, 1/2) → 01600_quota_by_prefix_forwarded_ip: a transient stderr-noise flake on a recently-added test in an unrelated subsystem (quota-by-IP). The test produced fully correct output; the failure was classified having stderror because a <Warning> QuotaCache: Re-chose quotas for 7 enabled set(s) over 2 quotas in 1317 ms leaked into stderr under the loaded runner. CI's own randomized-settings diagnosis re-ran it 6 times → 6/6 passed (The failure is not reproducible (likely a transient issue)). Not reproducible on master (pull_request_number = 0, 0 failures in 90 days).
  • Stress test (amd_tsan) / Stress test (arm_tsan) → Hung check failed, possible deadlock found: the chronic master-wide flake the CI bot itself attributes to Hung check failed, possible deadlock found #107941. The hung stacks are in executeASTFuzzerQueries / QueryAnalysisPass::run / TCPHandler::runImpl with zero frames from this PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for the latest report (commit 67705ca1) — all four red checks are unrelated, pre-existing master-wide flakes, none touched by this change:

  • Stateless tests (arm_binary, parallel) → 04093_msan_fiber_distributed_false_positive: the distributed-query handshake desync Unexpected packet from server 127.0.0.2:9000 (expected TablesStatusResponse, got ProfileInfo) (UNEXPECTED_PACKET_FROM_SERVER). Tracked by Fix flaky distributed query "Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)" #108854 ("Fix flaky distributed query …"), still open; CIDB shows 7 unrelated PRs hitting it on 2026-06-30 alone (108004, 100365, 108728, 108345, 107532, 108556, …). Unrelated to txn_version metadata.

  • Stress test (amd_tsan) / Stress test (arm_tsan) → Hung check failed, possible deadlock found: the chronic master-wide hang the CI bot itself attributes to Hung check failed, possible deadlock found #107941. The hung stacks are all in executeASTFuzzerQueries / QueryAnalysisPass::run / TCPHandler::runImpl with zero frames from any file this PR touches.

  • Upgrade check (amd_release) → Error message in clickhouse-server.log: a MutatePlainMergeTreeTask logging Code: 395 … FUNCTION_THROW_IF_VALUE_IS_NON_ZERO for the expression if(1, _CAST(plus(x, throwIf(1)), 'UInt64'), x). This is the well-known upgrade-check false positive produced by a stateless test that issues a deliberately-failing throwIf mutation (the … + throwIf(1) WHERE 1 pattern, e.g. 02597_column_update_tricky_expression_and_replication): the background mutation retries around the upgrade restart and leaves its expected error in the log. CIDB confirms it as a wide flake — 11 unrelated PRs hit the identical throwIf upgrade-log error on 2026-06-30 (108833, 108887, 108554, 108070, 86768, 107983, 108886, 79091, 108049, 108100, plus this one), spanning completely unrelated subsystems. This PR adds no throwIf mutation and does not touch mutation execution.

The reds could not be re-run yet because the workflow run is still in_progress (gh run rerun … cannot be rerun; This workflow is already running); they should be retried once it finishes. No re-merge: the merge-base is from earlier today (2026-06-30 04:43), the net diff is unchanged from the already-reviewed state, and every red also fails on master, so merging would only add churn.

AI Review verdict on the current commit is ✅ Approve and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The workflow run `28458592657` finished (completed/failure at 20:30Z), so I re-triggered its four failed jobs with gh run rerun --failed — they were the reruns that could not be started earlier while the run was still in_progress.

All four reds are the pre-existing, master-wide flakes already triaged above and are categorically unrelated to this change (the PR touches only txn_version metadata cleanup paths and adds two stateless tests — no distributed-query handshake, AST-fuzzer, or mutation-execution code):

No re-merge (merge-base is from earlier today and master has not touched any of the seven changed source files since then). AI Review verdict is ✅ Approve and there are no unresolved review threads.

alexey-milovidov and others added 2 commits July 1, 2026 02:31
Merging the latest `master` (610 commits) brought in tests that reused
numbers `04489` (`04489_max_threads_auto_parsing_compat`) and `04490`
(`04490_dict_get_keys_float_signed_zero_consistency`,
`04490_table_readonly_partition_commands`), colliding with this PR's
`04489_attach_as_replicated_clears_tmp_txn_version` and
`04490_attach_part_clears_tmp_txn_version`.

Renumber the two regression tests to the next free numbers `04492` and
`04493`. The tests use fixed table names and contain no internal
references to their own number, so only the file names change.

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

Copy link
Copy Markdown
Member Author

Re-merged the latest master (the branch was 610 commits behind) and renumbered the two regression tests to resolve a test-number collision it surfaced.

  • Collision: since the previous merge, master reused numbers 04489 (04489_max_threads_auto_parsing_compat) and 04490 (04490_dict_get_keys_float_signed_zero_consistency, 04490_table_readonly_partition_commands), which clashed with this PR's 04489_attach_as_replicated_clears_tmp_txn_version and 04490_attach_part_clears_tmp_txn_version. Renamed them to the next free numbers 04492/04493. The tests use fixed table names and carry no internal references to their own number, so only the file names changed.
  • Merge: clean. The only source file master touched since the merge-base that this PR also edits is MergeTreeData.cpp (44 commits); the PR's additions there sit in unchanged surrounding context, and MergeTreeData.cpp passes -fsyntax-only against the merged tree. The net diff is otherwise unchanged (7 source files, 2 tests).

New head is eafdde86c66; a fresh CI run will start on it. The only red checks on the previous commit were Stress test (amd_tsan) / Stress test (arm_tsan) failing on Hung check failed, possible deadlock found — the chronic master-wide flake the CI bot attributes to #107941 (hung stacks in executeASTFuzzerQueries / TCPHandler::runImpl, no txn_version frames), unrelated to this change. No unresolved review threads; AI Review verdict is ✅ Approve.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.40% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 40/51 (78.43%) · Uncovered code

Full report · Diff 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.

Yes, sounds reasonable.

@alexey-milovidov alexey-milovidov self-assigned this Jul 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 6, 2026
Merged via the queue into master with commit 0386e6e Jul 6, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-attach-as-replicated-tmp-txn-version branch July 6, 2026 01:12
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 6, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…g paths

The previous commit promoted the temporary version file to the shared constant
`VersionMetadata::TMP_TXN_VERSION_METADATA_FILE_NAME` but only handled it in
`InterpreterCreateQuery::clearTransactionMetadata` (the `ATTACH AS REPLICATED`
conversion). Every other path that strips, skips, or removes transaction
metadata still handled only `txn_version.txt`, so the same stale-`.tmp` state
could resurface there.

A part with a stale `txn_version.txt.tmp` but no `txn_version.txt` is read by
`VersionMetadataOnDisk::loadMetadata` as a rolled-back transaction
(`creation_tid == Tx::DummyTID`, `creation_csn == Tx::RolledBackCSN`); since
`DummyTID` is not non-transactional, `wasInvolvedInTransaction` is true and
`MergeTreeData::loadDataPart` marks the part `Outdated` and discards it,
silently losing committed data. The most direct case is
`ALTER TABLE ... ATTACH PART`: it strips the main file
(`MergeTreeData::loadPartAndFixMetadataImpl` -> `removeVersionMetadata`) and
reloads, but a leftover `.tmp` survives and gets the part discarded on the next
full table load.

Clear the temporary file together with the main file in every such path:
- `IMergeTreeDataPart::removeVersionMetadata` (used by `ATTACH PART` reload),
- the `ATTACH PART` pre-load strip in `MergeTreeData::tryLoadPartsToAttach`,
- the backup-restore copy filter in `MergeTreeData::restorePartFromBackup`,
- `DataPartStorageOnDiskBase::freeze` / `freezeRemote` after cloning,
- `DataPartStorageOnDiskBase::clearDirectory` (also avoids the slow recursive
  removal fallback on a non-empty directory).

The hardlink-tracking exclusions in `MergeTreeData::cloneAndLoadDataPart` are
left as-is: the destination part writes its own fresh `txn_version.txt` via
`setAndStoreCreationTID`, so it loads as committed regardless of a hardlinked
stale `.tmp` (which `loadMetadata` removes on load).

Add a deterministic regression test (04490) that injects a stale
`txn_version.txt.tmp` into a detached part, runs `ATTACH PART`, then forces a
full reload and asserts the committed row survives (count 1, not 0). Verified
against the pre-fix binary: the row is lost (count 0) without this fix.

Addresses the AI review "Request changes" finding on
ClickHouse#108772

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=7dda23a8ec1552f04de5601a1fe59708a5406ee1&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…plicated-tmp-txn-version

Fix ATTACH AS REPLICATED discarding committed data via stale txn_version.txt.tmp
yariks5s pushed a commit to ylw510/ClickHouse that referenced this pull request Oct 22, 2026
`MutateSomePartColumnsTask` hardlinks every file of the source part that is
not in `collectFilesToSkip`. That set took `txn_version.txt` from
`getFileNamesWithoutChecksums`, which lists it only if it exists at that
moment, and never contained `txn_version.txt.tmp`. When the source part's
version metadata is rewritten concurrently (a commit stamping its creation CSN,
e.g. a background merge transaction finalized by the TransactionLog updating
thread), `VersionMetadataOnDisk::storeInfoToDataPartStorage` writes
`txn_version.txt.tmp` and then renames it over `txn_version.txt`, and the
mutation copies the transient file:

- on a local disk the mutated part keeps a `.tmp` with the source part's
  version info and no `txn_version.txt`, so on the next load
  `VersionMetadataOnDisk::loadMetadata` treats it as rolled back and the
  part's rows disappear (the source part is already removed);
- on object storage the hardlink is deferred to the disk transaction commit,
  and if the rename happened first the mutation fails with
  `Can't create hardlink for file .../txn_version.txt.tmp (FILE_DOESNT_EXIST)`.

The new part always writes its own version metadata, so skip both files by
name. ClickHouse#108772 made the consumers tolerate a stray `.tmp`; this closes the
producer.

This is the failure of `03752_attach_as_replicated_transaction_metadata` on
`Stateless tests (amd_debug, distributed plan, s3 storage, parallel)`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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.

2 participants