Repository navigation
Do not throw a logical error when an ephemeral node is held by someone else - #114408
Conversation
…e else
zkutil::ZooKeeper::deleteEphemeralNodeIfContentMatches waits for a contended
ephemeral to disappear and threw LOGICAL_ERROR on timeout. That condition is
expected runtime state rather than a broken invariant:
* another live server may legitimately hold the node, which is the whole
reason the content predicate exists;
* the wait can be shorter than the holder's session. Keeper removes a dead
session's ephemerals only at session expiry, and the timeout negotiated
during the handshake is stored in Coordination::ZooKeeper's own args copy
and never propagated to zkutil::ZooKeeper::args, which is the object this
wait reads. The message already names this case and then classified it as
a logical error anyway.
LOGICAL_ERROR calls abortOnFailedAssertion from the Exception constructor
under DEBUG_OR_SANITIZER_BUILD, i.e. before unwinding, so a caller-side catch
cannot prevent the abort and the fix has to be at the shared site. Raise
ABORTED instead. The message, the wait and the control flow are unchanged, so
the operation still fails and activation still refuses to proceed rather than
assuming ownership.
This follows ClickHouse#113913, which chose ABORTED for the sibling condition in
StorageKafka2::assertActive. That covered the direct-read path; this is the
activation path. All six call sites (StorageKafka2, the MergeTree restarting
thread, two in DatabaseReplicatedWorker and two in DDLWorker) already treat a
failed activation as retryable and none of them branches on the error code.
Verified in both directions with a TestKeeper gtest, and end-to-end against a
live server through ReplicatedMergeTreeRestartingThread, where the previous
code terminated the server and the new code reports ABORTED, retries with
backoff and leaves the replica read-only.
Internal second-model review (adjudicated)An independent model reviewed this change cold against the ClickHouse review skill, and I
Also noticed while reviewing, and deliberately not chased here: in |
|
Workflow [PR], commit [e0ed9b7] Summary: ✅
AI ReviewSummaryThis PR reclassifies contended or rewritten Keeper Findings❌ Blockers
Tests
Final VerdictChanges requested. The LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 55/59 (93.22%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260812-000300 |
|
cc @Michicosun @alesapin, could you review this? |
…test
The arm_tidy build failed with
gtest_zookeeper.cpp:41:16: error: Value stored to 'started_at' during its
initialization is never read [clang-analyzer-deadcode.DeadStores]
FAIL() expands to `return GTEST_MESSAGE_(...)` (gtest-internal.h:1295). The
static analyzer does not model the throw edge out of
deleteEphemeralNodeIfContentMatches, so the only path it explores is the one
where the call returns normally and FAIL() returns immediately, leaving
started_at unread. arm_tidy builds with -Werror, so the single diagnostic
failed the job and dropped the rest of the matrix.
Use ADD_FAILURE(), which records the failure without returning, so the store
and its read sit on one linear path. This is the established idiom for the
try/catch "should have thrown" shape in this repository
(gtest_sensitive_data_masker.cpp uses it four times).
The elapsed lower bound is preserved and still load-bearing: replacing the
tryWait condition at ZooKeeper.cpp:1461 with `true` reddens exactly the new
assertion (0 vs 600), and reverting ABORTED to LOGICAL_ERROR still aborts the
test with exit 134.
| @@ -1460,7 +1461,7 @@ void ZooKeeper::deleteEphemeralNodeIfContentMatches(const std::string & path, st | |||
| int32_t timeout_ms = 3 * args.session_timeout_ms; | |||
| if (!eph_node_disappeared->tryWait(timeout_ms)) | |||
| throw DB::Exception( | |||
There was a problem hiding this comment.
This turns the timeout into a normal DB::Exception unwind, but DDLWorker::processTask still arms EphemeralNodeHolder::existing(active_node_path, *zookeeper) before it knows it owns /active/<host> (src/Interpreters/DDLWorker.cpp:684-719). On this contended path, unwinding through EphemeralNodeHolder::~EphemeralNodeHolder calls an unversioned tryRemove(path) (src/Common/ZooKeeper/ZooKeeper.h:809-817), so timing out here can delete another worker's active node and break the single-executor contract for distributed DDL. Can we delay creating the holder until after create(active_node_path, ...) succeeds, or at least disarm it before deleteEphemeralNodeIfContentMatches waits and throws?
There was a problem hiding this comment.
The holder lifetime defect is real, but this PR does not introduce the unwind it depends on, so it is pre-existing and out of scope here.
abort_on_logical_error defaults to false (src/Core/ServerSettings.cpp:1433) and DEBUG_OR_SANITIZER_BUILD is undefined in release, so Exception.cpp:114 does not abort there: LOGICAL_ERROR already unwound out of deleteEphemeralNodeIfContentMatches in every release build before this change. ~EphemeralNodeHolder (ZooKeeper.h:809-817) is unconditional on the error code, so it already ran the same unversioned tryRemove. DDLWorker.cpp:694 also throws a plain Coordination::Exception through the same armed holder, in all build types, at the pinned merge-base. This PR changes no line in DDLWorker.cpp.
Fixing the holder lifetime means rewriting processTask's ownership window inside a PR whose whole diff is one error code and its test, so I would rather not fold it in. Recorded as a known residual on this PR instead.
This is my second round on this PR, so I will leave further discussion here for a human reviewer.
The message named a session_timeout_ms mismatch or a bug as the only two explanations, but this branch is reached whenever the node's content does not match ours, and the ordinary cause is that another live session legitimately holds it or a previous session's node has not expired yet. Operators reading it were pointed at a config audit for a condition the code itself anticipates and waits for. The foreign owner is now the primary explanation and the timeout mismatch a secondary one. The error code, the wait and the control flow are unchanged.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units9756 translation units recompiled, 14459 s compile time in total, 9322 of them have a recent master baseline.
|
CI finish ledger - 2674bd9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
177 leaves: 151 OK, 25 skipped with a stated reason (reused from cache, not affected by the Session id: cron:our-pr-ci-monitor:20260813-080000 |
Ergus
left a comment
There was a problem hiding this comment.
Some comments:
-
This is intended to be a "Bug Fix", but the PR's says release behaviour is unchanged except for the error code and message text. The abort only ever happened in debug/sanitizer builds, which are not official stable releases.
-
The sibling PR #113913, used "Improvement" for the identical change class.
On the other hand, the Bug Fix category is what schedules the Bugfix validation (unit tests) gate that is currently the only red check.
-
Add the integration test from #115818's reproducer.
| "Ephemeral node {} still exists after {}s, probably it's owned by someone else. " | ||
| "Either session_timeout_ms in client's config is different from server's config or it's a bug. " | ||
| "Node data: '{}'", | ||
| DB::ErrorCodes::ABORTED, |
There was a problem hiding this comment.
The downgrade removes the only signal that catches a real bug reaching this branch, and open issue #115818 is the live proof
Add Related: #115818 to the description. It is the strongest evidence for the change and the clearest statement of what the change does not fix.
Reconsider ABORTED. It is among the most-thrown codes in the codebase, so after this change system.errors no longer distinguishes an identity collision from a cancelled query.
There was a problem hiding this comment.
Both done in e0ed9b7.
Reconsidered as asked: the code is now REPLICA_ALREADY_EXISTS. ABORTED is raised from 66 places in src/, REPLICA_ALREADY_EXISTS from 7 others, and every one of those 7 is this same condition, including There already is an active replica with this replica path in StorageReplicatedMergeTree and the Replica ... already exists that the non-distributed CREATE DATABASE path in #115818 already returns for exactly this misconfiguration. So system.errors separates it again, and both entrances to the same problem now report the same code.
Related: #115818 is in the description, which also states plainly that this PR does not fix the issue: the database is still left unusable, only without the abort.
On losing the signal: with a code specific to this condition, the retry loop still logs the node path and the owner's ServerUUID on every attempt and system.errors still counts it, and #115818 asks for the same thing it asks of this branch, that a user-reachable misconfiguration should not produce a LOGICAL_ERROR.
| { | ||
| auto code = tryRemove(path, stat.version); | ||
| if (code != Coordination::Error::ZOK && code != Coordination::Error::ZNONODE) | ||
| throw Coordination::Exception::fromPath(code, path); |
There was a problem hiding this comment.
the fast-delete branch of the same function still reports a Keeper race in a way that aborts debug builds.
tryRemove(path, stat.version) tolerates ZNONODE but rethrows anything else as Coordination::Exception.
A non-hardware Coordination::Exception lands on chassert(false) at DDLWorker.cpp:1239
There was a problem hiding this comment.
Verified and fixed in e0ed9b7.
Among the non-hardware codes, tryRemove(path, stat.version) can only return ZBADVERSION there, and it is reachable: the content of an active node is rewritten in place while it is still ours, for instance when DatabaseReplicated strips the unsynced marker (DatabaseReplicatedWorker.cpp:641). It is now reported as the same REPLICA_ALREADY_EXISTS as the wait branch, so it no longer reaches the chassert(false) you pointed at.
DDLWorker::markReplicasActive repeats that read and versioned removal inline for loopback hosts (DDLWorker.cpp:1498), and the copy had the identical problem, reached from the same catch. There a rewritten node is now skipped, which is what the branch already does when another replica claims the host.
The helper's version race is pinned by a TestKeeper test in both directions: with the new branch removed, the assertion sees 999 instead of 253. The loopback copy has no deterministic test. Forcing a write into the window between tryGet and tryRemove needs the first failpoint in DDLWorker.cpp plus an integration test holding it open, which is a larger production change than the four lines it would cover, so I left it out. Happy to add it if you would rather have it.
ABORTED is thrown from 68 places in src/, so system.errors could not tell an identity
collision from a cancelled query. REPLICA_ALREADY_EXISTS is thrown from 7, all of them the
same condition ("There already is an active replica with this replica path" in
StorageReplicatedMergeTree, "Replica ... already exists" in DatabaseReplicated), and it is
the code the non-distributed CREATE DATABASE path already returns for the misconfiguration
in ClickHouse#115818.
The fast-delete branch of the same function had the same defect. tryRemove(path,
stat.version) tolerates ZNONODE but rethrows every other code as a Coordination::Exception,
and a non-hardware Coordination::Exception reaches chassert(false) in
DDLWorker::initializeMainThread, so losing a race aborted debug builds. The reachable code
there is ZBADVERSION: the content of an active node is rewritten in place while it is ours,
for instance when DatabaseReplicated strips the unsynced marker from <replica_path>/active.
Report it as the same runtime condition.
No caller changes behaviour: none of the six branches on the error code, and the
no_sense_to_retry list in DDLWorker::tryExecuteQuery contains neither the old nor the new
code.
Co-Authored-By: Claude Opus 5 <[email protected]>
The reproducer from ClickHouse#115818: CREATE DATABASE ... ON CLUSTER with literal shard and replica names gives both hosts one database UUID and one replica name, so one host finds <replica_path>/active owned by the live other one. session_timeout_ms is lowered to 3s so the wait is 9s instead of 45s. The test asserts that the losing replica reports Code: 253 and that neither server aborted. With LOGICAL_ERROR restored at the throw site it fails: the losing node logs "Logical error: 'Ephemeral node ... still exists after 9s" and dies. Co-Authored-By: Claude Opus 5 <[email protected]>
…tive DDLWorker::markReplicasActive repeats the read, compare and versioned removal inline for loopback hosts, so its ZBADVERSION was still a non-hardware Coordination::Exception reaching chassert(false) in initializeMainThread. A rewritten node is now skipped, like a node the branch already skips when another replica claims it. Also drop the claim that a version mismatch proves foreign ownership: it proves only that the node changed, and the rewrite that reaches this in practice keeps the same server identity. Co-Authored-By: Claude Opus 5 <[email protected]>
Round: e0ed9b7Points 1 and 2, the changelog category: switched to Point 3, the integration test: added as The error code and the fast-delete branch are answered in the two inline threads. |
|
📊 Cloud Performance Report ✅ AI verdict: This is a coordination-layer change: it only touches ZooKeeper ephemeral-node removal (swapping a LOGICAL_ERROR for REPLICA_ALREADY_EXISTS), DDLWorker.markReplicasActive, and their tests. None of that code runs during a ClickBench SELECT, so the three flagged read-path deltas (Q18 +5.5%, Q32 +6.9%, Q34 +6.4%) cannot plausibly be caused by this PR. Q18 and Q32 are downgraded to not_sure as run-to-run variance; Q34 shows a cleaner, consistent shift but still lands within master's normal variance band and off the changed path, so it stands as not_sure rather than a real regression. No PR-attributable performance change found. clickbenchFlagged queries (3 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
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
The code is alright.
36ce602
Related: #115818
Related: #113913
Related: #86434
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Activating a replica whose
active/is_activenode in Keeper is still held by another session is now reported asREPLICA_ALREADY_EXISTSinstead ofLOGICAL_ERROR, so it no longer aborts the server in debug and sanitizer builds. The same applies when that node is rewritten while it is being removed.Description
Related: #115818, #113913, #86434
deleteEphemeralNodeIfContentMatchesfinds the node held by a foreign owner, logsisn't owned by us. Will wait until it disappears, waits3 * session_timeout_ms, and then threwLOGICAL_ERROR. That is reachable from a single user query: in #115818 oneCREATE DATABASE ... ON CLUSTERwith literal shard and replica names makes two hosts the same replica, and the loser then aborts every 45s in debug builds. It is also ordinary runtime state, because Keeper drops a dead session's ephemerals only at expiry while activation retries sooner.It is now reported as
REPLICA_ALREADY_EXISTS, which is what the non-distributed path already returns for the same misconfiguration.ABORTEDis raised from 66 places insrc/,REPLICA_ALREADY_EXISTSfrom 7 others and every one of them is this same condition, sosystem.errorsstill separates an identity collision from a cancelled query. The wait, the control flow and all six call sites are unchanged, and none of them branches on the error code.The fast-delete branch of the same function had the same defect.
tryRemove(path, stat.version)rethrows every code other thanZNONODEas aCoordination::Exception, and a non-hardware one reacheschassert(false)inDDLWorker::initializeMainThread. The reachable code there isZBADVERSION, since the content of anactivenode is rewritten in place, and it is now reported the same way.DDLWorker::markReplicasActiverepeats that read and versioned removal inline for loopback hosts, where a rewritten node is now skipped like one claimed by another replica.#115818 itself is not fixed here. The database is still left unusable, only without the abort.
Both directions are verified with
TestKeeperunit tests and with the #115818 reproducer as an integration test: on this branch the losing replica logsCode: 253, and withLOGICAL_ERRORrestored that test aborts the server.Workflow [PR]
Sync PR [sync-upstream/pr/114408]
Version info
26.10.1.469-master(included in26.10and later)