Skip to content

Split TransactionLog into TransactionManager, TransactionLog and TransactionSession - #117822

Merged
tuanpach merged 12 commits into
ClickHouse:masterfrom
tuanpach:sync-transaction-manager
Sep 18, 2026
Merged

tuanpach merged 12 commits into
ClickHouse:masterfrom
tuanpach:sync-transaction-manager

Conversation

@tuanpach

@tuanpach tuanpach commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

TransactionLog carried three unrelated responsibilities: the singleton lifecycle and its Keeper handle, the CSN log with its mirror and cleanup, and the per-replica session identity. This splits them into four units:

  • TransactionManager — singleton lifecycle, Keeper handle, worker thread.
  • TransactionLog — the CSN log, its local mirror and its cleanup.
  • TransactionSession — session identity, peer liveness, invalid TIDs.
  • TransactionPayloads — the Keeper payload types and their serialization.

TransactionManager becomes the entry point, so callers of the old TransactionLog statics move over to it.

Two fixes come along with the split, both in CSN log node names:

  • serializeCSN no longer goes through zkutil::getSequentialNodeName, which assumes Int32 and underflows its padding. The Keeper sequential counter is int64_t, so names grow past ten digits and stop being order-comparable as strings.
  • reloadCSNLogs orders entries by CSN rather than by node name, and fences itself with a sync pipelined into the read, because a full reload is published unconditionally and a trailing node would otherwise move latest_snapshot backwards.

The parts that depend on SharedMergeTree and VersionMetadataOnKeeper sit behind #if CLICKHOUSE_CLOUD and are not built here.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2b892e3]

Summary: ✅


AI Review

Summary

This PR splits the transaction code into TransactionManager, TransactionLog, and TransactionSession, adds session_node_version to transaction identities, and changes log cleanup to use per-replica tail pointers. The refactor is not review-ready yet: current HEAD still introduces persistence and SQL compatibility breaks, and it leaves several correctness holes around stale sessions, unknown-state finalization, startup part loading, and transactional mutation recovery.

PR Metadata
  • Changelog category is incorrect. Not for changelog does not fit a PR that changes the public TransactionID tuple shape and adds new Keeper requirements on startup/load paths.
  • Exact replacement text:
### Changelog category (leave one):
- Backward Incompatible Change

### Changelog entry:
`transactionID()` and the transaction ID columns in `system.parts`, `system.transactions`, `system.query_log`, and `system.transactions_info_log` now return `Tuple(UInt64, UInt64, UUID, Int64)` instead of `Tuple(UInt64, UInt64, UUID)`, adding `session_node_version` as the fourth element, so queries that compare or destructure the old 3-field tuple must be updated. Transactions also now require Keeper to advertise `LIST_WITH_STAT_AND_DATA`, `FILTERED_LIST`, `MULTI_READ`, and `CHECK_STAT`; clusters missing those flags will reject transactional startup and load paths until Keeper is upgraded.
Findings

