Skip to content

Fix flaky 03752_attach_as_replicated_transaction_metadata on object storage - #103599

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-03752-attach-as-replicated-flake
Apr 28, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-03752-attach-as-replicated-flake

Conversation

@groeneai

@groeneai groeneai commented Apr 27, 2026 •

Copy link
Copy Markdown
Collaborator

Fix flakiness in 03752_attach_as_replicated_transaction_metadata (test2) on object-storage CI configurations. Requested by @alexey-milovidov on #100976 (comment).

Failure mode

CI failure (Stateless tests (amd_debug, distributed plan, s3 storage, parallel) on PR #100976, 2026-04-27):

Code: 341. DB::Exception: Exception happened during execution of mutation
'mutation_8.txt' with part 'all_1_7_1' reason:
'Code: 107. Can't create hardlink for file
store/52b/52b157be-f5de-4174-aae2-da7e2bd450c0/all_1_7_1/txn_version.txt.tmp:
While committing metadata operation #0. (FILE_DOESNT_EXIST)'

The failing query is DELETE FROM t0 WHERE TRUE; in test2, which spawns a mutation. On object storage the mutation's part-clone goes through DataPartStorageOnDiskBase::freeze → Backup → queued createHardLink operations on an external metadata transaction (committed later, in MetadataOperationsHolder::commit).

Test2 inserts 6 active blocks (plus a rolled-back transactional one). A background merge of those source parts runs concurrently with the subsequent DELETE mutation. The merge writes a transient txn_version.txt.tmp on the merged part during VersionMetadataOnDisk::storeInfoToDataPartStorage (two-phase write: createFile(*.tmp) → writeFile(*.tmp) → replaceFile(*.tmp -> txn_version.txt)).

If the mutation iterates the merged part's directory while txn_version.txt.tmp exists, it queues a hardlink operation for that file. By the time the queued op is committed, the rename has completed, the source .tmp is gone, and CreateHardlinkOperation::execute fails:

auto object_metadata = tryReadMetadataFile(compatible_key_prefix, path_from, disk);
if (!object_metadata.has_value())
    throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "Can't create hardlink for file {}", path_from);

(src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDiskTransactionOperations.cpp:368)

CIDB confirms 4 hits in 30 days across 4 unrelated PRs, three of which are on object-storage configurations (s3 storage, azure).

Fix

Force the merge to complete deterministically before the DELETE mutation runs:

BEGIN TRANSACTION;
OPTIMIZE TABLE t0 FINAL;
COMMIT;
DELETE FROM t0 WHERE TRUE;

OPTIMIZE FINAL is synchronous, so when COMMIT returns the merged part's txn_version.txt is fully stable (no transient .tmp). After it, only one active part remains, so no further background merges can be scheduled before the mutation. The merge has to run inside a transaction because the table already has transactions used on it (BEGIN TRANSACTION ... ROLLBACK above) and a non-transactional merge is rejected with Cancelling merge ... transactions were enabled for this table (MergeTreeDataMergerMutator::renameMergedTemporaryPart).

Only test2 is changed; test1 and test3 only insert two parts each, so they are not exposed to this race in practice.

The output of all three tests is unchanged (SELECT COUNT(*) returns 0, 0, 418 as before), so .reference does not need updating.

Verification

  • tests/clickhouse-test --test-runs 50 03752_attach_as_replicated_transaction_metadata → 50/50 passes (61s) on debug local-disk build.
  • Reasoning above explains why the queued-hardlink commit failure can no longer occur after the merged part's metadata is fully stable.

Note on the underlying race

The deeper bug — that Backup queues hardlinks for transient *.tmp files which can disappear before the queued op is committed on object storage — exists in src/Storages/MergeTree/Backup.cpp (no filter for transient version-metadata files) and src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp (post-Backup cleanup removes txn_version.txt from the destination but not txn_version.txt.tmp). Other tests/code paths could theoretically hit the same race. That's worth a separate, source-side fix; this PR only stabilizes the test as requested.

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):

NO ENTRY

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100976&sha=49f741a8f4d15de6fdbb6d32fc9d996694fa1799&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29

Version info

  • Merged into: 26.5.1.149

…torage

Test2 of 03752_attach_as_replicated_transaction_metadata was racy on object
storage. After 6 active inserts, a background merge of the source parts could
run concurrently with the `DELETE FROM t0 WHERE TRUE` mutation that follows.

The merge writes a transient `txn_version.txt.tmp` on the resulting merged
part during `storeInfoToDataPartStorage` (two-phase write: create `.tmp` →
rename to `txn_version.txt`). On object storage the mutation's clone uses an
external metadata transaction, so the queued `createHardLink` for that `.tmp`
file is not committed until later — by which time the rename has completed,
the source `.tmp` is gone, and the mutation fails with:

    Code: 107. Can't create hardlink for file
    store/.../all_1_7_1/txn_version.txt.tmp:
    While committing metadata operation #0. (FILE_DOESNT_EXIST)

