Skip to content

Honour lock_acquire_timeout for the lightweight update lock in Keeper - #114125

Merged
alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:lwu-lock-acquire-timeout-deadline
Aug 28, 2026
Merged

alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:lwu-lock-acquire-timeout-deadline

Conversation

@groeneai

@groeneai groeneai commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed lightweight UPDATE on ReplicatedMergeTree being rejected with TIMEOUT_EXCEEDED after a few seconds under concurrent updates, long before the configured lock_acquire_timeout elapsed. The Keeper lock acquisition loop was bounded by a fixed number of tries instead of by the timeout, so raising lock_acquire_timeout had no effect.

Description

A valid lightweight UPDATE was rejected with

Code: 159. Failed to get lock with 100 tries for lightwegiht update in auto mode. (TIMEOUT_EXCEEDED)

after about 3 seconds, with lock_acquire_timeout at 120 seconds and the cluster granting locks normally. update_parallel_mode defaults to auto, so this is the default path.

Root cause: getLockForAutoMode watched the parent directory .../lightweight_updates/in_progress, whose child set changes on every concurrent update, and Poco::Event returns at once when already signalled: across 15228 waits requesting 120000 ms the longest was 0.086 s, so the loop spun to max_tries = 100. getLockForSyncMode had the same shape, at ~6 s.

Elapsed time against lock_acquire_timeout is now the only failure condition, and the wait is on the conflicting update's own node:

  • Remaining time is a Stopwatch subtraction in the millisecond domain: the setting has no upper constraint and a steady_clock deadline overflows above ~9223372036 s.
  • ZBADVERSION from 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 new PatchesAcquireLockBadVersionRetries profile event.
  • The wait is split into 3 s slices polling query cancellation, plus one poll on leaving the loop so a cancellation arriving in the last slice is not reported as the lock timing out. All four paths share this helper, including the plain MergeTree ones that waited in a single try_lock_for/wait_for: with a held lock and max_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 to lock_acquire_timeout, as the setting documents.

Acquisition is still unfair (the EphemeralSequential node 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.

arm lock_acquire_timeout before after
A 120 s (default) 13/237 rejected at 3.03/3.23/3.62 s 0/205 rejected
B 600 s 11/233 rejected at 3.03/3.26/3.48 s 0/219 rejected
C 3 s 19/242 rejected at 3.14/3.25/3.51 s 11/269 rejected at 3.08/3.08/3.10 s

Before, 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:

  • parent-directory watch restored: 19 lock tries against 2, passing the table above identically, i.e. the deadline alone turns a premature failure into a busy spin.
  • ZBADVERSION backoff 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).
  • unchunked wait: a waiter with max_execution_time = 2 runs 17.2 s uninterrupted, against stopping at 3.03 s. With only the loop-exit poll removed, all four lock_acquire_timeout = 2.5 arms report the lock timeout at ~2.52 s instead of their own 2 s limit.
  • watch re-registered per slice: a waiter parked across six slices registers 7 watches on the node, against 1.

03100_lwu_57_lock_acquire_timeout covers 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 inside PatchesAcquireLockMicroseconds, so that arm does not assert the backoff duration. 03100_lwu_35_lock_profile_events still passes.


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

groeneai and others added 4 commits August 9, 2026 18:17
…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 gate passes over 4 revisions,
11 findings; each pass followed by an independent cold review of the resulting code).

