Skip to content

Refactor VersionMetadata - #92141

Merged
tavplubix merged 6 commits into
ClickHouse:masterfrom
tuanpach:refactor-version-metadata
Apr 16, 2026
Merged

tavplubix merged 6 commits into
ClickHouse:masterfrom
tuanpach:refactor-version-metadata

Conversation

@tuanpach

@tuanpach tuanpach commented Dec 15, 2025 •

Copy link
Copy Markdown
Member

Refactor: Decouple version metadata logic from IMergeTreeDataPart

This PR introduces a class hierarchy for managing transactional version metadata, separating data representation from persistence logic.

Motivation

The old VersionMetadata mixed data storage, business logic, and disk persistence in a single struct. This refactoring creates a clean separation of concerns to enable future extensions (e.g., metadata stored in ZooKeeper for replicated tables).

Architecture Changes

New class hierarchy:

  • VersionInfo - Pure data structure holding transaction IDs, CSNs, and storing version
  • VersionMetadata - Abstract base class with core MVCC logic (visibility, locking, CSN management)
  • VersionMetadataOnDisk - Concrete implementation that persists metadata to txn_version.txt files on disk

Integration with IMergeTreeDataPart:

  • Changed version from value member to std::unique_ptr<VersionMetadata> to enable polymorphism
  • Removed file I/O methods (writeVersionMetadata, loadVersionMetadata, appendCSNToVersionMetadata, etc.)
  • File operations now encapsulated in VersionMetadata and VersionMetadataOnDisk

Key Implementation Details

VersionInfo (new pure data class):

  • Encapsulates creation_tid, removal_tid, creation_csn, removal_csn, and storing_version
  • Provides isVisible logic for MVCC snapshot isolation
  • Implements serialization/deserialization to/from buffers
  • Uses storing_version field for optimistic concurrency control (detect concurrent metadata updates)

VersionMetadata (abstract base class):

  • Implements high-level operations: setAndStoreCreationTID, setAndStoreRemovalTID, setAndStoreCreationCSN, setAndStoreRemovalCSN
  • Provides loadAndAdjustMetadata to recover CSNs from TransactionLog after server restart
  • Uses template method pattern: calls abstract storeInfoImpl, loadMetadata, tryLockRemovalTID, etc.
  • Implements retry logic for version conflicts via updateStoreAndSetMetadataWithRefresh

VersionMetadataOnDisk (disk persistence implementation):

  • Stores metadata in txn_version.txt file within data part directory
  • Uses atomic write protocol: write to .tmp file, then rename
  • Implements deferred persistence optimization: delays writing metadata for non-transactional parts until first transaction touches the part (reduces disk I/O)
  • Manages removal_tid_lock_hash as std::atomic<TIDHash> for lock-free removal locking

Removal TID lock handling (key change):

  • Before: tryLockRemovalTID set both removal_tid_lock AND removal_tid, then appendRemovalTIDToVersionMetadata persisted it
  • After: tryLockRemovalTID only sets removal_tid_lock_hash atomically; removal_tid is set and persisted separately via setAndStoreRemovalTID
  • Rationale: Cleaner separation between in-memory locking and persistent state

Transaction terminology updates:

  • Renamed Tx::PrehistoricTID/Tx::PrehistoricCSN → Tx::NonTransactionalTID/Tx::NonTransactionalCSN for parts created without transactions
  • More accurately reflects that these parts were never involved in transactions, not that they're "ancient"

File Organization

  • src/Interpreters/TransactionVersionMetadata.{cpp,h} deleted
  • src/Interpreters/MergeTreeTransaction/VersionInfo.{cpp,h} added
  • src/Interpreters/MergeTreeTransaction/VersionMetadata.{cpp,h} added
  • src/Interpreters/MergeTreeTransaction/VersionMetadataOnDisk.{cpp,h} added

Testing

Updated existing integration and stateless tests to reflect terminology changes and new metadata validation logic.

Changelog category (leave one):

  • Improvement

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

Refactor MergeTree transaction version metadata management to improve code maintainability and enable future extensions.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.996

@tuanpach tuanpach added the can be tested Allows running workflows for external contributors label Dec 15, 2025
@clickhouse-gh

clickhouse-gh Bot commented Dec 15, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b06d9b3]

Summary: ✅


AI Review

Summary