Force the merge to complete deterministically before the mutation runs:
`OPTIMIZE TABLE t0 FINAL` is synchronous, so when `COMMIT` returns the merged
part's metadata is fully stable. After it, only one active part remains, so no
further background merges can be scheduled before the mutation. The merge has
to run inside a transaction because the table already had transactions used
on it (`BEGIN TRANSACTION ... ROLLBACK` above) and a non-transactional merge
is rejected with `Cancelling merge ... transactions were enabled for this
table`.

Test1 and test3 only insert two parts each, so they are not exposed to this
race in practice and are left unchanged. The output of all three tests is
unchanged (`SELECT COUNT(*)` returns the same values), so the `.reference`
file does not need updating.

Verified locally with `--test-runs 50` (50/50 passes; runs took 61s).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100976&sha=49f741a8f4d15de6fdbb6d32fc9d996694fa1799&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29
PR: ClickHouse#100976
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Partial — the original race is rare (4 hits / 30 days on object-storage configs) and I do not have a deterministic on-demand repro. I have a deterministic understanding of the mechanism (mutation clone iterates source files while a background merge's txn_version.txt.tmp is in flight; the queued hardlink commits after the rename completes and fails with FILE_DOESNT_EXIST).
b Root cause explained? Yes — the merge calls VersionMetadataOnDisk::storeInfoToDataPartStorage which writes txn_version.txt.tmp then renames it to txn_version.txt. On object storage, the mutation's Backup queues createHardLink operations on a MetadataOperationsHolder; commit happens after Backup returns. If iteration captured the .tmp and the rename then completes, CreateHardlinkOperation::execute calls tryReadMetadataFile which returns nullopt and throws FILE_DOESNT_EXIST (MetadataStorageFromDiskTransactionOperations.cpp:368).
c Fix matches root cause? Yes — BEGIN TRANSACTION; OPTIMIZE FINAL; COMMIT; makes the merge synchronous and fully committed; after it, only one active part remains so no further background merges can race with the subsequent DELETE mutation. The transient .tmp no longer exists when the mutation iterates the source.
d Test intent preserved? Yes — test2 still tests "ATTACH AS REPLICATED with mixed transactional history": rolled-back transactional insert, multiple non-transactional inserts, the merged result, the DELETE mutation, and the ATTACH AS REPLICATED/AS NOT REPLICATED cycle. Output is unchanged (SELECT COUNT(*) still returns 0), .reference does not need updating.
e Both directions demonstrated? Without fix: CIDB shows 4 PR-run failures in 30 days (3 on object-storage configs: s3 storage ×2, azure). With fix: local --test-runs 50 → 50/50 passes (debug local-disk build, 61s). I do not have an S3 reproduction loop here; the fix's correctness is established by the mechanism analysis above (closing the merge → mutation handoff window).
f Fix is general, not a narrow patch? This is intentionally a narrow test-only patch as requested. The underlying Backup.cpp/DataPartStorageOnDiskBase.cpp race (no filter for transient *.tmp files in the iteration; post-Backup cleanup removes only txn_version.txt, not .tmp) is documented in the PR body as a follow-up worth a separate source-side fix.

Session: cron:clickhouse-ci-task-worker:20260427-081500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alexey-milovidov — could you review this? Test-only fix for 03752_attach_as_replicated_transaction_metadata that forces the merge in test2 to complete inside a transaction (BEGIN TRANSACTION; OPTIMIZE FINAL; COMMIT;) before the DELETE mutation runs, eliminating the race where the mutation's queued createHardLink for a transient txn_version.txt.tmp is committed after the merge's atomic rename and fails with FILE_DOESNT_EXIST on object storage.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a2f8d9a]

Summary: ✅


AI Review

Summary

This PR stabilizes 03752_attach_as_replicated_transaction_metadata by forcing a deterministic merge (BEGIN TRANSACTION + OPTIMIZE TABLE ... FINAL + COMMIT) before the DELETE mutation in test2, which addresses the described object-storage timing race in CI. The change is narrowly scoped to one stateless test and looks correct.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 27, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

This is quite complex, but ok to stabilize the test for low-priority features (transactions and attach as replicated).

@alexey-milovidov alexey-milovidov self-assigned this Apr 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 28, 2026
Merged via the queue into ClickHouse:master with commit cd197ee Apr 28, 2026
165 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 28, 2026
@groeneai groeneai mentioned this pull request Apr 29, 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 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.

3 participants