# Sev Finding Verdict Evidence / action
1 ❌ A large lock_acquire_timeout overflows a steady_clock deadline, so a contended update fails instantly (the opposite of this PR's contract) AGREE, fixed @ d842cae Raised independently by my own review and the gate. All time_point arithmetic removed; remaining time is a Stopwatch subtraction in the millisecond domain. At 1e10 s the pre-fix build fails after 133-274 ms reporting 1 try; the fixed build waits out the hold and succeeds
2 ⚠️ ZBADVERSION retried with no delay and no longer count-bounded, so a waiter spins on Keeper for the whole timeout AGREE, fixed @ d842cae 50 ms backoff, matching the precedent in this function's own caller. Worst-case attempts for one query 221/228/176 without it against 115/116/115 with it
3 ⚠️ The wait was uninterruptible, so KILL QUERY and max_execution_time could not fire AGREE, fixed @ d842cae 3 s slices polling QueryStatus::checkTimeLimit(). Needed a hold longer than one slice to discriminate at all: unchunked runs 17.2 s uninterrupted, chunked stops at 3.03 s
4 ⚠️ The test could not detect removal of either mechanism the change adds AGREE, fixed @ d842cae, b045dd3, daaeeef Answered over three rounds: churn arm with a bounded attempt oracle, CAS-contention arm, cancellation arm, watch-registration arm, each shown red on a build with only that mechanism removed and green on the fix, 3/3
5 ❌ The huge-timeout arm drove signed-overflow UB through pre-existing code, aborting sanitizer builds AGREE, fixed @ b045dd3 Raised independently by my own review and the gate. 1e10 s is consumed earlier in the same query by the table-share lock, which converts it to a nanosecond deadline at the identical threshold. Arm retargeted to 1e6 s = 1e15 ns, 9223x below INT64_MAX
6 ⚠️ Each 3 s slice registered another live Keeper watch callback on the same node AGREE, fixed @ b045dd3 The watch is now registered once per outer iteration and the slices reuse it. ZooKeeperWatch samples 3 s apart with 3 waiters: 5,8,11,14,17 per-slice against a flat 5,5,5,5,5
7 ❌ The test ran within a few seconds of the Fast test 60 s per-test timeout AGREE, fixed @ daaeeef Raised independently by my own review and the gate. 55.03 s median / 56.15 s max over 50 runs, and the runner kills the process group at 60 s. Tagged long, which both --no-long paths skip; verified in both directions with the same runner and binary
8 ⚠️ Nothing detected the watch-registration fix being reverted AGREE, fixed @ daaeeef Query- and path-scoped count of watch-carrying requests in system.zookeeper_log: 1/1/1 on the fix against 7/7/7 on a build that re-registers per slice, plus a guard asserting the waiter really spanned three slices, shown firing on a short-hold control
9 ❌ A lock can be granted on an attempt begun after the timeout elapsed DISAGREE lock_acquire_timeout is documented as how long a request waits before failing, not a deadline invalidating a granted lock, and the repo's canonical timed lock behaves identically: RWLockImpl::getLock grants when the predicate became true at or after the deadline with no post-deadline recheck, and that is the very lock guarding this same UPDATE. Adding the recheck would make this lock stricter than the primitive it composes with and turn completed work into spurious TIMEOUT_EXCEEDED
10 ⚠️ The reduced huge-timeout arm no longer exercises the overflow-safe arithmetic DISAGREE The arithmetic is right, but the finding concedes its own load-bearing step: the outer table lock prevents any unsafe value reaching this code, converting the same setting at the identical threshold, so no value reachable from SQL isolates this loop. That is exactly why finding 5 required the retarget. Re-litigating would restore finding 5
11 ⚠️ checkTimeLimit's false return is discarded, so timeout_overflow_mode = 'break' cannot stop the wait DISAGREE In the default throw mode both KILL QUERY and max_execution_time throw from ProcessList before the bool exists, so nothing is discarded on the paths this change claims. In break mode the bool means "return the partial result" and a lock waiter has none. Every peer waiter in the tree discards it identically, including the precedent this chunking was modelled on
12 ⚠️ The test stays green if the 100-attempt cap is restored alongside the deadline DISAGREE Mechanism conceded and verified: I re-traced all 12 reference lines and a re-added cap leaves every one green. Refuted at the remedy's necessary step, since both mechanisms this PR adds are attempt-rate reducers: the 50 ms backoff caps lost-CAS retries at 20/s, and the per-conflict watch cuts round-trips ~52%. Structurally a waiter that sees one conflict-free listing wins the CAS and returns, so exceeding 100 attempts is confined to the branch the backoff rate-limits. The fixture that reaches it needs 16 writers for 20 s and yields 115/116/115 attempts, a 15% margin over the threshold on an unloaded debug build where sanitizers run ~20x slower; at test-affordable size the same statistic overlaps between arms (26/22/37 with against 49/39/34 without). This is the oracle class already measured and rejected three times here, and the by-construction inequality now committed was adopted in its place. It also contradicts finding 7: a 16-writer arm adds ~20 s to a test that just needed the long tag to survive

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence
and are terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped; one
finding of my own (the cancellation arm's exposure to randomized settings) was dropped after my
own follow-up verification refuted it.

Residual disclosed and deliberately not chased: lock acquisition is still unfair, since the
EphemeralSequential node is created but not used for ordering. That is in the description.

Session id: cron:clickhouse-review-slot-9:20260810-070200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two: 15 same-column concurrent updaters reproduce Code: 159 ... for lightwegiht update in auto mode (25 of 694 updates starved, 100 tries each, no grant); and the failpoint-based test, which needs no contention and fails 1/1 on unpatched master.
b Root cause explained? Yes. The watch was on the parent dir .../in_progress (PatchPartsLock.cpp:102), whose children change on every concurrent update; Poco::Event auto-resets and waitImpl (Event_POSIX.cpp:106-154) returns at once when already set, so tryWait(lock_acquire_timeout) never waited (15228 waits requesting 120000 ms, max 0.086 s, none >= 1 s). The real bound was constexpr size_t max_tries = 100.
c Fix matches root cause? Yes. Elapsed time against lock_acquire_timeout becomes the only failure condition, computed by Stopwatch subtraction in the millisecond domain so a large timeout cannot overflow; the wait moves to the conflicting update's own node; ZBADVERSION (47.5% of a victim's retries, invalidated by unrelated updates) backs off 50 ms since it has no node to watch; the wait is chunked at 3 s and polls query cancellation. No widened bound, no no-random-* tag, no guard at the failure site.
d Test intent preserved / new tests added? Yes. Nothing weakened or removed. 03100_lwu_35_lock_profile_events, which pins ProfileEvents['PatchesAcquireLockTries'] == 1 exactly, still passes; 03100_lwu_14_parallel (the AUTO-branch control) still passes. New test 03100_lwu_57_lock_acquire_timeout covers both Keeper modes, a large timeout, non-conflicting churn with a bounded lock-try oracle, CAS contention with a per-retry sleep lower bound, cancellation, and a bound on the watches one parked waiter registers. It is tagged long (~55 s median over 50 runs), so Fast test skips it via --no-long instead of killing it at the 60 s per-test timeout.
e Both directions demonstrated? Yes. Pre-fix, arms at 120 s / 600 s / 3 s all fail at the same ~3.2 s; post-fix only the 3 s arm fails, at 3.07-3.14 s. The new test reddens on unpatched master and on a build with the parent-directory watch restored (19 lock tries against 2) and on one with the chunked wait removed (a waiter with max_execution_time = 2 runs 17.2 s uninterrupted against 3.03 s). A huge timeout fails at 133-274 ms on the first try before the overflow fix and succeeds after waiting 2.2 s with it. Registering the watch per 3 s slice instead of once makes a waiter parked across six slices set 7 watches on the node against 1, which the test now asserts (red 3/3 on that build, green 3/3 on the fix, with a guard that the waiter really spanned three slices - shown firing on a short-hold control). The ZBADVERSION backoff now has a deterministic oracle too: with PatchesAcquireLockBadVersionRetries, acquisition must have taken at least 50 ms per counted retry, which reddens 3/3 on a no-backoff build and passes 3/3 on the fix. Build IDs asserted on every arm.
f Fix is general across code paths? Yes. Both Keeper carriers fixed: getLockForAutoMode and getLockForSyncMode (the latter measured failing at ~6.2 s, not assumed). Deliberately unchanged and verified already time-bound: PlainLightweightUpdatesSync::lockColumns (wait_for(lock, ms, pred)) and StorageMergeTree::getLockForLightweightUpdate (try_lock_for(ms)); async mode takes no lock. Single caller StorageReplicatedMergeTree.cpp:8658; SharedMergeTree inherits the fix.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers are not applicable (Keeper coordination loop, no data types). The input axis is the timeout: covered at 0, 1 s, 3 s, 60 s, 120 s, 600 s and 1e6 s. Values near the shared steady_clock ceiling are excluded on purpose: the outer RWLock (RWLock.cpp:104) converts the same setting to a nanosecond deadline and overflows at the identical 9223372036 s threshold, so no SQL-reachable value isolates this loop. 1e6 s = 1e15 ns is 9223x below INT64_MAX. getRemainingMs clamps at zero so an exhausted timeout yields tryWait(0), never a negative interval, and the value handed to Poco::Event::tryWait(long) is capped at the 3 s chunk.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changed. SettingsChangesHistory.cpp needs no entry, confirmed rather than assumed: it contains zero ProfileEvent references and does not list the sibling PatchesAcquireLockTries added by the same feature. The new PatchesAcquireLockBadVersionRetries is additive in system.events; no test snapshots the event list (02394_every_profile_event_must_have_documentation only requires a description >= 10 chars, which it has). No Keeper layout, node content or serialization change, so no mixed-version concern. lock_acquire_timeout = 0 keeps its current behaviour (uncontended update still granted, 3/3). The user-visible timing change - failing later, up to the configured timeout - is what the setting documents and is called out in the description.
i Invariants and contracts preserved? Yes. Mutual exclusion is untouched: the same EphemeralSequential node created by the same tryMulti with the same parent-version CAS; only the waiting and termination policy changed. EphemeralNodeHolder ownership and release paths are unchanged; no new lock or shared state (the stopwatch and each event are function-local). Watch liveness verified on all three release paths (explicit remove, session expiry via Close, client-side session loss), and the tryGet guard closes the lost-wakeup window since it tolerates ZNONODE. The watch is registered once per outer iteration and the slices reuse that one event, so a timed-out slice leaks no callback (ZooKeeperImpl.cpp:1300-1303 keys callbacks on the EventPtr and :1185-1193 erases only when the event arrives). The event is not reset between slices: the watch is one-shot, so discarding a set state would drop the only wakeup available. Cancellation now throws from inside the acquisition loop, before any lock node is created, so no partially-acquired state can leak.

Session id: cron:clickhouse-impl-slot-40:20260810-051100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin, could you review this? The Keeper lock acquisition for lightweight updates was bounded by a fixed 100 tries rather than by lock_acquire_timeout, and its tryWait watched the hot in_progress parent directory, so an already-signalled event made the wait return immediately and a valid UPDATE was rejected after about 3 seconds with a 120 second timeout configured.

@CurtizJ CurtizJ self-assigned this Aug 10, 2026
@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4de66b6]