This PR refactors MergeTree transaction version metadata into VersionInfo / VersionMetadata / VersionMetadataOnDisk, moving persistence and MVCC coordination out of IMergeTreeDataPart. I reviewed the current PR head for correctness, concurrency safety, and ClickHouse-specific invariants. I did not find any new high-confidence issues beyond findings that were already raised inline by clickhouse-gh[bot], so I am not adding duplicate inline comments.

Missing context
  • ⚠️ No fresh CI report/log links were provided in this review task, so runtime validation status could not be cross-checked from Praktika artifacts.
  • ⚠️ No local build directory is present in this workspace, so I could not execute the touched stateless/integration tests here.
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-improvement Pull request with some product improvements label Dec 15, 2025
@tuanpach
tuanpach force-pushed the refactor-version-metadata branch 2 times, most recently from 557eb21 to 780bc5f Compare December 16, 2025 02:27
@tiandiwonder
tiandiwonder requested review from Copilot and tiandiwonder and removed request for Copilot December 22, 2025 01:10

Copilot AI left a comment

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.

Pull request overview

This PR refactors the VersionMetadata class to decouple version logic from IMergeTreeDataPart by introducing a base class (VersionMetadata) and a subclass (VersionMetadataOnDisk) that persists metadata on disk. The refactoring moves transaction version metadata handling from src/Interpreters/TransactionVersionMetadata.{h,cpp} to a new directory structure under src/Interpreters/MergeTreeTransaction/, and introduces VersionInfo to encapsulate version-related data storage and retrieval.

Key changes:

  • Separated removal TID locking logic from removal TID storage
  • Added support for append-mode metadata writing on compatible storage backends
  • Introduced VersionInfo structure for cleaner metadata serialization
  • Updated test assertions to reflect behavioral changes in removal TID handling

Reviewed changes

Copilot reviewed 35 out of 35 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
tests/integration/test_transactions/test.py Refactored test assertions to use a helper function and added detailed comments explaining expected transaction metadata states
src/Storages/System/StorageSystemTransactions.cpp Updated include path for VersionMetadata header
src/Storages/System/StorageSystemParts.cpp Changed from direct member access to getter methods for version metadata fields
src/Storages/StorageReplicatedMergeTree.cpp Updated to use pointer-based access to version metadata
src/Storages/StorageMergeTree.cpp Modified to call storeMetadata instead of storeVersionMetadata
src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp Reorganized includes and updated version metadata access
src/Storages/MergeTree/MutateTask.cpp Updated method calls for storing version metadata
src/Storages/MergeTree/MergedBlockOutputStream.cpp Changed to use new metadata storage API
src/Storages/MergeTree/MergeTreePartsMover.cpp Updated to call loadAndVerifyMetadata instead of loadVersionMetadata
src/Storages/MergeTree/MergeTreeData.{h,cpp} Added friend declarations, removed inline metadata handling logic, delegated to VersionMetadata class methods
src/Storages/MergeTree/IMergeTreeDataPart.{h,cpp} Changed version from value to unique_ptr, removed metadata writing methods, delegated to VersionMetadata
src/Storages/MergeTree/IDataPartStorage.h Added filename parameter to writeTransactionFile method
src/Storages/MergeTree/DataPartsExchange.cpp Updated version metadata access pattern
src/Storages/MergeTree/DataPartStorageOnDiskBase.{h,cpp} Implemented new writeTransactionFile signature, updated file removal references
src/Storages/MergeTree/Compaction/PartsCollectors/MergeTreePartsCollector.cpp Updated to use getter methods for version metadata fields
src/Interpreters/TransactionsInfoLog.cpp Updated include path for VersionMetadata
src/Interpreters/TransactionVersionMetadata.{h,cpp} Deleted original files (moved to new location)
src/Interpreters/TransactionLog.cpp Added support for commit-time requests from transactions
src/Interpreters/QueryLog.cpp Updated include path for VersionMetadata
src/Interpreters/MergeTreeTransaction/VersionMetadataOnDisk.{h,cpp} New subclass implementing disk-based metadata persistence with append support
src/Interpreters/MergeTreeTransaction/VersionMetadata.{h,cpp} New base class containing core version metadata logic
src/Interpreters/MergeTreeTransaction/VersionInfo.{h,cpp} New structure for serializing/deserializing version information
src/Interpreters/MergeTreeTransaction.{h,cpp} Updated to use new metadata API, added request handling on commit
src/Interpreters/FilesystemCacheLog.h Removed unused include
src/Functions/FunctionsTransactionCounters.cpp Updated include path for VersionMetadata
src/CMakeLists.txt Added new object library for MergeTree transaction code
src/Backups/BackupEntryWrappedWith.h Added missing include for SeekableReadBuffer

