Repository navigation
Conversation
…tor throws An ordinary BEGIN TRANSACTION could abort the server. TransactionManager::TransactionManager() installs its Keeper component guard as a local of the constructor body, but the two ephemeral node holders it then takes, TransactionSession::active_node_holder and TransactionManager::cleanup_lock_holder, are members. C++ destroys a body's locals before the member subobjects, so any exception leaving the body destroyed the guard first and the member ~EphemeralNodeHolder then called tryRemove with no Coordination component set. ZooKeeper::pushRequest rejects that at ZooKeeperImpl.cpp:1718. This is one level beyond the usual "a destructor cannot be covered by a caller-side guard": the guard is in the right function, just in the wrong scope relative to member lifetime. Both faces are bad. In a debug or sanitizer build Exception::handleErrorCode calls abortOnFailedAssertion for LOGICAL_ERROR inside Exception's own constructor, so ~EphemeralNodeHolder's catch never sees it: the server aborts with signal 6, and the exception that unwound the constructor is never logged, which is why this fix is deliberately trigger-agnostic rather than aimed at one throwing statement. In a release build the throw happens inside pushRequest's own try, whose handler calls finalize(false, false, ...) before rethrowing, so the process-wide Keeper session is force-closed and every other Keeper-backed subsystem on the server loses its session at once. The fix keeps the guard where it is and wraps the constructor body in try / catch (...) that releases both holders while the guard is still alive, then rethrows. TransactionManager::shutdown() already documents this exact invariant and protects itself the same way with a nested guard scope around the same two releases. The shape also follows b95ea45 ("Move keeper component guard from EphemeralNodeHolder to DDLWorker::shutdown"), which removed a generic guard from ~EphemeralNodeHolder as too generic in favour of owner-scoped cleanup plus an explicit holder clear. A function-try-block would not work: its handler runs after the member subobjects are destroyed, so the holders would already be gone. Making the guard a first-declared data member would work but leaves the component installed on the pooled handler thread for the singleton's whole lifetime, and since pushRequest only throws on an empty component that would silence genuinely unguarded call sites elsewhere. A body-scoped catch is complete: no holder can exist before the body is entered, because the two member constructors that could hold one are pure member-initializer work with no Keeper calls, and both holders are only assigned from inside loadLogFromZooKeeper(). Both releases are no-ops on a null holder, so one handler also covers the window where _active is held but the cleanup lease is not yet. The other invariant shutdown() documents, that the holders must not outlive the ZooKeeper& they reference, needs no second fix here: on the unwind path reverse declaration order destroys both holders before zookeeper, and unlike shutdown() this path never calls zookeeper.reset() explicitly. TransactionManager::TransactionManager() is the only constructor in the tree that stores an ephemeral node holder into a member, so there is no structural sibling to extend this to. Of the nine EphemeralNodeHolder member carriers in src/, the other seven are all assigned in non-constructor functions, and of the twelve constructors that install a component guard in their body, only StorageKafka2 and StorageReplicatedMergeTree own a holder member at all, each assigned from a background task that the constructor does not run. The new integration test needs no product-code scaffolding: it writes one CSN log entry claiming an unknown format version, which makes CSNEntryData::deserialize throw from reloadCSNLogs, that is, after initOwnReplicaState has taken both holders. It asserts the cleanup lease is acquired twice in the window, because a second acquisition of an ephemeral znode is only possible if the failed constructor actually removed the first, and that the LOGICAL_ERROR needle does not appear. It runs first in the module: several part-loading paths build the singleton at startup once a transactional part exists on disk, and the singleton latches on success, so a later position could pass without covering anything. Reproducing the abort requires enforce_keeper_component_tracking, which is off by default but is written into every integration instance and is set for stateless runs too. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review in two independent passes: my own cold read of the resulting code (5 nits, no
Boundary of the "no structural sibling" claim, stated rather than left implicit. A different shape Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260919-094100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260919-085600 |
|
Workflow [PR], commit [e8869f6] Summary: ✅
AI ReviewSummaryThis PR moves Final Verdict✅ No new findings in the current diff. LLVM Coverage ReportMeasured on commit e8869f6.
Changed lines: Changed C/C++ lines covered: 21/24 (87.50%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units28 translation units recompiled, 255 s compile time in total, 28 of them have a recent master baseline. |
CI finish ledger - 102931eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Measured on the perf row, so the shard verdict is not misread as a perf regression: of the 1308 per-query rows on this run, 1306 are Session id: cron:our-pr-ci-monitor:20260919-170416 |
tavplubix
left a comment
There was a problem hiding this comment.
no longer aborts the server with Current component is empty
What does this error mean exactly?
TransactionManager::TransactionManager() installs its Keeper component guard as a local of the constructor body, but the two ephemeral node holders it then takes (TransactionSession::active_node_holder and TransactionManager::cleanup_lock_holder) are members.
So we still don't set the component for these requests, but bypass the enforce_component_tracking check, right? Why don't we make the guard a member too, or not initialize the node holders in the ctor body?
When using Keeper client, we must set a guard like One of the purposes should be for troubleshooting (e.g, link). When We can fix it by adding the guard to |
The
We must put the logic to clear |
|
The first question is answered above, so from my side only the consequence: What the error means. With
The opposite: the component is set for those two Guard as a member would get the destruction order right, but Not taking the holders in the constructor body is the cleaner shape and I agree with it, but it is wider than this fix: both holders are taken inside |
|
@groeneai can move the resetting logic to dtor of |
|
The path this PR fixes never reaches the destructor at all: when a constructor exits by exception, the object's own destructor is not invoked, only the destructors of its fully constructed members. Nothing calls The integration test here is the check for that: it throws from What I can do instead, if this is the part that bothers you: put the two releases in one named private helper that installs the guard itself, called from both |
|
Can we put the initialization logic into |
|
Yes, and I would rather do it in this PR than leave the narrow fix standing. Two things I measured on the current head before answering, because both change how the call has to be wired.
So the shape I would implement: A throw out of One thing the move does not give for free: with no handler in |
… the constructor Both reviewers asked for the same reshape: @ tavplubix, "Why don't we make the guard a member too, or not initialize the node holders in the ctor body?", and @ tuanpach, "Can we put the initialization logic into TransactionManager::start()?". This does the second, which removes the abort structurally instead of handling it. The constructor took two ephemeral node holders that are members (TransactionSession::active_node_holder, TransactionManager::cleanup_lock_holder) while its Keeper component guard was a local of the body. C++ destroys a body's locals before the member subobjects, so an exception leaving the body destroyed the guard first and the member ~EphemeralNodeHolder called tryRemove with no Coordination component set; ZooKeeper::pushRequest rejects that. After the split, a successful constructor leaves both holders as members of a live object, so an unwind out of start() destroys only start()'s own locals and no holder destructor runs at all. There is nothing left to handle. start() and the constructor are both private, with friend class SingletonHelper<TransactionManager>, and the server calls TransactionManager::instance() rather than instance().start(). Two reasons, both measured, neither visible in the diff. First, exclusion against shutdown: shutdownIfAny() holds instance_mutex while calling shutdown(), and shutdown() joins updating_thread before taking mutex, so a start() reachable outside instance_mutex could create a thread that shutdown() has already passed and then have zookeeper reset under it. Second, no new stall: start() holds mutex across Keeper RPCs bounded only by the client watchdog (worst case about three session timeouts, 90 s by default), which is invisible only while the instance is unpublished, because other threads then block on instance_mutex exactly as they do today across the equally long constructor, rather than on the mutex that commitTransaction, rollbackTransaction and getCSNImpl need. Construction alone no longer yields a usable object, so the constructor must not be reachable without the initialization that follows it; that also forces new Derived() in place of std::make_shared<Derived>(), since make_shared constructs inside the standard library, which is not the friend. A failed attempt discards its instance rather than retrying in place, and createInstanceOrThrow publishes only after start() returns. Retrying on the same object would not work: TransactionLog::initLogRoot asserts it begins empty (chassert(tid_to_csn.empty()), chassert(last_loaded_csn == Tx::UnknownCSN)), processCSNLogs fills exactly those two, and the statement after the log load, ThreadFromGlobalPool's construction, can throw from scheduleOrThrow. So a second start() on a reused instance would trip that assertion in a debug build. Discarding also reproduces today's semantics exactly, since a throwing constructor already destroys everything and the next instance() builds afresh, and it means instance_holder is non-null if and only if the instance is started, so shutdownIfAny() can never see a half-built object. That is also why round 1's release-on-failure handler is deleted rather than moved: the unwind now runs ~TransactionManager() -> shutdown(), which installs its own component guard and performs the same two releases before zookeeper.reset(). On that path stop_flag is false and updating_thread is null, so shutdown() reaches the releases unconditionally and a handler in start() would be dead code. The property still holds that _active and the cleanup lease are released immediately rather than at Context::shutdown(); only the mechanism changed. ~EphemeralNodeHolder has its own catch plus tryLogCurrentException, so there was never a std::terminate exposure to move off the destructor either. Three new lock edges, none of which closes a cycle: mutex -> running_list_mutex via publishLoadedSnapshot (all 14 running_list_mutex critical sections in this file were enumerated and none reaches mutex), mutex -> TransactionLog::mutex (TransactionLog holds only paths, a const TransactionSession &, a const std::atomic_bool & and a logger, and calls back into nothing), and mutex -> Context's zookeeper_mutex via global_context->getZooKeeper() (Context::getZooKeeper and its callees contain zero TransactionManager references). Nothing reachable from loadLogFromZooKeeper() re-acquires mutex, and the launched updating thread's first getZooKeeper() blocks on mutex for zero further statements. The server calls the singleton eagerly before loadMetadata when allow_experimental_transactions is set, because otherwise initialization lands on whichever thread first touches it: measured, that is a background table-loading thread, through MergeTreeData::PartLoadingTree::add -> getCSN, VersionMetadata::loadAndUpdateMetadata -> tryGetCSN, and StorageMergeTree::loadMutations -> getCSN, all of which run on async loading jobs with async_load_databases enabled by default. The call is deliberately not fatal. Today a Keeper problem surfaces at the first transaction and never at startup, so throwing would add a new startup failure mode in which a transient Keeper outage becomes a restart loop; tests/config/config.d/transactions.xml is installed into every stateless test server; and the lazy path still retries, so nothing is lost. Fail fast is honoured as reported at startup instead of at the first transaction. Making the guard a member instead was rejected with reasoning already posted: current_component is static thread_local, so a member guard would stay installed on whichever pooled thread built the singleton and mis-attribute every later request from that thread, hiding genuinely unguarded sites, since pushRequest only throws on an empty component. A function-try-block does not work either, because its handler runs after the member subobjects are destroyed. The guard itself still has to move into start(): every Keeper request start() makes goes through pushRequest, which requires a non-empty component, so deleting it would break the normal path. Calling start() from Server::createServers, as literally proposed, does not cover the construction sites: createServers runs after loadMetadata, two of its five call sites are config-gated, it also runs from updateServers and the SYSTEM START LISTEN callback so it is not one-shot, and clickhouse-local never calls it. The integration test is reshaped rather than added. It is renamed test_failed_start_releases_ephemeral_holders, and the injection now happens before the restart, because the server initializes the log itself at startup and an entry planted afterwards would never be seen by a failing initialization. Its assertions are absolute rather than deltas because the harness config sets rotateOnOpen, so count_in_log reads only the process started by the restart, which is the whole window of interest. A new arm asserts the server still answers SELECT 1 after the eager initialization fails; it is preceded by an assertion on that initialization's own startup diagnostic, so the arm observes an attempt that ran and failed rather than a server that never tried. Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the private-constructor block and the publication story in createInstanceOrThrow (both narrate the new design); compress start()'s block to the member-destruction-order property that pushRequest's component requirement depends on.
|
Done, see 8c026bc. The initialization now lives in Two corrections to what I said when I accepted the reshape, both in the PR description as well. Round Internal second-model review: adjudication log (click to expand)Pre-publication review of the reshape, in two independent passes per round: my own cold read of the
Severity: ❌ blocker / Also checked and clean, for what it is worth to a reviewer. The three new lock edges ( Validation beyond the PR's own module: the nine integration modules that enable transactions and |
Pre-PR validation gate (click to expand)
Mutation arms, all three as required: reverting the whole Validation beyond the module: all nine integration modules that enable Session id: cron:clickhouse-impl-slot-4:20260922-052700 |
CI finish ledger - 42d9798Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Neither failure is reachable from this diff, which touches Session id: cron:our-pr-ci-monitor:20260922-120136 |
…ders separately test_failed_start_releases_ephemeral_holders asserted `Acquired cleanup lease >= 2` over the whole post-restart process, but three start() attempts contribute to that count: the eager one in Server.cpp, the lazy one from BEGIN TRANSACTION, and the final successful one. A single release satisfied it, while the contract the test states is that both failing attempts release what they took. Measured with a mutation that leaks the cleanup lease from the second shutdown of the process onwards, which is the shape of a leak confined to the lazy path: the count falls from 3 to 2 so `>= 2` still holds, `Current component is empty` stays 0 because a holder whose need_remove is clear never calls tryRemove, and the third attempt still succeeds because tryAcquireCleanupLock returns silently on ZNODEEXISTS and createActiveNode removes a stale `_active` before taking its own. The test passed. The oracle is now per attempt: after the eager failure and again after the lazy failure, both ephemeral znodes a start() attempt takes are read out of Keeper and must be absent, and the lease count must have grown across each attempt, which is only possible if the previous attempt released it. After the successful attempt both znodes must be present, so the two empty results are an absence and not a path that never takes them. Those reads sync() first. The test client is pinned to zoo1 while the server shuffles the three configured endpoints, so an unsynced read of a follower could show a holder the server had already removed and redden the test for no reason. test_drop_replica reads Keeper the same way. The same mutation now fails at the lazy-failure arm with "the lazy start() failure left ephemeral node holders behind: ['cleanup_lock']", every earlier assertion still passing. On the unmutated binary the test passes 5 of 5 and the whole test_transactions module 10 of 10. Co-Authored-By: Claude Opus 5 <[email protected]>
CI finish ledger - ab4f807Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
On the first row, one deliberate omission worth stating: the earlier merged trim of that test is Session id: cron:our-pr-ci-monitor:20260923-163416 |
|
Owner for the Not caused by this PR: over 30 days that parameter has 14 rows on 14 distinct carriers and 0 true-master rows, and one of the carriers is a docs-only change, so the signature cannot depend on any carrier's diff. Whether the test also needs its own timeout headroom restored, independently of #121772, is asked at #121096 (comment) |
| /// otherwise build this singleton on a background table-loading thread. | ||
| try | ||
| { | ||
| TransactionManager::instance(); |
There was a problem hiding this comment.
I think we can call start() here, and we don't need to wrap in a try-catch.
If TransactionManager cannot start when config is enabled, we should raise an error early
There was a problem hiding this comment.
Done in 956b548: the startup call no longer catches everything, so a transaction log that cannot be initialized (a Keeper without the feature flags transactions need, a log entry it cannot read) now stops the server.
- The call is still
TransactionManager::instance(): it runsstart()on a fresh instance and publishes it only ifstart()succeeds.start()itself stays private because it holdsmutexacross the Keeper requests, which is only safe while no other thread can see the instance. - I kept one exception: a Keeper hardware error (
Coordination::isHardwareError) is logged, and the first transaction retries. Without it a server with transactions enabled cannot start while Keeper is unreachable, andtest_replicated_database::test_startup_without_zkfails (I ran it). If you want that to be fatal too, I will drop the catch and turn transactions off for that test's restart. - Four DatabaseReplicated test configs enabled transactions without running any, on Keeper feature flags the harness randomizes, so their servers would now fail to start. I removed the setting there.
With `allow_experimental_transactions` enabled, the eager `TransactionManager::instance()` call before `loadMetadata` now rethrows everything except a Keeper hardware error, so a transaction log that cannot be initialized (a Keeper that does not advertise the feature flags transactions need, a CSN entry in an unknown format, no ZooKeeper configuration at all) stops the server at startup instead of surfacing at the first transaction. An unavailable Keeper is still only logged: `test_replicated_database::test_startup_without_zk` restarts a node that has transactions enabled while its Keeper connections are rejected and requires it to come up, and the next use of the manager retries the initialization. `test_failed_start_releases_ephemeral_holders` now expects the start with the bad CSN entry to fail and checks the log of the process that refused to start: the attempt took the cleanup lease, the load error is logged, and `Current component is empty` is not. The per-attempt znode checks go away together with the lazy attempt they covered, which a server with transactions enabled no longer reaches after a failed initialization. That attempt was also what showed a failed instance is never published, so `test_start_is_retried_after_keeper_was_unavailable` takes over: the server starts with its Keeper connections rejected, and the first transaction afterwards must take the cleanup lease, which an instance published by the failed attempt would never do. And `test_startup_fails_on_other_keeper_errors` plants a persistent node with a child where the ephemeral `_active` node goes, so `createActiveNode` fails with `ZNODEEXISTS`, a Keeper error that is not a hardware one, and the server must still refuse to start. Four DatabaseReplicated modules enabled transactions without running any, on a Keeper whose feature flags the harness randomizes. With the error fatal they fail to start whenever the Keeper node a server connects to lacks one of the four flags, so the setting is removed from their configs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… log at startup The eager TransactionManager::instance() call before loadMetadata logged and skipped every Keeper hardware error, and Coordination::isHardwareError also covers ZNOAUTH. So a server whose Keeper credentials do not match the log's ACL still started, and every transaction then failed the same way. Now only the codes of a Keeper that cannot serve the request right now (connection loss, an expired session, an operation timeout, the memory soft limit) leave the initialization to the next use; any other Keeper error, including ZNOAUTH and a marshalling error, stops the server. test_startup_fails_when_keeper_denies_access restricts the log's ACL to an identity the server does not have and requires the server to refuse to start. With the previous check the server logs "Cannot initialize the transaction log at startup" and keeps running, so the test fails. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report 🟢 AI verdict: This PR changes only server startup when allow_experimental_transactions is set in the config: the transaction manager is now created at startup and its Keeper setup moves out of the constructor into start(). It also adds integration tests. None of the benchmarked SELECT queries run this code, so the PR cannot plausibly cause any of the flagged shifts. ClickBench Q20 (-41.4%, CPU time roughly halved) is a large, clear shift that the hard trust rule locks as an improvement, but it most likely comes from a code difference between the PR build and the base build, not from this diff. The not_sure rows (Q18, Q28, Q30, Q33, Q34) are small slowdowns, mostly on noisy queries and inside master's normal range, and the envelope suppressions are consistent with a diff that never touches these queries. clickbench🟢 1 improved · Flagged queries (6 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
Dear @tuanpach, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Related: #117822
Related: #120932
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Move
TransactionManager's Keeper initialization out of its constructor intoTransactionManager::start(), so an ordinaryBEGIN TRANSACTIONcan no longer abort the server withCurrent component is empty.Description
An ordinary
BEGIN TRANSACTIONcan abort the server wheneverenforce_keeper_component_trackingis on. It is off by default, but both test harnesses write it into every server they start.The constructor took two ephemeral node holders that are members (
TransactionSession::active_node_holder,TransactionManager::cleanup_lock_holder) while its Keeper component guard was a local of the body. C++ destroys a body's locals before the member subobjects, so an exception leaving the body destroyed the guard first, and the member~EphemeralNodeHolderthen calledtryRemovewith no component set.ZooKeeper::pushRequestrejects that with aLOGICAL_ERRORraised insideException's own constructor, so a debug build aborts before the unwinding exception is ever logged.Initialization moves into
TransactionManager::start(), andSingletonHelper::createInstanceOrThrowpublishes the instance only after it succeeds. A successful constructor then leaves both holders on a live object, and a failed attempt discards its instance, whose~TransactionManager()->shutdown()releases both under its own guard.The server initializes the log before
loadMetadata, because resolving a part's transactionalcreation_tidwhile loading tables would otherwise build the singleton on a background loading thread. With transactions enabled, a log that cannot be initialized stops the server at startup. Only an unavailable Keeper is logged and left to the next use, so such a server still starts without Keeper, astest_startup_without_zkrequires. The call isTransactionManager::instance(), notstart():start()holdsmutexacross Keeper RPCs, which is safe only while the instance is unpublished. Four DatabaseReplicated test configs enabled transactions without using them, on randomized Keeper feature flags, and drop the setting.Workflow [PR]
Sync PR [sync-upstream/pr/121005]