❌ Blockers

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117822#discussion_r3921974359] [src/Common/TransactionID.cpp:20-35, src/Interpreters/TransactionSession.cpp:139-150, src/Interpreters/TransactionManager.cpp:468-477, src/Interpreters/MergeTreeTransaction/VersionInfo.cpp:81-100, src/Interpreters/TransactionPayloads.cpp:83-87, 154-158, 191-197] TransactionID now persists a fourth field as soon as _session is initialized, but the enclosing on-disk and Keeper payloads still claim version: 1. This leaves no rollout-safe mixed-version or downgrade path for transactional metadata. Suggested fix: version the nested TID payload change and keep the old format readable and writable until the migration is complete. I still consider this real because TransactionSession::initSessionNode unconditionally bumps the session znode, so fresh transactions immediately serialize the 4-field form.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117822#discussion_r3921974365] [src/Interpreters/TransactionLog.cpp:54-75, src/Interpreters/TransactionManager.cpp:181-190] The new layout creates only per-replica _tail_ptr znodes and never preserves the legacy root tail_ptr, so the Keeper state produced by this binary is not downgrade-safe. Suggested fix: keep populating the legacy path until the layout change has an explicit migration/version gate. I still consider this real because the incompatibility is persisted in Keeper, not only in local memory.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117822#discussion_r3921974383] [src/Interpreters/TransactionManager.cpp:95-110, src/Storages/MergeTree/MergeTreeData.cpp:2282-2289] The new Keeper feature gate is reachable from part loading through TransactionManager::getCSN, so upgrading a server can now fail ATTACH and startup on existing transactional parts before any new BEGIN TRANSACTION. Suggested fix: apply the stricter requirement only to newly created transactional metadata, or perform an explicit migration check before part loading starts. I still consider this real because the load path runs while reading pre-existing on-disk metadata.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117822#discussion_r3921974374] [src/Interpreters/TransactionLog.cpp:101-106, 410-452, src/Interpreters/TransactionManager.cpp:379-423, 826-840] assertTIDIsNotOutdated returns when global_tail_ptr is still UnknownCSN, which leaves tryFinalizeUnknownStateTransactions free to roll back a transaction that actually committed while this replica was partitioned. Suggested fix: treat UnknownCSN as "cannot decide yet", or seed the global watermark before unknown-state finalization runs. I still consider this real because global_tail_ptr is only advanced by cleanup, so a non-cleaner or recently reconnected replica keeps this guard vacuous.
  • [src/Interpreters/TransactionLog.h:125-134, src/Interpreters/TransactionLog.cpp:508-562, 599-623] The new per-table cleanup state is incomplete: collectRemovableEntries and computeCleanupPlan ignore per-table processed floors entirely, table_affected_csns is only erased/pruned, and updateTableProcessedCSN has no callers. In the CLICKHOUSE_CLOUD path this still allows log GC to advance past tables that have not processed a touched CSN. Suggested fix: populate the per-table affected set and clamp cleanup by the minimum processed CSN of every touched table.
  • [src/Interpreters/MergeTreeTransaction.cpp:416-457, 536-548, src/Interpreters/TransactionManager.cpp:549-560, src/Interpreters/InterpreterTransactionControlQuery.cpp:82-95] A stale _session ZBADVERSION during COMMIT is treated like an ordinary serialization conflict, but rollback of a transaction already in COMMITTING is NotNeeded, so the state guard drops it back to RUNNING and the session keeps it attached. That leaves the client able to keep using a transaction that can never commit successfully. Suggested fix: make a failed _session check terminal for the transaction and detach it from the session on that path.
  • [src/Storages/MergeTree/MergeTreeData.cpp:2282-2294, src/Interpreters/TransactionManager.cpp:795-823] Startup part classification still uses "not in my local running_list" as evidence of rollback after an unresolved TID. That is wrong for parts created by another live replica, so PartLoadingTree can discard a peer's still-running part as rolled back. Suggested fix: use the same invalidation/re-check sequence as VersionMetadata::tryGetCSN instead of the local-running-list shortcut.
  • [src/Storages/StorageMergeTree.cpp:1654-1669, 2062-2068, 2508-2522] loadMutations now persists RolledBackCSN into orphaned transactional mutation files instead of deleting them. Those entries are then skipped forever by selectPartsToMutate, while markFinishedMutations stops at the first transactional entry, so one rolled-back mutation can block later mutations after restart. Suggested fix: treat only committed CSNs as loadable here and keep removing RolledBackCSN entries.
  • [src/Interpreters/MergeTreeTransaction/VersionMetadata.cpp:804-811, src/Functions/FunctionsTransactionCounters.cpp:98-107, src/Storages/System/StorageSystemParts.cpp:136-138, 364-375, src/Interpreters/QueryLog.cpp:163, 358-361] This PR changes the public SQL contract of TransactionID from Tuple(UInt64, UInt64, UUID) to Tuple(UInt64, UInt64, UUID, Int64) across transactionID and system/log tables. Existing queries that compare or destructure 3-field tuples now break, as shown by the stateless test rewrites in the diff. Suggested fix: preserve the 3-field public tuple and expose session_node_version separately, or keep the compatibility break but document it and provide migration guidance explicitly.
Tests
  • ⚠️ [tests/integration/test_part_loading_tree_rollback/test.py:15, src/Interpreters/TransactionManager.cpp:95-107, src/Storages/MergeTree/MergeTreeData.cpp:2282-2289] The touched integration suites force the required Keeper flags on, so they do not prove the new fail-closed contract. Please add one focused negative test with check_stat: 0 (or another required flag disabled) that asserts the explicit SUPPORT_IS_DISABLED failure on a real entrypoint such as loading transactional metadata or ATTACH TABLE.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: make the persisted TransactionID/Keeper layout changes rollout-safe, fix the stale-session and unknown-state correctness holes, stop misclassifying peer-owned startup state and rolled-back transactional mutations, and either preserve the public 3-field TransactionID SQL contract or document the compatibility break with matching migration guidance.

LLVM Coverage Report

Measured on commit 2b892e3.

Metric Baseline Current Δ
Lines 88.50% 88.40% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.60% -0.10%

Changed lines: Changed C/C++ lines covered: 1252/1905 (65.72%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 3, 2026
@tuanpach tuanpach assigned tuanpach and murphy-4o and unassigned tuanpach Sep 3, 2026
@zlareb1

This comment was marked as low quality.

writeText(tid.host_id, buf);
/// Emit the 4th field only when set, so the common (never-restarted) case stays byte-identical
/// to the old 3-field form. Once a session version is assigned it is always written.
if (tid.session_node_version != 0)

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.

❌ Blocker: this changes the serialized TransactionID shape without any version bump or downgrade path. beginTransaction now stamps every TID with session.getVersion() (src/Interpreters/TransactionManager.cpp:465-475), and initSessionNode always bumps _session via createIfNotExists + unconditional set (src/Interpreters/TransactionSession.cpp:139-150), so transactional TIDs immediately start writing a fourth field here. That text form is then persisted into txn_version.txt (src/Interpreters/MergeTreeTransaction/VersionInfo.cpp:84-89) and all the Keeper payloads that still claim version: 1 (src/Interpreters/TransactionPayloads.cpp:83-87, 154-158, 191-197). The current master reader still asserts ) right after host_id in src/Common/TransactionID.cpp:30-39, so one transaction on the new binary is enough to strand a downgrade or mixed-version replica when it reads part metadata or a log/stamp entry. getHash also changes on the same field (src/Common/TransactionID.cpp:9-16), and invalid_tids persists that hash into Keeper paths (src/Interpreters/TransactionSession.cpp:108-117, 363-372) with no compatibility layer. This needs an explicit format version / migration story instead of changing the nested TID payload in place.

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.