Comment thread src/Interpreters/MergeTreeTransaction.h Resolved
@tuanpach

tuanpach commented Feb 5, 2026

Copy link
Copy Markdown
Member Author

@tiandiwonder Please help to review this PR.

@tuanpach

tuanpach commented Feb 5, 2026 •

Copy link
Copy Markdown
Member Author
    mutable std::mutex creation_and_removal_tid_mutex;
    /// ID of transaction that has created/is trying to create this object stored in the storage.
    TransactionID creation_tid TSA_GUARDED_BY(creation_and_removal_tid_mutex) = Tx::EmptyTID;
    /// ID of transaction that has removed/is trying to remove this object stored in the storage.
    TransactionID removal_tid TSA_GUARDED_BY(creation_and_removal_tid_mutex) = Tx::EmptyTID;

    /// CSN of the transaction that created this stored in the storage.
    std::atomic<CSN> creation_csn = Tx::UnknownCSN;
    /// CSN of transaction that has removed this object stored in the storage.
    std::atomic<CSN> removal_csn = Tx::UnknownCSN;
Currently, `creation_csn` and `removal_csn` is atomic. I think we can protect them under `creation_and_removal_tid_mutex`. So the update of these info is atomic.

@tuanpach
tuanpach force-pushed the refactor-version-metadata branch 5 times, most recently from 8e3c0fc to c045716 Compare February 14, 2026 14:48
@alexey-milovidov

Copy link
Copy Markdown
Member

The changelog entry is missing (still ...). The selected category "Improvement" requires one.

@tuanpach

Copy link
Copy Markdown
Member Author

The changelog entry is missing (still ...). The selected category "Improvement" requires one.

Updated

@tuanpach
tuanpach force-pushed the refactor-version-metadata branch from c045716 to f16fa02 Compare February 16, 2026 00:19
tuanpach and others added 3 commits April 16, 2026 01:47
The stateless test CI job "ParallelReplicas, s3 storage" runs with
`max_parallel_replicas=10` and a 3-node cluster. Under this configuration,
`SELECT count() FROM t` is distributed across all 3 replica nodes.

Transaction context (including `SET TRANSACTION SNAPSHOT`) is not propagated
to remote parallel-replica workers. Consequently, each remote worker reads
all parts without the snapshot restriction:

- `rows_at_snapshot_1`: initiator sees 2 (snapshot=1), 2 remotes see 3 each → 2+3+3=8 (expected 2)
- `rows_in_txn_before_drop`: all 3 workers see 4 rows → 4+4+4=12 (expected 4)

Fix: add `no-parallel-replicas` tag to both tests so they are skipped in
the ParallelReplicas CI run. Transaction-snapshot isolation cannot be tested
correctly when queries are fanned out to replica workers that lack the
originating transaction's context.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@tuanpach
tuanpach force-pushed the refactor-version-metadata branch from 7f8a27a to b06d9b3 Compare April 16, 2026 02:51
@clickhouse-gh

clickhouse-gh Bot commented Apr 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 90.90% 90.90% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 75.02% (772/1029) | lost baseline coverage: 108 line(s) · Uncovered code

Full report · Diff report