Summary: ✅


AI Review

Summary

This PR reworks lightweight UPDATE lock acquisition so Keeper-backed waits are bounded by elapsed lock_acquire_timeout, watch the conflicting update-* node instead of the hot parent directory, and poll query cancellation in both Keeper and plain MergeTree paths. The main starvation fix looks sound, but two contract gaps remain in the current head, so I would not approve it as-is.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Honour lock_acquire_timeout for the lightweight update lock in Keeper #114125#discussion_r3797112527] [src/Storages/MergeTree/PatchParts/PatchPartsLock.cpp:75-81, 131-133, 211-214, 387-405; src/Storages/StorageMergeTree.cpp:1226-1235, 3784-3802; src/Storages/StorageReplicatedMergeTree.cpp:8727-8750] waitInterruptibly only calls checkTimeLimit() before each slice and after a timed-out final slice. If the blocker releases after max_execution_time has already expired but before the slice ends, all four lock paths treat that wakeup as success and continue. On plain MergeTree the expired query can then enter waitForCommittingInsertsAndMutations() with no further deadline check; on replicated tables with update_sequential_consistency = 1 it can continue into waitForCommittingOpsToFinish(). That breaks the PR's new "prompt cancellation while waiting for the lightweight-update lock" contract, and the current test only covers the easier case where the lock is still held after the deadline.
    Suggested fix: re-check QueryStatus on the success path before acting on a wakeup. For Keeper waits that can happen right after waitInterruptibly; for plain sync/auto waits it has to happen before returning success / before in_progress_columns.add, releasing the just-acquired mutex if the post-wakeup check aborts.

  • [dismissed by author -- https://github.com/Honour lock_acquire_timeout for the lightweight update lock in Keeper #114125#discussion_r3763419202] [src/Core/Settings.cpp:5404-5412; docs/reference/settings/session-settings/other.mdx:883-890; src/Common/RWLock.cpp:123-129; src/Storages/MergeTree/PatchParts/PatchPartsLock.cpp:124-133, 200-212, 232-242, 371-405; src/Storages/StorageMergeTree.cpp:1190-1210] The setting contract for lock_acquire_timeout = 0 is still the opposite of the documented one. Both the setting definition and RWLockImpl say 0 means "no locking timeout", but every lightweight-update lock path still does one optimistic attempt and then fails immediately whenever the lock is contended. Because this PR is explicitly about honoring lock_acquire_timeout for lightweight updates, leaving the zero value broken means the setting is still not honored across its full documented domain.
    Suggested fix: keep the optimistic first attempt, but make the contended 0 case wait unboundedly afterwards just like RWLockImpl, and cover it with a contended lock_acquire_timeout = 0 arm for both sync and auto.

Tests
  • ⚠️ Add a focused arm where the holder releases after max_execution_time has expired but before the 3000 ms slice ends, and assert the waiter aborts before it can use the wakeup on both Keeper and plain MergeTree paths.
  • ⚠️ Add a contended lock_acquire_timeout = 0 arm for sync and auto; the current zero-timeout coverage only proves the uncontended fast path.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.30% -0.10%

Changed lines: Changed C/C++ lines covered: 83/118 (70.34%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 10, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4de66b638 with master d33f21163 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ab19f7494; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 711.27 MiB 708.23 MiB -3.05 MiB (-0.43%)

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 sizes

76 object files changed (+18.63 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/PatchPartsLock.cpp.o 252.57 KiB 268.81 KiB +16.24 KiB (+6.43%)

737 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

7845 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.
The matched translation units cost +832.8 s (+8%) in total before that adjustment.

Translation unit Master PR Δ vs median
contrib/wasmedge-cmake/__/wasmedge/lib/executor/instantiate/table.cpp 10.4 s 5.6 s -5.6 s (-50%)
contrib/wasmedge-cmake/__/wasmedge/lib/executor/instantiate/memory.cpp 9.9 s 5.5 s -5.1 s (-48%)

Job report

groeneai and others added 5 commits August 11, 2026 01:47
…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.
groeneai and others added 2 commits August 11, 2026 18:22
…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.

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fd39bc6

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / Sanitizer (STID: 2064-34a1) LeakSanitizer, all-indirect and zero-direct, rooted at Context::createCopy reached from QueryAnalyzer::evaluateScalarSubqueryIfNeeded; the abandoned-plan reference cycle of issue #113954, not reachable from this diff #113397 (external, open)

This PR changes PatchPartsLock, StorageMergeTree, a failpoint and one stateless test, none of
which touch Context/Settings copy lifetime or the analyzer. The same signature fired on two
other unrelated PRs (#110180, #109071) whose diffs are disjoint from this one and from each other.

Two merged candidates were checked against the tree the run actually built (praktika
master_commits) and both are present in it while the leak still fired, so neither is linked as
the owner: #113953 (the DatabaseReplicated digest-finalizer cycle) and #114326 (the PromQL
shared-subquery revert). The strong MaterializedCTEPtr back-edge that #113397 makes weak is
still present in that tree, which is why #113397 is the live owner.

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)))

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. ReplicatedMergeTreeSink.cpp:1333-1337 has the same shape deliberately, breaking on a
    successful tryWait and reaching checkTimeLimit() only on the timed-out path. That is the
    precedent this PR was asked to converge on.
  2. It would turn a successful acquisition into an error. At that point the ephemeral node and the
    in_progress_columns entry already exist, so each caller
    (StorageMergeTree.cpp:1187, :1198) would have to release a lock it was told it never got.
  3. 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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 88ab20e

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Quick functional tests infra: died in Set up job, codeload.github.com 429 downloading actions/checkout@v6, 3 attempts, no checkout or test ran a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, 1/3) infra: same codeload 429 setup death, no test ran a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) infra: same codeload 429 setup death, no test ran a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Unit tests (msan, function_prop_fuzzer) infra: same codeload 429 setup death, no test ran a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Fast test (arm_darwin) infra: the unpacked clickhouse binary has no execute bit, so install.sh and the server start both fail Permission denied and the server never starts a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Build profile diff infra: GH auth failed - required by job at runner.py:321, 0 robot-token rotations, 81 s write-up posted at #113939 (comment)