This is an experimental feature, no need to make it compatible

session.createActiveNode(zookeeper);

/// Initialize our own tail_ptr in Keeper if absent.
zookeeper->tryCreate(session.replicaTailPtrPath(), Tx::serializeCSN(Tx::MaxReservedCSN), zkutil::CreateMode::Persistent);

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.

❌ Blocker: a fresh deployment on this layout can no longer be downgraded, because the legacy <txn_root>/tail_ptr znode is never created anymore. initLogRoot now creates only /log (src/Interpreters/TransactionLog.cpp:54-81), and this initialization path writes only replicas/<uuid>_tail_ptr (src/Interpreters/TransactionManager.cpp:178-188). The current master startup still does an unconditional get(zookeeper_path + "/tail_ptr") in src/Interpreters/TransactionLog.cpp:221, so an old binary fails its transaction-log initialization with ZNONODE until an operator recreates that node by hand. If downgrade support is still expected, the old path has to keep being populated (or the new layout needs a compatibility switch/migration gate).

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.

Transaction is an experimental feature, no need to make it compatible

/// Ensure that we are not trying to get CSN for TID that was already removed from the log.
/// Use global_tail_ptr (min across all live replicas) as the safe truncation boundary.
CSN tail = instance().txn_log.getGlobalTailPtr();
if (tail == Tx::UnknownCSN || tail <= tid.start_csn)

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.

❌ Blocker: this guard is now fail-open in exactly the case where tryFinalizeUnknownStateTransactions needs it to stay fail-closed. assertTIDIsNotOutdated returns when global_tail_ptr is UnknownCSN (src/Interpreters/TransactionManager.cpp:823-837), but that watermark is never seeded on startup/reconnect and only advances after this replica itself completes a cleanup pass (src/Interpreters/TransactionLog.cpp:101-107, 262-359). After a network partition, the cleanup owner explicitly excludes our dead session from computeGlobalMinTailPtr (src/Interpreters/TransactionLog.cpp:425-452) and may prune the committed csn-* entry while we are away. On reconnect we reload the log and then roll back any unknown-state txn whose CSN is still missing (src/Interpreters/TransactionManager.cpp:315-330, 376-420). Because the watermark is still UnknownCSN on this replica, the guard becomes vacuous and a transaction that actually committed while the reply was lost is silently finalized as rollback. This needs to treat UnknownCSN as “cannot decide yet” or seed global_tail_ptr from the live replicas before unknown-state finalization runs.

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.

Prior to this PR, transaction doesn't work with multiple replicas.
We need follow up PR to support multiple replicas.