@tavplubix
tavplubix added this pull request to the merge queue Apr 16, 2026
Merged via the queue into ClickHouse:master with commit f2f8540 Apr 16, 2026
161 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 Apr 16, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 16, 2026
Tests `04057_transaction_version_metadata_lifecycle` and
`04060_transaction_snapshot_visibility` (introduced by PR ClickHouse#92141) use
INSERT inside BEGIN TRANSACTION. Async inserts inside transactions are
NOT_IMPLEMENTED, so these tests fail 100% of the time on the AsyncInsert
CI configuration. The existing transaction tests (01172, 01173, etc.)
are already in the blacklist — these two were missed.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@azat

azat commented Apr 17, 2026

Copy link
Copy Markdown
Member

@tuanpach This is backward incompatible change since it changes the format of metadata - adding storing_version:, right?
And hence the upgrade check fails - https://pastila.nl/?00781ae3/b428915e6cd3905a46534966e419f9a5#4P2dM9LRP6DlE5rlHTPLxg==GCM

Is it hard to make it compatible?

@tuanpach

Copy link
Copy Markdown
Member Author

@tuanpach This is backward incompatible change since it changes the format of metadata - adding storing_version:, right? And hence the upgrade check fails - https://pastila.nl/?00781ae3/b428915e6cd3905a46534966e419f9a5#4P2dM9LRP6DlE5rlHTPLxg==GCM

Not only storing_version. The old format can have a duplicated field (e.g, two removal_csn) because append is used. The new format does not use append, so the metadata doesn't have duplicated fields.

Is it hard to make it compatible?

It can be done, not too hard. We need to detach the old format and convert it to the new one. But this is an experimental feature. Is it necessary?

@tavplubix

Copy link
Copy Markdown
Member

It's not necessary, we can break compatibility of experimental features. But we need to suppress the failure

@tuanpach

Copy link
Copy Markdown
Member Author

It's not necessary, we can break compatibility of experimental features. But we need to suppress the failure

It makes sense. I will update the parsing logic to avoid throwing an exception in that case.

@tuanpach

Copy link
Copy Markdown
Member Author

Updated it here: #103031

@azat

azat commented Apr 17, 2026

Copy link
Copy Markdown
Member

@tuanpach

Copy link
Copy Markdown
Member Author

@tuanpach I also find this logs too noisy - https://pastila.nl/?0018d7ff/70b402a436870f5f3a2a40c28adaa13e#X3xfZCboT+I/B2LhIdxGmw==GCM

Is it ok to make them LOG_TEST?

I will do it.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 18, 2026
Regression from ClickHouse#92141: server aborts with signal 6 during `loadDataPart`
in debug and sanitizer builds when a part directory contains a leftover
`txn_version.txt.tmp` file with no corresponding `txn_version.txt`. This
state is produced by `VersionMetadataOnDisk::loadMetadata` case 2 (an
incomplete write that was not atomically renamed). It returns a
`VersionInfo` with `creation_tid = Tx::DummyTID` and
`creation_csn = Tx::RolledBackCSN`.

`Tx::DummyTID = {NonTransactionalCSN, DummyLocalTID, Nil} = {1, 2, Nil}`
has `start_csn == NonTransactionalCSN` but `local_tid == DummyLocalTID`
— which fails the invariant asserted in `TransactionID::isNonTransactional`.
The new `VersionMetadata::validateInfo` (added by ClickHouse#92141) and
`VersionInfo::wasInvolvedInTransaction` both call `isNonTransactional` on
the loaded `creation_tid`, so the assertion aborts the server.

Two changes:
- `TransactionID::isNonTransactional`: widen the assertion to allow the
  `DummyTID` special case. The function still correctly returns `false`
  for `DummyTID` because `local_tid == DummyLocalTID != NonTransactionalLocalTID`.
- `VersionMetadata::validateInfo`: early-return for rolled-back parts
  (`creation_csn == RolledBackCSN`). Such parts are marked `Outdated`
  immediately after loading by `MergeTreeData::loadDataPart` and cleaned
  up, so the live-part invariants validated here do not apply.

CI reports showing the crash:
- PR ClickHouse#103047: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103047&sha=ec0124d77b94c97a4b1b48049b0215b1dddb94a5&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29
- PR ClickHouse#102961: same `Stateless tests (amd_debug, distributed plan, s3 storage, parallel)` check

Regression test `04104_transaction_version_metadata_dummy_tid_load.sh`
deterministically creates the scenario by dropping a bogus
`txn_version.txt.tmp` into a part directory and running `DETACH` +
`ATTACH`. Before the fix the server aborts with signal 6 at
`TransactionID.h:90`; after the fix the rolled-back part is marked
`Outdated` and invisible.

Session: cron:clickhouse-ci-task-worker:20260418-221500
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request May 25, 2026
After ClickHouse#92141 refactored version metadata to use atomic tmp+rename writes
instead of `WriteMode::Append`, the race that previously corrupted
`txn_version.txt` on encrypted disks (see ClickHouse#59898 discussion) is no longer
possible: concurrent `creation_csn` and `removal_tid` updates can no longer
interleave inside the encrypted append path.

Install `transactions.xml` in encrypted-storage CI jobs and drop the
`no-encrypted-storage` tag from transaction-related stateless tests.
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-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.

7 participants