Notes for readers:

  • None of these six ran a test. Four died inside GitHub's own Set up job step with
    Failed to download archive 'https://codeload.github.com/actions/checkout/tar.gz/...' after 3 attempts (429). One died in the pre-step GH auth path. One never started a server.
  • The Fast test (arm_darwin) failure is a distinct signature from the two known arm_darwin
    families: the server never starts at all, so there is no Server died row and no hang. The
    merged darwin rwlock fix is present on this build and did not prevent it. The same signature
    is in the job logs of two unrelated pull requests today (Fix NOT_FOUND_COLUMN_IN_BLOCK in query_plan_convert_join_to_in with arrayJoin JOIN key #104809, Reimplement the KQL (Kusto) dialect on a lexer, an AST and AST translation #112932), and this branch
    changes only src/ files plus its own test, so it cannot strip an execute bit.
  • This branch's own new test 03100_lwu_57_lock_acquire_timeout passed everywhere it ran.
    There are no test-level failures at this commit: 322,282 result rows across 177 jobs, zero
    FAIL and zero ERROR.

Session id: cron:our-pr-ci-monitor:20260818-000000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Fast test (arm_darwin) binary exec-bit failure in the CI finish ledger above: #115236

Root cause: the self-extracting bundle destroys itself. unlink(self) succeeds, the Darwin-only copy_file(tmp -> self) fails EEXIST, and the error return precedes the chmod restoring the executable bit, so every later invocation of that path is Permission denied. Why the destination exists after a successful unlink is not yet established (macOS-only, not reproducible without a macOS host), so #115236 reports the destination's identity at the abort rather than guessing at a fix.

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
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.

@alexey-milovidov alexey-milovidov 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.

Not bad...

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 28, 2026
Merged via the queue into ClickHouse:master with commit 5a9fd96 Aug 28, 2026
338 of 355 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
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:

  • Culprit PR: Lightweight Updates with patch parts Lightweight Updates with patch parts #82004
  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3, 25.8.

CC introducing PR author: @CurtizJ
CC introducing PR reviewer: @Blargian

CC component owner: @scanhex12 @Michicosun

Analysis metadata

comp-mutations · Severity P2 · Finding phase_d_pr114125

  • Verified against master build dcf60013dc27 (aarch64)
  • Caused by: Lightweight Updates with patch parts #82004 (commit 0dfd2fa215a0, found by bisecting in several steps)
  • Walked 4 release(s) below the supported window: still reproduces down to 25.7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default 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