/// Fail-close before any list-with-data or multi-read call runs.
auto zk = global_context->getZooKeeper();
if (!zk->isFeatureEnabled(KeeperFeatureFlag::LIST_WITH_STAT_AND_DATA)

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.

❌ Blocker: this new Keeper feature gate is not limited to BEGIN TRANSACTION; it can now abort table load and server startup for existing transactional data. TransactionManager is created lazily from TransactionManager::getCSN, and MergeTreeData calls that during part loading whenever txn_version.txt contains an unresolved creation_tid (src/Storages/MergeTree/MergeTreeData.cpp:2251-2268). So an upgraded server talking to ZooKeeper or an older Keeper hits SUPPORT_IS_DISABLED here before the user ever starts a transaction, as soon as one table still has transactional metadata on disk. That is a backward-incompatible load path and needs either a compatibility fallback, a gate limited to newly created transactional tables, or an earlier explicit migration check before part loading.

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.

Transaction is an experimental feature, no need to make it compatible

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2b892e3e6 with master 718e603a5 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

45 object files changed (+1.10 MiB total), 4 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/TransactionSession.cpp.o new 425.45 KiB +425.45 KiB
src/CMakeFiles/dbms.dir/Interpreters/TransactionManager.cpp.o new 352.54 KiB +352.54 KiB
src/CMakeFiles/dbms.dir/Interpreters/TransactionLog.cpp.o 368.92 KiB 517.46 KiB +148.55 KiB (+40.27%)
src/CMakeFiles/dbms.dir/Interpreters/TransactionPayloads.cpp.o new 90.75 KiB +90.75 KiB
src/CMakeFiles/dbms.dir/Interpreters/MergeTreeTransaction.cpp.o 225.70 KiB 267.41 KiB +41.71 KiB (+18.48%)
src/CMakeFiles/clickhouse_common_io.dir/Common/ZooKeeperNodeVersion.cpp.o new 34.14 KiB +34.14 KiB
src/CMakeFiles/dbms.dir/Storages/StorageMergeTree.cpp.o 1.45 MiB 1.46 MiB +18.00 KiB (+1.22%)

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

343 translation units recompiled, 3058 s compile time in total, 339 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.87 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -513.6 s (-14%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Processors/QueryPlan/ReadFromMergeTree.cpp 34.8 s 23.1 s -7.2 s (-24%)

Translation units without a recent master baseline:

  • src/Interpreters/TransactionManager.cpp: 7.0 s
  • src/Interpreters/TransactionSession.cpp: 6.0 s

Job report

/// Create empty entry to allocate new CSN to safely start counting from the beginning and avoid TID duplication.
/// TODO It's possible to skip this step in come cases (especially for multi-host configuration).
Coordination::Error code = zookeeper->tryCreate(zookeeper_path_log + "/csn-", "", zkutil::CreateMode::PersistentSequential);
CSN new_tail = std::min(oldest_snapshot, oldest_unfinalized_start_csn);

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.

❌ Blocker: the new per-replica _tail_ptr no longer includes the per-table processed_csn floor that this PR introduces for processPartsUpdate. advanceOwnTailPtr advances from min(oldest_snapshot, oldest_unfinalized_start_csn) only, so in the CLICKHOUSE_CLOUD path a replica can advertise _tail_ptr past the highest CSN some touched table has actually reconciled. Once the cleanup owner trims that csn-* prefix, the lagging replica has lost the log rows it still needs after lag or restart. Please clamp _tail_ptr by the minimum processed CSN across affected tables, or keep those entries until every touched table reports them processed.

/// A commit request lost a conflict (lock taken over, marker collision, part gone).
/// Report a clear transaction error instead of the raw Keeper code, then roll back.
if (e.code == Coordination::Error::ZNODEEXISTS
|| e.code == Coordination::Error::ZBADVERSION

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.

❌ Blocker: ZBADVERSION here is not only "some concurrent part change" anymore; it is also the _session guard that rejects commits from a session a peer already replaced. That creates a race with advanceSessionVersionAndRollbackStaleTxns: if a stale transaction is already in COMMITTING, rollbackTransaction returns NotNeeded because MergeTreeTransaction::rollback at src/Interpreters/MergeTreeTransaction.cpp:481 only flips UnknownCSN -> RolledBackCSN. The commit then lands in this branch, state_guard restores CommittingCSN -> UnknownCSN, and InterpreterTransactionControlQuery::executeCommit keeps the transaction attached because it only detaches on UNKNOWN_STATUS_OF_TRANSACTION.

Concrete trace:

  • session expires, runUpdatingThread bumps session_node_version;
  • a concurrent COMMIT races that sweep and reaches Keeper with the old txn->tid.session_node_version;
  • the _session Check fails with ZBADVERSION;
  • this branch throws SERIALIZATION_ERROR, but the transaction goes back to RUNNING instead of becoming terminal.

After that the session can keep issuing writes on a transaction that can never commit successfully. Please make a failed _session check terminal for the transaction (or mark stale transactions before the sweep drops running_list_mutex) instead of treating it like an ordinary part conflict.

Comment thread src/Interpreters/TransactionManager.cpp Resolved
csn = TransactionManager::getCSN(version_info.creation_tid);
if (!csn
&& TransactionLog::instance().tryGetRunningTransaction(version_info.creation_tid.getHash()) == nullptr)
&& TransactionManager::instance().tryGetRunningTransaction(version_info.creation_tid.getHash()) == nullptr)

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.

❌ Blocker: this startup-only rollback heuristic no longer matches the transaction liveness model the PR introduces. VersionMetadata::tryGetCSN was changed to classify "no CSN" as rolled back only after isTIDInvalid() proves the owner session is dead (src/Interpreters/MergeTreeTransaction/VersionMetadata.cpp:507-520), but read_txn_status() still uses the old "not in my local running_list => rolled back" rule.

That is wrong for peer-created parts. running_list is populated only by this replica's beginTransaction() (src/Interpreters/TransactionManager.cpp:465-477), so a part whose creation_tid belongs to another live replica always hits nullptr here. On startup of a SharedMergeTree replica, the trace is:

  • peer B has written a part with unresolved creation_tid but has not committed yet;
  • replica A scans it during PartLoadingTree::add;
  • getCSN() returns UnknownCSN because there is no csn-* entry yet;
  • this branch sees no local running transaction and returns RolledBack.

The loading tree can then drop that still-live peer part or let an intersecting committed part evict it. This path needs the same isTIDInvalid() / re-check sequence as VersionMetadata::tryGetCSN, not the local-running-list shortcut.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
tuanpach added a commit to tuanpach/ClickHouse that referenced this pull request Sep 4, 2026
`TransactionLog::removeOldEntries` guards its log-cleanup Multi with a
`CheckStat` request (TransactionLog.cpp:315). `CheckStat` is a Keeper extension
behind the `check_stat` feature flag. When Keeper does not advertise it, Keeper
answers `Unsupported operation: CheckStat` and drops the whole session. The
session is shared, so an unrelated in-flight COMMIT dies with it: the commit
Multi never lands, `tryFinalizeUnknownStateTransactions` correctly finds no CSN
and rolls the transaction back, and the client sees

    Code: 649. Transaction (...) was rolled back. (INVALID_TRANSACTION)

with no hint of the real cause. The rolled-back transaction also stays open on
its session, so the next `BEGIN TRANSACTION` there fails with `Nested
transactions are not supported`, cascading into later tests.

Two changes:

- `TransactionManager`'s constructor now also requires `CHECK_STAT`, alongside
  the three flags it already checked. A Keeper without it now fails fast with a
  clear message instead of losing a commit to a killed session.
- Pin `check_stat` in the four integration tests that use transactions
  (`test_transactions`, `test_broken_tmp_txn_version_startup`,
  `test_part_loading_tree_rollback`, `test_replicated_database`). The harness
  randomizes every Keeper feature flag a test does not pin, so these were
  failing on the unlucky rolls.

Diagnosed from the CI run below, where keeper1 and keeper2 both rolled
`check_stat: 0`. Verified locally: with `check_stat` forced to 0 the server now
reports the new `SUPPORT_IS_DISABLED` message rather than a lost commit, and
`test_transactions` passes 9/9 with the flag pinned.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117822&sha=44740ca3a75feee52a43a959f8995543db2994c4&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%203%2F6%29
Related: ClickHouse#117822
…sactionSession

`TransactionLog` carried three unrelated responsibilities: the singleton
lifecycle and its Keeper handle, the CSN log with its mirror and cleanup, and
the per-replica session identity. This splits them into four units:

- `TransactionManager` - singleton lifecycle, Keeper handle, worker thread.
- `TransactionLog` - the CSN log, its local mirror and its cleanup.
- `TransactionSession` - session identity, peer liveness, invalid TIDs.
- `TransactionPayloads` - the Keeper payload types and their serialization.

`TransactionManager` is now the entry point, so callers of the old
`TransactionLog` statics move over to it.

Two fixes come along with the split, both in CSN log node names:

- `serializeCSN` no longer goes through `zkutil::getSequentialNodeName`, which
  assumes Int32 and underflows its padding. The Keeper sequential counter is
  `int64_t`, so names grow past ten digits and stop being order-comparable as
  strings.
- `reloadCSNLogs` orders entries by CSN rather than by node name, and fences
  itself with a `sync` pipelined into the read, because a full reload is
  published unconditionally and a trailing node would otherwise move
  `latest_snapshot` backwards.

The parts that depend on `SharedMergeTree` and `VersionMetadataOnKeeper` sit
behind `#if CLICKHOUSE_CLOUD` and are not built here.
`TransactionID` gained `session_node_version`, so `getTransactionIDDataType`
returns a four-element tuple. Three producers still built a three-element one:

- `StorageSystemParts` and `TransactionsInfoLog` inserted a short `Tuple`.
- `QueryLog` pushed into sub-columns 0..2 and left sub-column 3 empty, so the
  tuple's sub-columns had different lengths and the `system.query_log` insert
  failed. Rows were lost, which broke every test that reads `system.query_log`
  after a flush, none of which involve transactions.

Update the affected test references for the wider tuple, and drop the now
unused `fs` namespace alias in `TransactionManager.cpp`.
Integration tests randomize Keeper feature flags, and `TransactionManager`
fails closed unless Keeper advertises `filtered_list`, `multi_read` and
`list_with_stat_and_data`. A run that switched any of the three off made every
test in these two directories fail at `BEGIN TRANSACTION`.

Declare the three as required so the randomizer leaves them on.
`TransactionID` gained a fourth field, `session_node_version`, so
`getTransactionIDDataType` renders `system.parts.creation_tid` and
`removal_tid` as `Tuple(UInt64, UInt64, UUID, Int64)`. The integration test
still wrote three-element tuples, which failed two ways:

- comparing a column against a three-element literal threw
  `ILLEGAL_TYPE_OF_ARGUMENT`, e.g.
  `removal_tid = (1,1,'00000000-0000-0000-0000-000000000000')`;
- `expect_part_info` keys its `replace_map` on the TID text, so the
  substitution missed and the symbolic assert failed with
  `assert "(1,1,'...',0)" == 'tid0'`.

Append the fourth element to the 24 TID literals. Verified locally: the six
tests fail on this branch before the change and pass after it, with the same
binary.
`TransactionManager`'s constructor is fail-close: it throws
`SUPPORT_IS_DISABLED` unless Keeper advertises `LIST_WITH_STAT_AND_DATA`,
`FILTERED_LIST` and `MULTI_READ`. The integration harness randomizes every
Keeper feature flag a test does not list in `keeper_required_feature_flags`, so
any test that touches transactions fails on the unlucky rolls.

Two tests touch transactions without pinning all three:

- `test_replicated_database` — `bad_settings_node` is configured with
  `implicit_transaction = 1` on purpose, so every query on it starts a
  transaction. It pinned `multi_read` but not the other two. All six instances
  now share one `KEEPER_FEATURE_FLAGS` list.
- `test_part_loading_tree_rollback` — its parts are fabricated with a real
  `creation_tid`, so `ATTACH TABLE` resolves that TID through
  `TransactionManager`. It pinned nothing.

Also updates a comment that still named `TransactionLog::instance`, which this
branch renamed to `TransactionManager::instance`.

Verified locally: the generated `feature_flags.yaml` now has all three flags at
1 on every Keeper node while the unpinned flags still vary per node, and the
affected tests pass.
`TransactionLog::removeOldEntries` guards its log-cleanup Multi with a
`CheckStat` request (TransactionLog.cpp:315). `CheckStat` is a Keeper extension
behind the `check_stat` feature flag. When Keeper does not advertise it, Keeper
answers `Unsupported operation: CheckStat` and drops the whole session. The
session is shared, so an unrelated in-flight COMMIT dies with it: the commit
Multi never lands, `tryFinalizeUnknownStateTransactions` correctly finds no CSN
and rolls the transaction back, and the client sees

    Code: 649. Transaction (...) was rolled back. (INVALID_TRANSACTION)

with no hint of the real cause. The rolled-back transaction also stays open on
its session, so the next `BEGIN TRANSACTION` there fails with `Nested
transactions are not supported`, cascading into later tests.

Two changes:

- `TransactionManager`'s constructor now also requires `CHECK_STAT`, alongside
  the three flags it already checked. A Keeper without it now fails fast with a
  clear message instead of losing a commit to a killed session.
- Pin `check_stat` in the four integration tests that use transactions
  (`test_transactions`, `test_broken_tmp_txn_version_startup`,
  `test_part_loading_tree_rollback`, `test_replicated_database`). The harness
  randomizes every Keeper feature flag a test does not pin, so these were
  failing on the unlucky rolls.

Diagnosed from the CI run below, where keeper1 and keeper2 both rolled
`check_stat: 0`. Verified locally: with `check_stat` forced to 0 the server now
reports the new `SUPPORT_IS_DISABLED` message rather than a lost commit, and
`test_transactions` passes 9/9 with the flag pinned.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117822&sha=44740ca3a75feee52a43a959f8995543db2994c4&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%203%2F6%29
Related: ClickHouse#117822
`rollback` decided whether to restore a part it had removed from the return value of
`resetRemovalTID`: a clear that changed nothing was read as "another operation owns this removal".
A mutate task of the same transaction can get there first - it stamps `removal_tid` on its source,
looks up whether that stamp committed, reads `RolledBackCSN` and blanks the stamp - so the clear
finds nothing to do on a part that is still ours, and the part is never restored to Active.

Such a part stays readable by every transaction, because visibility comes from the version
metadata, but a merge can no longer retire it, because a merge only takes parts out of the Active
set. `OPTIMIZE FINAL` then copies its row into the merged part without retiring the original and
the row is returned twice. A later transactional ALTER blocked by that part finds no removal lock,
so no write conflict is reported and it waits to `max_execution_time` instead of failing with a
serialization error.

Decide from the record instead: restore when there is no committed removal and the stamp is either
gone or still ours. A real takeover leaves the new owner's `removal_tid` in place, so it is still
correctly declined.

Also log the part a waiting transactional mutation is blocked on, with its state, removal stamp and
lock hash. That decision was previously invisible, and it is the only place such a mutation can
learn about a write conflict.

The test drives the interleaving with two failpoints that change only timing, no values: one holds
the CSN lookup open, which in production is a Keeper round-trip, and one holds a rollback right
after it is marked and before it clears any stamp. Which source is left poisoned depends on which
mutate task is mid-lookup, so the attempt is repeated.
@tuanpach
tuanpach force-pushed the sync-transaction-manager branch from d9f0f0e to 9f5ef32 Compare September 6, 2026 05:25
if (!entry.tid.isNonTransactional() && !entry.csn)
{
if (auto csn = TransactionLog::getCSN(entry.tid))
if (auto csn = TransactionManager::getCSN(entry.tid))

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.

❌ Blocker: TransactionManager::getCSN now returns RolledBackCSN for invalidated transactions, but this startup path still treats any non-zero result as "committed". After a crash between durable rollback and killMutation() removing the mutation_*.txt file, loadMutations() will write RolledBackCSN into the orphaned entry instead of deleting it. That entry never clears itself: selectPartsToMutate() only skips RolledBackCSN mutations "for now" (src/Storages/StorageMergeTree.cpp:2011-2016), and markFinishedMutations() / clearOldMutations() never collect transactional entries (src/Storages/StorageMergeTree.cpp:2469-2488). One rolled-back transactional mutation can therefore block all later mutations after restart. Please branch on Tx::isCommittedCSN(csn) here and keep removing the file on RolledBackCSN.

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 36a7373a-01a1-4e07-9374-9da275d4d0a6
  • MIRAI run: b8489f93-1a61-48ab-8efa-dc62cb7f28ca
  • PR check IDs:
    • clickbench_1515349_1788786353
    • clickbench_1515355_1788786353
    • clickbench_1515361_1788786353
    • tpch_adapted_1_official_1515369_1788786353
    • tpch_adapted_1_official_1515382_1788786353
    • tpch_adapted_1_official_1515419_1788786353

@murphy-4o murphy-4o 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.

no more review advice as it's a sync PR.
it would be better to sweep verbose claude-code style comments

std::unordered_set<StoragePtr> storages TSA_GUARDED_BY(mutex);
DataPartsVector creating_parts TSA_GUARDED_BY(mutex);
DataPartsVector removing_parts TSA_GUARDED_BY(mutex);
/// Parts this transaction is removing, with the `<part>/removal_lock` fingerprint each

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.

those verbose comments are useless for human, nobody would like to read such long comments...

…nager

Six files conflicted. The substantive one: master gained
`NonTransactionalRemovalLocks` (batch two-phase non-transactional removal),
while this branch added a `LockKind` parameter to the same two functions, so
both sides added a different fourth parameter to `removeOldPart` and
`addNewPartAndRemoveCovered`. They are orthogonal, so both are kept: the
statics now take `LockKind kind, NonTransactionalRemovalLocks & removal_locks`,
and `kind` is threaded into `lockRemovalTID`, where the lock intent is
recorded. `NonTransactionalRemovalLocks::store` keeps calling the public
`setAndStoreRemovalTID`, because `finalizeNonTransactionalRemoval` is
protected and, on the only implementation here, does exactly that.

`VersionMetadata::isCreatedByUncommittedTransaction` and `isCreationCommitted`
are new in master and called `TransactionLog::getCSN`, which this branch moves
to `TransactionManager`; both were retargeted.
types.push_back(std::make_shared<DataTypeUInt64>());
types.push_back(std::make_shared<DataTypeUInt64>());
types.push_back(std::make_shared<DataTypeUUID>());
types.push_back(std::make_shared<DataTypeInt64>());

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.

❌ Blocker: this turns TransactionID into a new public SQL type, not just an internal wire-format detail. getTransactionIDDataType now widens system.parts.creation_tid / removal_tid, system.transactions.tid, system.query_log.transaction_id, system.transactions_info_log.tid, and transactionID() from Tuple(UInt64, UInt64, UUID) to Tuple(UInt64, UInt64, UUID, Int64). Existing queries that destructure or compare these values against a 3-field literal now break; 02345_implicit_transaction.sql had to be rewritten in this PR for exactly that reason.

Please keep the user-facing type backward-compatible (for example by preserving the 3-field tuple and exposing session_node_version separately), or treat this as an explicit compatibility break with the corresponding changelog and migration guidance.

with_zookeeper=True,
# That constructor also refuses to start unless Keeper advertises these three flags, and
# the harness randomizes any flag a test does not pin.
keeper_required_feature_flags=[

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.

⚠️ The touched transaction suites now pin all four Keeper flags on, but there is still no focused regression test for the new fail-closed contract itself. TransactionManager now throws SUPPORT_IS_DISABLED when CHECK_STAT or the other required flags are missing before either BEGIN TRANSACTION or part loading runs (src/Interpreters/TransactionManager.cpp:95-108, src/Storages/MergeTree/MergeTreeData.cpp:2282-2288). If that constructor check is dropped or moved off the load path later, these tests still stay green because the harness forces the flags to 1. Please add one negative test with check_stat: 0 that asserts the explicit failure on one of the entrypoints this file relies on (ATTACH TABLE with transactional metadata would be the most direct fit here).

`smt_force_txn_rollback_invalidation` and `tx_log_abort_cleanup_multi` are
already in `APPLY_FOR_FAILPOINTS` since master commit 3275244 ("Sync
critical files from private"), so the copies added by this branch expand `M`
a second time and break the build with `error: redefinition of
'smt_force_txn_rollback_invalidation'`. Both fail points stay available
through the existing `REGULAR` registrations.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117822&sha=53f772a809b71d065f5caed70ef3b37af8a491f8&name_0=PR
PR: ClickHouse#117822
@tuanpach
tuanpach added this pull request to the merge queue Sep 18, 2026
Merged via the queue into ClickHouse:master with commit 0386af7 Sep 18, 2026
178 checks passed
@tuanpach
tuanpach deleted the sync-transaction-manager branch September 18, 2026 02:40
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 18, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@tuanpach @murphy-4o — this PR looks backward incompatible but is categorized as Not for changelog (changelog entry is not required).

Why: VersionMetadata.cpp:810 adds a fourth DataTypeInt64 to getTransactionIDDataType, which is the declared type of five system-table columns and the return type of transactionID(). A/B on the PR's own merge-base binary vs a post-merge binary: SELECT count() FROM system.parts WHERE creation_tid = (1, 1, '00000000-0000-0000-0000-000000000000') returns 0 before and throws ILLEGAL_TYPE_OF_ARGUMENT after. These columns exist regardless of allow_experimental_transactions, so the break is not confined to the experimental feature.

Suggested category: Backward Incompatible Change. Ignore if the change is intentionally non-breaking.

@clickgapai

Copy link
Copy Markdown
Contributor

@tuanpach @murphy-4o — title/description suggestions:

Description (currently incomplete):

  • Why: The body describes the change as a four-way split plus two CSN-node-name fixes. It does not mention the new TransactionID field at all, nor that it changes user-visible system-table column types, the transactionID() return type, and the on-disk txn_version.txt/mutation_*.txt TID encoding, nor the new Keeper feature-flag requirement that makes TransactionManager refuse to construct.

  • Suggested addition:

    Also in this PR:

    • TransactionID gains a fourth field session_node_version. This changes Tuple(UInt64, UInt64, UUID) to Tuple(UInt64, UInt64, UUID, Int64) for system.parts.creation_tid/removal_tid, system.dropped_tables_parts.creation_tid/removal_tid, system.query_log.transaction_id, system.transactions.tid, system.transactions_info_log.tid, and for the return type of transactionID(). Existing queries that compare these against a three-element tuple literal fail with ILLEGAL_TYPE_OF_ARGUMENT; system.query_log and system.transactions_info_log are renamed aside on upgrade by SystemLog::prepareTable. These columns are present whether or not allow_experimental_transactions is set, so this needs a Backward Incompatible Change entry.
    • On disk, a TID with a non-zero session_node_version serialises with four fields in txn_version.txt and mutation_*.txt. initSessionNode assigns a non-zero version on the first server start, so this is the normal case, not the exception.
    • TransactionManager now refuses to construct unless Keeper advertises LIST_WITH_STAT_AND_DATA, FILTERED_LIST, MULTI_READ and CHECK_STAT. Part loading reaches this without consulting allow_experimental_transactions.
    • TransactionManager::getCSN is no longer a pure in-memory lookup: a miss now costs Keeper round trips (TransactionLog::resolveGapCSNFromKeeper), and it is called from VersionMetadata::isVisible.

Ignore if intentional.

@clickgapai

Copy link
Copy Markdown
Contributor

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

Close anything that's wrong or already addressed.

pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 21, 2026
…n the stress and upgrade checks

Upgrade check (amd_release) has been failing since 2026-09-18 12:03 UTC with

    Code: 344. DB::Exception: Transactions require Keeper to advertise
    `LIST_WITH_STAT_AND_DATA`, `FILTERED_LIST`, `MULTI_READ` and `CHECK_STAT`
    feature flags. Upgrade the Keeper cluster: Cannot attach table ...
    (SUPPORT_IS_DISABLED)

logged from AsyncLoader::worker, with that table's load job finishing FAILED and
later queries on it getting Code: 722. It is 12 of 229 upgrade-check runs (5.2%)
across 12 unrelated PRs.

The configuration these checks build is internally inconsistent.
tests/config/install.sh always links config.d/transactions.xml, so every stress
and upgrade server runs with allow_experimental_transactions=42; configure() in
stress_tests.lib then rolls filtered_list and multi_read 50/50 into the embedded
Keeper's config.d/keeper_port.xml. KeeperContext force-enables FILTERED_LIST only
when multi_read is on, so with p = 1/2 per server start the Keeper advertises
neither. upgrade_runner.sh calls configure() once per release, so the two servers
roll independently and the pre-upgrade server can be stopped mid-run leaving
parts whose txn_version.txt carries a transactional creation_tid. Loading such a
part on the restarted server runs MergeTreeData::loadDataPart ->
VersionMetadata::loadAndUpdateMetadata -> validateInfo, which calls
TransactionManager::instance() for any creation_tid that is not
isNonTransactional() and so constructs the lazy singleton; its constructor
requires the four flags and fails closed, aborting the ATTACH. The requirement
reached master only with ClickHouse#117822 (merge 0386af7, 2026-09-18 02:03 UTC),
which is why the failures start that day.

Requiring the flags is deliberate, and ClickHouse#117822 already applied the matching
remedy on the integration side by pinning keeper_required_feature_flags in the
transaction tests. The shell harness shared by Stress test (*) and Upgrade
check (*) is the one it missed, so stop randomizing those two flags there.
check_not_exists, create_if_not_exists and remove_recursive keep rolling, and the
MULTI_READ-off client path keeps dedicated coverage in
tests/integration/test_refreshable_mv_no_multi_read.

Verified with two single-node servers over one data directory differing only in
the two flags: off, both a committed and an uncommitted transactional part fail
to attach with the same stack frames as the CI artifact; on, both load. Driving
the real configure() block over 50 seeds x 40 iterations keeps both flags enabled
in 2000/2000 rolls, against 985/2000 disabled once the two deleted lines are
restored.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
ClickHouse#117822 made `TransactionLog` a non-singleton owned by `TransactionManager`,
so the empty-part skip in `selectPartsToMutate` now takes the latest snapshot
from `TransactionManager`, as `clearEmptyParts` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 1, 2026
Master split TransactionLog into TransactionManager (ClickHouse#117822), so the
claim/rollback split now lives on TransactionManager instead:
rollbackTransaction(txn, already_claimed) and the static claimRollbackFor.

MergeTreeTransaction::rollback now takes commit_gate exclusive around its
UnknownCSN -> RolledBackCSN CAS and returns RollbackResult. claimRollback
keeps that: it does the same gated CAS and the csn.notify_all that every
csn writer owes, and rollback(already_claimed) skips both when the caller
already won the claim. The commit's own CAS in beforeCommit is under the
same gate, so exactly one of commit or KILL MUTATION still wins.

Master now catches exceptions from the re-entrant killMutation in the
rollback sweep, so the erase-before-rollback order no longer protects a
noexcept frame; it is kept so the sweep finds nothing to remove and an
unlink failure is reported to the KILL MUTATION caller instead of only
being logged. Comments trimmed accordingly.

The test pause point in beforeCommit stays outside commit_gate, so a
parked commit does not hold the gate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... pr-not-for-changelog This PR should not be mentioned in the changelog 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