Repository navigation
Honour lock_acquire_timeout for the lightweight update lock in Keeper - #114125
alexey-milovidov merged 18 commits into
Conversation
…k in Keeper A valid lightweight UPDATE on ReplicatedMergeTree was rejected with Code: 159. Failed to get lock with 100 tries for lightwegiht update in auto mode. (TIMEOUT_EXCEEDED) after about 3 seconds, while lock_acquire_timeout was 120 seconds and the cluster kept granting locks normally throughout. This is the default path: update_parallel_mode defaults to auto and enable_lightweight_update defaults to true. getLockForAutoMode registered its watch on the parent directory <zk>/lightweight_updates/in_progress, whose child set changes on every concurrent lightweight update. Poco::Event auto-resets and EventImpl::waitImpl is `while (!_state) pthread_cond_timedwait(...)`, so an already-signalled event returns immediately whatever interval was requested. The intended backoff therefore degenerated into a busy spin and the loop was really terminated by `constexpr size_t max_tries = 100`, not by the user's timeout. Measured on a single node with embedded Keeper: across 15228 waits requesting 120000 ms the longest wait was 0.086 s and none reached 1 s, and 25 of 694 updates were rejected at 2.7-3.2 s. Raising lock_acquire_timeout bought nothing: arms at 120 s and 600 s failed at the same ~3.2 s. In addition 47.5 per cent of the retries ended on ZBADVERSION from the parent-version CAS, which any other update invalidates even with no column conflict, so nearly half of a victim's budget made no progress on its own conflict. getLockForSyncMode had the same count-bound shape and was measured failing at about 6 s. Make an absolute deadline derived from lock_acquire_timeout the only failure condition and drop the try count as a bound. Wait on the conflicting update's own node instead of the hot parent directory, so the event fires when the blocking update actually finishes; a fresh Poco::Event is used per wait because the watch is one-shot, and tryGet tolerates ZNONODE so a node that disappeared in the meantime is observed immediately rather than blocking on an event that will never be set. After ZBADVERSION retry at once, since the version changed because some unrelated update committed and there is no conflict of this query to wait for. The acquisition attempt stays unconditional, so an uncontended update is still granted with lock_acquire_timeout = 0; that setting's semantics are unchanged here on purpose. Per-try ProfileEvents still increment, so 03100_lwu_35_lock_profile_events, which asserts exactly one try for an uncontended acquisition, is unaffected. The exception messages now report the elapsed budget and spell "lightweight" correctly. A query that used to fail after a few seconds may now wait up to lock_acquire_timeout before failing, which is the documented contract of the setting. Acquisition is still unfair: the EphemeralSequential node is created but not used for ordering. Fair queueing would need a predecessor-watch protocol and a mixed-version compatibility story and is not attempted here. The new test uses the existing *_lightweight_update_sleep_after_block_allocation failpoint, which holds the lock for 3000 ms, so it is deterministic and needs no contention: a 1000 ms timeout must fail with TIMEOUT_EXCEEDED having actually waited, a 60000 ms timeout must succeed, and an uncontended zero timeout must still succeed. It fails on unpatched master for both Keeper modes.
Review round 1 on the previous commit: address a signed-overflow regression introduced by the deadline, rate-limit the ZBADVERSION retry, make the wait interruptible, and give the test oracles that detect the removal of each mechanism. Deriving the deadline as steady_clock::now() + milliseconds(lock_acquire_timeout) multiplies the millisecond value by 1e6, because steady_clock::duration is int64 nanoseconds. SettingFieldTimespan::microsecondsFromUnits accepts up to INT64_MAX/1e6 = 9223372036854 seconds and there is no lock_acquire_timeout entry in SettingsConstraints, so any value above 9223372036.854 s overflows: signed overflow is undefined behaviour, and the wrap observed on a Debug build yields an already-expired deadline, so a contended update fails on its first try. Measured at lock_acquire_timeout = 10000000000: sync failed after 274 ms and auto after 133 ms, both reporting 1 try. There is no time_point arithmetic left in the file; the remaining time is a Stopwatch reading subtracted in the millisecond domain, where both operands are already Int64 milliseconds. The same arms now wait out the blocking update and succeed after about 2.2 s. The ZBADVERSION branch retried with no delay, and with the try count no longer a bound it could spin on Keeper for the whole timeout. It has no node to watch, since the version changed because an unrelated update committed, so it now sleeps min(50 ms, remaining) before retrying, following waitForCommittingOpsToFinish in StorageReplicatedMergeTree. With 16 same-column writers over 20 s the worst-case try count for one query drops from 221/228/176 to 115/116/115 across three repeats. Note this bounds the retry rate rather than the retry count, so no test arm asserts it; the measurement is the evidence. Poco::Event::tryWait is a bare pthread_cond_timedwait loop with no cancellation hook, so a single wait of up to lock_acquire_timeout left the query unkillable for that whole window while the caller held the table share lock taken in InterpreterUpdateQuery. The wait is now split into 3000 ms slices, the same value and reason as event_wait_timeout_ms in StorageReplicatedMergeTree, with QueryStatus::checkTimeLimit() polled before each slice as in MergeTreeDataPartWriterOnDisk. No bookkeeping is needed because a fresh event is already created per wait, so a slice that returns unset falls through to the loop's own re-evaluation. With a 20 s holder, a waiter with max_execution_time = 2 was interrupted at 3.03 s where before it ran the full 17.2 s. This also caps the argument handed to tryWait(long). 03100_lwu_57_lock_acquire_timeout gains, per mode, an arm with a huge but valid timeout, and overall a non-conflicting churn arm asserting a bounded PatchesAcquireLockTries plus a cancellation arm; the churn arm needs a hold longer than one chunk, which the 3000 ms failpoint cannot provide, so it uses eight unmerged parts and sleepEachRow instead. The 1000 ms arm's integer $SECONDS check is replaced by query_duration_ms from system.query_log asserting both a lower and an upper bound, which also removes its one-second-boundary flake surface. Three builds each missing one mechanism were checked: restoring the parent-directory watch, reverting the whole change, and removing the chunked wait all fail the test.
Splitting the wait into 3 s slices to poll query cancellation made the caller build a fresh Poco::Event, and hence register a fresh Keeper watch, for every slice. A timed out tryWait deregisters nothing: ZooKeeperImpl keys watch callbacks on the EventPtr and erases them only when the node's event actually arrives. A waiter on the default 120 s timeout therefore accumulated one live callback per slice on a single unchanged node, which multiplies by the number of waiters under exactly the concurrent workload this change targets, and drifts the ZooKeeperWatch metric because it is decremented only on fire. The slice loop moves into the wait helper so one registration serves the whole wait. The event is deliberately not reset between slices: the Keeper watch is one-shot, so a discarded signal would be the only wakeup the wait could ever have received. Also add PatchesAcquireLockBadVersionRetries, counting the retries caused by another update winning the parent-version CAS. Those retries have no node to wait on and back off a fixed 50 ms, so the counter gives that mechanism a test oracle that follows from the sleep itself: acquisition must have taken at least 50 ms per counted retry. The regression test gains an arm driving that CAS contention with pairwise-disjoint columns, and its huge-timeout arm drops from 1e10 s to 1e6 s. The retired value is consumed earlier in the same query by the outer table lock, which converts it to a nanosecond deadline and overflows above roughly 9223372036 s - a pre-existing limitation of every lock_acquire_timeout consumer, not of this loop. Co-Authored-By: Claude Opus 5 <[email protected]>
…gistration The test takes about 55 s (median 55.03 s, max 56.15 s over 50 runs), which the Fast test runners kill at their 60 s per-test timeout, so it is tagged long and skipped there via --no-long. The runtime is the ~45 s of lock holds that make the arms discriminate: shrinking the hold below one 3000 ms wait chunk was measured to destroy the cancellation arm, so the tag is the correct way to pay for the oracle. Registering the Keeper watch once per wait rather than once per 3 s chunk had no test coverage: moving the chunk loop back out of waitInterruptibly preserves interruptibility and every reference line while restoring a leaked callback per chunk, since a timed out tryWait deregisters nothing. The extra waiter reuses the cancellation arm's existing hold, so it costs no runtime, and counts the watched requests it issued in system.zookeeper_log: 1 on the fix against 7 across six chunks without it. system.zookeeper_log is preferred over the server-wide ZooKeeperWatch metric because the count is scoped to the waiter's own query, it separates 1 from 7 rather than 0 from 2, and parts.lib already reads that table. A waiter that spans fewer chunks than the bound allows would satisfy it while still re-registering, so the arm first asserts the acquisition really spanned three chunks; that guard was shown firing on a short-hold control.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 4 gate passes over 4 revisions,
Severity: ❌ blocker / Residual disclosed and deliberately not chased: lock acquisition is still unfair, since the Session id: cron:clickhouse-review-slot-9:20260810-070200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260810-051100 |
|
cc @CurtizJ @alesapin, could you review this? The Keeper lock acquisition for lightweight updates was bounded by a fixed 100 tries rather than by |
|
Workflow [PR], commit [4de66b6] Summary: ✅
AI ReviewSummaryThis PR reworks lightweight Findings
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 83/118 (70.34%) · Uncovered code |
clang-tidy's google-runtime-int rejects the platform-dependent `long`
spelling, and arm_tidy runs with -warnings-as-errors, so the cast added in
this PR broke the build:
error: consider replacing 'long' with 'int64' [google-runtime-int]
Poco::Event::tryWait takes a long, and the argument is Int64, so the cast
was written to make the narrowing explicit. It is unnecessary: Int64 is
int64_t, which is long on both Linux targets and long long on Darwin, and
long is 64-bit on all of them, so the implicit conversion is value
preserving on every platform ClickHouse builds for. This is also how the
other 30 tryWait call sites in src/ pass their argument, for example
ReplicatedMergeTreeSink.cpp with std::min<UInt64>. The value was already
bounded by max_wait_chunk_ms (3000) regardless.
Also trim waitInterruptibly's comment to the two invariants a reader needs
at that spot. Why re-registering per chunk would leak a watch callback, and
that Poco::Event ignores KILL QUERY and max_execution_time, are the reasons
for the design rather than local invariants, so they belong here: a timed
out tryWait deregisters nothing, and ZooKeeperImpl keys callbacks on the
event pointer, so a fresh event per chunk would leave one live callback per
chunk on an unchanged node.
Verified by compiling the translation unit with the project's own flags:
clang-tidy goes from one error to zero, and the build stays clean under
-Weverything -Werror for x86_64, aarch64 and both Darwin targets. The
emitted LLVM IR is identical apart from debug metadata, so behaviour is
unchanged, and 03100_lwu_57_lock_acquire_timeout still passes.
The test waited for a hardcoded block number via wait_for_block_allocated, which counts rows in the append-only system.zookeeper_log. run() starts three holders on one table, and block numbers are allocated sequentially, so only the first holder ever created block-0000000001: the second and third waits matched that stale row and returned without their own holder owning the lock. Measured on one table, three successive holders allocate 0001, 0002 and 0003, and an instrumented run of the old wait returns in 0 s on every call after the first. The arms still contended, but only by an incidental margin rather than by synchronisation: the old wait sleeps 0.3 s before its first query, while a holder needs 98-194 ms here to reach the failpoint. On a slower or loaded runner that margin inverts and the arms silently stop exercising the lock. Both sites now share wait_for_lock_held, which counts the children of a node the table always has: the single lock node in sync mode, in_progress/update-* in auto mode. Those are zero until a holder owns the lock and drop back to zero when it is released, so the predicate observes current state instead of history. It also fails loudly instead of falling through, which the open-coded loop in run_cancel did on timeout. The arms that succeed by design now also assert that the lock was granted only after waiting, using PatchesAcquireLockMicroseconds rather than the whole query duration, which is inflated by the update's own work and was measured earlier in this PR to mask the signal. Verified in both directions: OK on the PR head, and FAIL on a binary with the source reverted to the PR base, where 6 of the 12 reference lines differ. 50 of 50 randomized runs pass, median 55.95 s.
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. Object file sizes76 object files changed (+18.63 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7845 translation units recompiled, 10855 s compile time in total, 7799 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
|
…xed time The test held the lightweight update lock with rmt_lightweight_update_sleep_after_block_allocation, whose action is a fixed 3000 ms sleep that has already started by the time the lock node appears. What remained of it when a waiter began was therefore whatever was left after block allocation, a poll interval and a client round trip, which on a loaded sanitizer runner tends to zero. All six assertions in run() compared the waiter's own timing against that residue, so all six flipped: 0 of 5 flaky check runs passed on amd_asan_ubsan, 2 of 5 on amd_tsan, 3 of 5 on amd_msan. In every flip the server behaved better than asserted -- the lock was granted where the test demanded a timeout, or contention did not materialise -- so the test was calling correct behaviour a failure. Hold the lock with the infinite_sleep failpoint instead, following 04162_system_cancel_view_during_refresh and 04095_wait_fp_pause_disable: the holder parks inside sleep() while holding the lock and stays there until this test releases it, so no arm races a deadline that started expiring earlier. The assertions no longer read a clock either. Being inside the wait is now PatchesAcquireLockTries from system.processes, and being granted the lock after contention is a try count rather than an acquisition time, both of which are facts about where a query got to that a slow runner cannot change. The 1000 ms arm additionally bounds the try count, which is what distinguishes a timeout that ends the wait from a fixed number of attempts each waiting the whole timeout: at that value the pre-fix code takes 100 attempts and 101 s. run_churn gets the same treatment and now waits for the churn to commit ten times before releasing, because a parent directory watch is only woken by commits that happen while the waiter is parked. Its lower bound moves from 1 to 2 so an uncontended run cannot satisfy it. Verified in both directions with build ids asserted on the server: green on the PR head and 50 of 50 randomized runs, red on a binary with the src changes reverted (6 of 12 reference lines, including both 1000 ms arms and churn). An uncontended waiter reports 1 try, so the contended assertions cannot pass vacuously. Median runtime 43.9 s, down from 55.0 s. Co-Authored-By: Claude Fable 5 <[email protected]>
Waiting for PatchesAcquireLockTries to become positive was the wrong synchronization point: both modes increment it before sending the attempt it counts, so a fast poll could release the holder while that first attempt was still in flight and let it succeed. Wait for the watch the waiter registers instead, which exists only once an attempt has come back reporting the lock taken. Two oracles could also pass without the property they check. The 1000 ms arm asserted only a lower bound on duration, so an implementation that multiplied the configured timeout still produced the expected line; it now also bounds the duration from above. run_churn suppresses every churn error and polled for ten commits without insisting it saw them, so a fixture that never churned would have left a parent directory watch indistinguishable from a per-conflict one; it now fails explicitly instead of falling through. Green on the PR head, 50 of 50 randomized runs, and red on a binary with the src changes reverted (6 of 12 reference lines). Co-Authored-By: Claude Fable 5 <[email protected]>
…sing The log tables outlive the tables this test drops, and clickhouse-test --database reuses a single database across tests, a mode the stress job uses. Tagging by database alone therefore let one run match another run's rows: the wait for a registered watch could return on a previous run's watch, and the CAS arm aggregated every historical QueryFinish row for the same log comment. Tag with a per-run id instead. run_churn also released the holder before stopping the churn. Those commits had already woken a parent directory watch as many times as they were going to, but once the waiter became runnable they could make it lose the parent version compare-and-swap any number of times, which the five attempt bound does not allow. Stop and reap the churn first. Green on the PR head and 50 of 50 randomized runs; red on a binary with the src changes reverted (6 of 12 reference lines). Co-Authored-By: Claude Fable 5 <[email protected]>
…-acquire-timeout-deadline # Conflicts: # src/Storages/MergeTree/PatchParts/PatchPartsLock.cpp
Both Keeper modes poll cancellation through the same waitInterruptibly helper, but the only multi-slice cancellation arm hard-coded update_parallel_mode = 'auto'. Replacing the sync call site with a single uninterruptible tryWait therefore kept the test green: measured, that mutation passes while deleting checkTimeLimit from the shared helper does redden it. The new arm lives in run(), which is already mode-parameterized, so it covers sync and auto. It does not read a clock: a waiter whose max_execution_time is shorter than both the hold and lock_acquire_timeout must fail with its own time limit, and which error ends the wait is a fact about where the query got to rather than about how long anything took. An uninterruptible wait reports the lock timeout instead. Verified in both directions with the Build ID asserted on the server per arm: OK on the fix (51.86 s), and FAIL on a sync-only uninterruptible-wait mutation, reddening exactly the new sync line.
…n-replicated tables The chunked wait added for the Keeper-backed paths left the plain MergeTree ones blocked in a single try_lock_for/wait_for call, so on a non-replicated table a lightweight UPDATE stayed unkillable until lock_acquire_timeout: measured with a parked holder and max_execution_time = 2, the waiter ran the full 30 s and died of the lock timeout, against 3.1 s and its own time limit on ReplicatedMergeTree. The chunk-and-poll loop becomes one shared helper taking the wait as a callable, so all four call sites use the same implementation. Both plain paths check the lock once before waiting, which is what keeps lock_acquire_timeout = 0 working for an uncontended update, as the Keeper paths already did. The test grows a plain MergeTree arm per mode with the same clock-free oracle: which error ends the wait. It fails on exactly those two lines on a build with only this part removed.
…e lock The chunked wait polled QueryStatus::checkTimeLimit() only before each chunk, so a cancellation arriving while the final chunk was waiting was never observed: the helper returned false and every caller turned that into TIMEOUT_EXCEEDED naming the lock timeout instead of the query's own limit. With lock_acquire_timeout below the 3000 ms chunk size the whole wait is a single chunk, so the query's limit could never be reported at all. Measured on one binary, holder parked while holding the lock, waiter at lock_acquire_timeout = 2.5 s with max_execution_time = 2 s: before, all four paths (both Keeper modes and both plain MergeTree modes) failed at ~2.52 s with "Failed to get lock in 2500 ms"; after, each ends on "maximum: 2000 ms". Both errors are TIMEOUT_EXCEEDED, so the test oracle matches on the message. ReplicatedMergeTreeSink::commitPart checks after each timed-out wait step for the same reason. A per-iteration check would be redundant with the next iteration's, so only the loop-exit path is guarded here. The query_status lookup is hoisted out of the loop since it no longer happens once per chunk. The watch arm of the test held the lock for the duration of a ~20 s update, whose length randomized settings are free to change, so its anti-vacuity guard (the wait must span at least three chunks) failed intermittently in the flaky check. The holder now parks at the infinite_sleep failpoint and is released after a fixed number of chunks, making the span chosen by the test: measured 12331-12345 ms against the 9000 ms bound over six randomized runs. This also drops the eight-part fixture the old hold needed.
…or it The arm ran six writers on disjoint columns for four wall-clock seconds and relied on two of them overlapping inside the window between reading the in_progress version and using it in the compare-and-swap. That window is microseconds wide, so whether any writer lost the CAS depended on how many updates the runner managed to start concurrently. On an idle machine about a hundred updates ran and a quarter of them retried; in the failing CI job the same arm got fourteen updates with at most three ever in flight and none retried, so the arm's own anti-vacuity guard reported it had never reached contention. A pauseable failpoint at that point lets the test park one update between the read and the compare-and-swap, commit an unrelated update while it is parked, and then release it. The victim loses the compare-and-swap exactly once, so the retry count is pinned by the construction rather than sampled from a race. The previous oracle also asserted that acquiring took at least one backoff period. That is dropped: PatchesAcquireLockMicroseconds encloses the parked time, so under this construction the bound holds even on a build with the backoff removed, which was confirmed by building that binary and watching the arm still pass. The wait for the pause is bounded so that a failure to park reports which step failed instead of hanging until the test is killed. Co-Authored-By: Claude Opus 5 <[email protected]>
| Stopwatch acquire_watch; | ||
|
|
||
| for (size_t i = 0; i < max_tries; ++i) | ||
| /// The first attempt is unconditional, so an uncontended update still succeeds at zero timeout. |
There was a problem hiding this comment.
lock_acquire_timeout is documented as 0 — No locking timeout in both src/Core/Settings.cpp and docs/reference/settings/session-settings/other.mdx, but this code still treats 0 as “make one optimistic attempt, then fail immediately if the lock is contended”. The same pattern remains in getLockForAutoMode and in the plain MergeTree helpers, and the new zero-timeout arms only cover the uncontended case.
That means the PR still does not fully honor the setting it is meant to fix: a lightweight UPDATE with lock_acquire_timeout = 0 cannot wait indefinitely for a conflicting update the way other locking requests do. Can we make 0 mean an unbounded wait here as well (like RWLockImpl::getLock), and add a contended lock_acquire_timeout = 0 arm that waits for the parked holder to release instead of throwing TIMEOUT_EXCEEDED?
There was a problem hiding this comment.
The reading of the docs is right, and the gap is real: with lock_acquire_timeout = 0 a contended
lightweight UPDATE fails instead of waiting. But it is pre-existing, not something this PR
introduces, so I am not fixing it here.
Measured on a debug build, holder parked at infinite_sleep and the victim reading the column the
holder updates (hasConflict compares updated-vs-used), 3/3 runs each:
| arm | lock_acquire_timeout = 0, contended |
|---|---|
| unpatched master | Code: 159, Failed to get lock with 100 tries ... in auto mode |
| this PR | Code: 159, Failed to get lock in 0 ms with 1 tries ... in auto mode |
Both throw TIMEOUT_EXCEEDED; only the message changes. Controls for the same fixture: the lock is
registered in Keeper before the victim runs (in_progress child present), and a finite
lock_acquire_timeout = 1 throws on both arms - at 101459 ms on master against 1243 ms here, which
is this PR's actual subject.
So making 0 mean an unbounded wait is a separate behaviour change to the setting's contract, on a
path this PR deliberately leaves alone: the unconditional first attempt is what keeps an uncontended
zero-timeout update working, and the same zero-means-fail-immediately shape lives in
getLockForSyncMode and the plain MergeTree helpers. You raised the same axis earlier on
#106961, and it is tracked separately from this PR. I would rather land the deadline fix and then
change the zero semantics in one place, for every consumer of the setting, with its own contended
arms.
CI finish ledger - fd39bc6Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
This PR changes Two merged candidates were checked against the tree the run actually built (praktika Session id: cron:our-pr-ci-monitor:20260812-083000 |
# Conflicts: # src/Common/FailPoint.cpp
| if (query_status) | ||
| query_status->checkTimeLimit(); | ||
|
|
||
| if (wait_chunk(std::min(max_wait_chunk_ms, remaining_ms))) |
There was a problem hiding this comment.
checkTimeLimit() only runs before a wait slice and after a timed-out final slice. If the query times out or is cancelled while it is inside a slice that later returns success, this helper returns true without another cancellation check.
Concrete trace: max_execution_time = 2, lock_acquire_timeout = 30, and the holder releases at about 2.1 s. The first 3 s wait_chunk then returns success, lockSyncMutex / lockColumns treat that as a granted lock, and the Keeper paths do another acquisition attempt, even though the query's own deadline has already passed. The asynchronous CancellationChecker only fires on a coarse grid, so a small update can slip through this window and finish before the background timeout catches up.
Can we call query_status->checkTimeLimit() once on the success path too, before returning from waitInterruptibly? The current test only covers the case where the lock is still held after the deadline, so this success-after-timeout edge stays uncovered.
There was a problem hiding this comment.
You are right about the control flow: return true at the successful wait_chunk bypasses the
post-loop checkTimeLimit(), so a deadline that expires inside a slice which then succeeds is not
observed by this helper. I am not disputing that.
I measured your trace rather than reasoning about it, because the outcome is what decides this.
max_execution_time = 2, lock_acquire_timeout = 30, holder released inside the first 3000 ms
slice but after the deadline (2.2 / 2.5 / 2.8 s):
| mode | release | slice returned success | error raised | rows committed |
|---|---|---|---|---|
| auto | 2.2 s | yes (2362 ms) | maximum: 2000 ms |
0 |
| auto | 2.5 s | yes (2654 ms) | maximum: 2000 ms |
0 |
| sync | 2.5 s | yes (2658 ms) | maximum: 2000 ms |
0 |
Elapsed tracking the release instead of the 3000 ms chunk boundary is what shows the slice really
did return success, since both paths raise the same Code: 159. The query still dies of its own
limit and commits nothing. Enforcement is QueryStatus::checkTimeLimit from
MergeTreeDataSelectExecutor::selectPartsToRead (MergeTreeDataSelectExecutor.cpp:2859, and
:1066 per part), which is the first post-acquisition step and runs before any patch part is
written; PipelineExecutor::execute opens with the same check at PipelineExecutor.cpp:204.
Controls, since an oracle that cannot fail would prove nothing here: the same fixture with
max_execution_time = 0 commits 3 of 3 rows in both modes, and lock_acquire_timeout = 1 against
a still-held lock throws Failed to get lock in 1000 ms with 2 tries. My first version of this
probe was vacuous, the victim predicate matched zero rows while the holder was parked, and the
positive control is what caught it.
So I am not adding the check, for three reasons beyond the missing consequence:
ReplicatedMergeTreeSink.cpp:1333-1337has the same shape deliberately, breaking on a
successfultryWaitand reachingcheckTimeLimit()only on the timed-out path. That is the
precedent this PR was asked to converge on.- It would turn a successful acquisition into an error. At that point the ephemeral node and the
in_progress_columnsentry already exist, so each caller
(StorageMergeTree.cpp:1187,:1198) would have to release a lock it was told it never got. - The deadline is already honoured immediately afterwards, as measured above.
The residual is real and worth stating: one already-elapsed post-lock step runs before the
deadline is enforced. It is not user-reachable as wrong results, data loss or a hang, so I am
recording it here rather than expanding this PR.
This is the third time this axis has come up on this PR, so I am leaving the thread here for a
human rather than iterating further.
CI finish ledger — 88ab20eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Notes for readers:
Session id: cron:our-pr-ci-monitor:20260818-000000 |
|
Fixing PR for the Root cause: the self-extracting bundle destroys itself. |
One conflict: the APPLY_FOR_FAILPOINTS list tail in src/Common/FailPoint.cpp, where master appended smt_force_takeover_predicate_true and smt_takeover_fake_hardware_error_after_set while this branch appended patch_parts_lock_pause_before_cas. Both sides kept; master's entries stay in place and this branch's entry moves to the end of the list. src/Common/ProfileEvents.cpp and src/Storages/StorageMergeTree.cpp merged automatically. Verified afterwards that the merged tree differs from master 573230b by exactly the seven files of this PR and by no submodule pin.
The five cancellation checks looked for the literal "maximum: 2000 ms". The query deadline error now renders its limit as a fixed-point number, so that string no longer occurs and all five checks silently reported "not cancelled" even though the wait was interrupted on time. Match on "Timeout exceeded:" together with "maximum:" instead. Both tokens are independent of how the number is formatted, and the pair occurs only in QueryStatus::checkTimeLimit, so the checks still tell the query's own deadline apart from the lock timeout, which is what they are there to distinguish. Verified against a server built from this branch: with no deadline the update fails on the lock timeout and the check reads 0, with a two second deadline it reads 1, and the test as a whole matches its reference again.
The comment said values near INT64_MAX / 1e6 were avoided because the outer table lock converts the same setting to a nanosecond deadline and overflows first. That conversion now saturates and the tree carries a test that takes a hundred billion seconds through the table lock, so the reason no longer holds and the sentence is simply wrong here. Only the sentence is removed. Raising the arm to a hundred billion seconds was tried and does not buy anything: with the wait replaced by a single converted deadline the arm still passes, because the overflowed product wraps to about 7.7e18 nanoseconds, which is positive and far longer than the hold. Detecting that shape needs a value picked for a particular wrap, which is undefined behaviour to rely on, so the arm keeps its previous value and covers a large timeout being accepted and waited out rather than overflow.
5a9fd96
Reproducer-- Single node with embedded Keeper. Three sessions.
CREATE TABLE t (id UInt64, s String, v UInt64, w UInt64)
ENGINE = ReplicatedMergeTree('/clickhouse/tables/t', '1') ORDER BY id
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO t SELECT number, 'aa', 0, 0 FROM numbers(50);
-- session 1 — holds the lock ~25s, writes `s`
SET enable_lightweight_update = 1;
UPDATE t SET s = 'xx' WHERE sleepEachRow(0.5) = 0
SETTINGS update_parallel_mode = 'auto', function_sleep_max_microseconds_per_block = 300000000;
-- session 2 — churn, in a loop: writes `w`, conflicts with nobody, only changes
-- the `lightweight_updates/in_progress` directory the waiter watches
SET enable_lightweight_update = 1;
UPDATE t SET w = w + 1 WHERE id = 1 SETTINGS update_parallel_mode = 'auto';
-- session 3 — victim, reads `s`, so it must wait for session 1
SET enable_lightweight_update = 1;
UPDATE t SET v = 200 WHERE s = 'xx'
SETTINGS update_parallel_mode = 'auto', lock_acquire_timeout = 60;
-- 26.7/26.6/26.5/26.3/25.8, after ~2s:
-- Code: 159. DB::Exception: Failed to get lock with 100 tries for
-- lightwegiht update in auto mode. (TIMEOUT_EXCEEDED)
-- Clean on master (#114125): waits out the holder and is granted the lock at ~25s.Results:
Backport the fix to CC introducing PR author: @CurtizJ CC component owner: @scanhex12 @Michicosun Analysis metadata
|
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed lightweight
UPDATEonReplicatedMergeTreebeing rejected withTIMEOUT_EXCEEDEDafter a few seconds under concurrent updates, long before the configuredlock_acquire_timeoutelapsed. The Keeper lock acquisition loop was bounded by a fixed number of tries instead of by the timeout, so raisinglock_acquire_timeouthad no effect.Description
A valid lightweight
UPDATEwas rejected withafter about 3 seconds, with
lock_acquire_timeoutat 120 seconds and the cluster granting locks normally.update_parallel_modedefaults toauto, so this is the default path.Root cause:
getLockForAutoModewatched the parent directory.../lightweight_updates/in_progress, whose child set changes on every concurrent update, andPoco::Eventreturns at once when already signalled: across 15228 waits requesting 120000 ms the longest was 0.086 s, so the loop spun tomax_tries = 100.getLockForSyncModehad the same shape, at ~6 s.Elapsed time against
lock_acquire_timeoutis now the only failure condition, and the wait is on the conflicting update's own node:Stopwatchsubtraction in the millisecond domain: the setting has no upper constraint and asteady_clockdeadline overflows above ~9223372036 s.ZBADVERSIONfrom the parent-version CAS, which any unrelated update invalidates, has no node to wait on, so it backs off 50 ms instead of retrying at once, counted by a newPatchesAcquireLockBadVersionRetriesprofile event.MergeTreeones that waited in a singletry_lock_for/wait_for: with a held lock andmax_execution_time = 2, each now ends on its own limit.The first attempt stays unconditional, so an uncontended update still succeeds at
lock_acquire_timeout = 0. Behaviour change: a query that failed after a few seconds may now wait up tolock_acquire_timeout, as the setting documents.Acquisition is still unfair (the
EphemeralSequentialnode is created but not used for ordering); fair queueing needs a predecessor-watch protocol and a mixed-version story, out of scope.Validation
Debug build, single node with embedded Keeper. 15 concurrent same-column updaters split into three arms by
lock_acquire_timeout, in one concurrency window. Time-to-failure must track the timeout.lock_acquire_timeoutBefore, every arm failed at the same ~3.2 s regardless of its timeout; after, only the 3 s arm fails, at its own. Same for
update_parallel_mode = 'sync'(~6.2 s before).Each mechanism was checked against a build with only that mechanism removed, Build IDs asserted:
ZBADVERSIONbackoff removed: worst-case tries for one query 221/228/176 across three repeats, against 115/116/115 with it (measured directly, not asserted by the test).max_execution_time = 2runs 17.2 s uninterrupted, against stopping at 3.03 s. With only the loop-exit poll removed, all fourlock_acquire_timeout = 2.5arms report the lock timeout at ~2.52 s instead of their own 2 s limit.03100_lwu_57_lock_acquire_timeoutcovers the timeout arms, a large timeout, churn bounding the try count, a lost parent-version CAS, cancellation on both engines and in the single-slice case, and watch registration by one parked waiter. It fails on unpatched master. Every arm is fixed by construction rather than timed: holders and the CAS victim park at failpoints, so the watch arm's span is 12331-12345 ms against a 9000 ms bound over six randomized runs, and the CAS arm pins its one retry. Parked time falls insidePatchesAcquireLockMicroseconds, so that arm does not assert the backoff duration.03100_lwu_35_lock_profile_eventsstill passes.Workflow [PR]
Sync PR [sync-upstream/pr/114125]