Repository navigation
Use progress-based timeout in ZooKeeper client to avoid killing healthy sessions under load - #104351
Conversation
Instead of timing out after a fixed deadline from when an operation was submitted, the timeout now resets whenever the server shows signs of life (responds to any request or heartbeat). This prevents spurious `ZOPERATIONTIMEOUT` errors on busy clusters where the server is making steady progress through its request pipeline but individual operations take longer than `operation_timeout_ms`. Key changes: - `IKeeper::getLastResponseTimestamp` virtual method for progress tracking - `ZooKeeper::waitForFutureWithProgress` replaces raw `wait_for` in all sync wrappers, polling in 100ms intervals and extending the deadline on progress - `ZooKeeperImpl` receive thread rewritten to use progress-based timeouts with separate active/idle paths - `KeeperOverDispatcher` tracks progress via `last_response_ts` atomic - Queue-full timeout in `pushRequest` no longer kills the session since the request was never sent - Fix incorrect `OpNum::Sync` in `getACLImpl` timeout message (now `OpNum::GetACL`) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Remove duplicated progress-based timeout logic from the receive thread. The sync wrappers already handle operation-level timeout via `waitForFutureWithProgress`; the receive thread only needs to detect session-level death. Receive thread (`ZooKeeperImpl::receiveThread`): - Single `idle_deadline` based on `session_timeout_ms`, reset on any received data (heartbeat or operation response). - Throws `ZOPERATIONTIMEOUT` only when nothing has been received for `session_timeout_ms`. - Logs a rate-limited warning when the earliest in-flight operation has been waiting longer than `operation_timeout_ms`, but does not throw. Sync wrappers handle the actual timeout decision. - Removed the `max(last_response_ts, earliest_create_ts)` baseline, the dual active/idle paths, and the post-poll progress re-check. Sync wrappers (`ZooKeeper::waitForFutureWithProgress`): - Simplified polling loop. Removed `remaining` time computation and the final zero-timeout re-check. - `tryListRecursive` now uses `waitForFutureWithProgress` (was missed in the original commit). Tests: - Fixed case-sensitivity in `04071_keeper_progress_timeout`: `clickhouse-benchmark` outputs lowercase "executed". Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Use `session_timeout_ms` consistently for the progress timeout in both the receive thread and sync wrappers. Previously the receive thread used `session_timeout_ms` for its idle deadline while sync wrappers used `operation_timeout_ms` for their progress check — the dual-timeout mental model was unnecessary. Receive thread (`ZooKeeperImpl::receiveThread`): - Single deadline: `last_received_at + session_timeout_ms`. - Deadline-driven `in->poll(deadline - now)` — wakes up at exactly the right time, no bounded-poll hack. - Removed the rate-limited stale-operation warning, the separate `idle_deadline` variable, and the `min(operation_timeout_us, remaining_to_idle)` clamping. - A single `last_received_at` update after `receiveEvent()` returns covers all data types (operation responses, heartbeats, AND watch events). Previously watch events did not count as progress. Sync wrappers (`ZooKeeper::waitForFutureWithProgress`): - Single-loop `wait_for(session_timeout_ms)` + progress check. - No deadline tracking, no 1s polling. - Defense-in-depth only: fires only if the receive thread is stuck. Renames for accuracy (any received data — not just responses — counts as progress): - `last_response_ts` → `last_received_at` - `getLastResponseTimestamp` → `getLastReceivedAt` The `init()` chroot check keeps `operation_timeout_ms` because it runs under a shared mutex with an explicit comment warning against long waits there. It is a one-shot probe, not a progress-extended operation. `pushRequest` queue backpressure still uses `operation_timeout_ms` — that's a separate concern (waiting for queue space, not for a response). Test: - Updated the comment in `04071_keeper_progress_timeout` to reflect the unified `session_timeout_ms` (30s) instead of the old `operation_timeout_ms` (10s). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`waitForFutureWithProgress` previously waited indefinitely as long as the connection received any data, since global progress keeps the loop alive. This is the correct behavior for a busy but healthy session, but it cannot detect a single request stuck while heartbeats and other responses keep flowing — e.g. a request lost or dropped by the server. Add a hard cap of `3 * session_timeout_ms` per request. If a single request has not been answered within that window despite global progress, log a warning and give up. The caller then calls `finalize`, which kills the session and triggers a reconnect. This is the right recovery: a request stuck for that long on a connection that is otherwise alive indicates a real session-level problem. 3x is a generous upper bound — short enough to bound caller latency, long enough to never false-positive on a legitimately deep queue. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [722e7d6] Summary: ✅ AI ReviewSummaryThis PR replaces per-operation waiting in sync Findings❌ Blockers
Tests
Final VerdictStatus: Minimum required actions:
|
Bookend `waitForFutureWithProgress`'s hard cap (already at `3 * session_timeout_ms`) with the same cap inside `receiveThread`. The sync wrapper's cap only protects sync callers; async callers using bare `future.get()` (e.g. `StorageReplicatedMergeTree::createNewZooKeeperNodesAttempt`, `removePartsFromZooKeeper`, `markLostReplicas`, `ReplicatedMergeTreeMergePredicate`) had no upper bound and could hang forever if a single request was lost while heartbeats and other responses kept arriving. The receive thread now tracks the earliest in-flight operation and finalizes the session if it has been pending for more than `3 * session_timeout_ms`. `finalize` resolves all pending futures with `ZSESSIONEXPIRED`, so async callers wake up with an error instead of hanging. Found by clickhouse-gh[bot] review on #104351. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| /// heartbeat, or watch event), in microseconds since steady_clock epoch. | ||
| /// Updated by receiveThread after each receiveEvent call. | ||
| /// Read by sync wrappers via getLastReceivedAt() for progress-based timeout. | ||
| std::atomic<Int64> last_received_at{0}; |
There was a problem hiding this comment.
Maybe show that it's timestamp? last_received_at_time?
| /// Queue-full timeout is transient backpressure, not a session failure. | ||
| /// The request was never sent (probably_sent=false), so it's safe to | ||
| /// fail just this one request without killing the session. | ||
| if (!queue_full_timeout) |
There was a problem hiding this comment.
Maybe it make sense, but all the "user" code of this connection (for example ReplicatedMergeTree) will still do full re-initialization on this error. Maybe we can introduce some other error code which can be handled gracefully?
There was a problem hiding this comment.
Yeah that is true, it was something claude found that it made sense but I didn't want to add to this PR with more changes.
I'll just remove it from here and potentially add it in different PR.
| bool ZooKeeper::waitForFutureWithProgress(std::future<T> & future) const | ||
| { | ||
| using clock = std::chrono::steady_clock; | ||
| const auto timeout = std::chrono::milliseconds(args.session_timeout_ms); |
There was a problem hiding this comment.
Why session timeout and not operation timeout? I would prefer to wait for operation timeout => do some logging (impl->getLastReceivedAt() > last_seen_ts), wait more
There was a problem hiding this comment.
It is an extra layer of check in case receive thread gets stuck. Because of that it didn't make sense to me to have different timeouts.
But I was thinking about having the operation timeout for logging, wasn't sure if it would be too noisy during degradation.
|
|
||
| throw Exception(Error::ZOPERATIONTIMEOUT, | ||
| "Request {} for path {} stuck for over {} ms despite global progress — finalizing session", | ||
| stuck_request->getOpNum(), |
There was a problem hiding this comment.
I don't see why stuck_request cannot be nullptr here...
There was a problem hiding this comment.
It cannot be null because it's tied to stuck_deadline. We can reach this branch only if stuck_deadline < idle_deadline and now < idle_deadline.
If there is no stuck_request, stuck_deadline = clock::time_point::max() so the above wouldn't be true.
But we can definitely make it more expressive.
| if (in->poll(max_wait_us)) | ||
| auto deadline = std::min(idle_deadline, stuck_deadline); | ||
|
|
||
| if (now >= deadline) |
There was a problem hiding this comment.
Don't we terminate connection now in case of no requests for session timeout? (idle_deadline)
There was a problem hiding this comment.
There should always be requests because of Heartbeat.
Rename `getLastReceivedAt` and `last_received_at` to timestamp-specific names. Add a `chassert` for the receive-thread stuck-request invariant and let `pushRequest` errors use the existing finalization path.
| /// watch event). Used by progress-based timeout logic in sync wrappers. | ||
| /// Returns 0 (epoch) by default, meaning implementations without progress | ||
| /// tracking will fall back to plain timeout. | ||
| virtual Int64 getLastReceivedTimestamp() const { return 0; } |
There was a problem hiding this comment.
getLastReceivedTimestamp now defaults to 0, and waitForFutureWithProgress uses session_timeout_ms as its base timeout. For IKeeper implementations that don't override this method (e.g. TestKeeper), synchronous ZooKeeper calls now effectively stop honoring operation_timeout_ms and can block up to session_timeout_ms/3 * session_timeout_ms.
That is a behavioral regression versus the previous per-operation timeout contract. Can we either implement progress tracking in TestKeeper, or make waitForFutureWithProgress explicitly fall back to operation_timeout_ms when progress tracking is unavailable (timestamp stays 0)?
There was a problem hiding this comment.
I rechecked current HEAD (722e7d6933b57b584bcd0b6d8590eff06fe77c77): this is still unresolved.
IKeeper::getLastReceivedTimestamp still defaults to 0, TestKeeper still does not override it, and waitForFutureWithProgress now waits on session_timeout_ms rather than operation_timeout_ms. For implementations without progress tracking, this changes the effective sync timeout contract from operation-based to session-based.
Can we either implement getLastReceivedTimestamp in TestKeeper, or explicitly fall back to operation_timeout_ms in waitForFutureWithProgress when progress tracking is unavailable?
|
|
||
|
|
||
| template <typename T> | ||
| bool ZooKeeper::waitForFutureWithProgress(std::future<T> & future) const |
There was a problem hiding this comment.
This changes the timeout contract in all sync wrappers (operation_timeout_ms-based wait -> progress-based session_timeout_ms loop with 3 * session_timeout_ms cap), but I don’t see regression coverage for the new invariants.
Can we add a focused test proving both cases:
- a healthy, high-pipeline session does not expire while responses/heartbeats continue;
- a genuinely stuck request still fails within the hard cap?
Without this, it is hard to validate that we fixed the false-positive path without introducing long-hang regressions.
There was a problem hiding this comment.
I rechecked current HEAD (722e7d6933b57b584bcd0b6d8590eff06fe77c77) and still don’t see regression coverage for the new timeout invariants.
Please add focused tests proving both behaviors:
- continuous global progress (responses/heartbeats/watch events) does not trigger false session finalization under deep pipelining;
- a genuinely stuck request still fails within the
3 * session_timeout_mshard cap.
Without these, it’s hard to validate that we fixed the false-positive path without introducing long-hang regressions.
LLVM Coverage Report
Changed lines: 54.97% (94/171) | lost baseline coverage: 52 line(s) · Uncovered code |
Backport #104351 to 26.4: Use progress-based timeout in ZooKeeper client to avoid killing healthy sessions under load
Since ClickHouse#104351 (progress-based timeout in the ZooKeeper client, merged 2026-05-18), requests stalled by netem fault injection are no longer fast-failed by the operation timeout; they stay alive and complete in the latency tail. On the two netem fault scenarios that still used the default 10s `p99_le` gate this moved p99 from ~8s to 10.3-12.6s (while errors dropped from ~100-300 per run to 0), failing every NightlyKeeperFaults run since 2026-05-20. Set an explicit 15s threshold on these two scenarios, which passes with ~20% headroom over the worst observed nightly and still trips on a real >=2x regression. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=0eb658995715c01dd3bc1d6fdd13d61598b8096e&name_0=NightlyKeeperFaults&name_1=Keeper%20Stress%20%28Faults%29 Co-Authored-By: Claude Fable 5 <[email protected]>
…Keeper client to avoid killing healthy sessions under load
Closes #100466. See the issue for full problem analysis and motivation.
Implementation differences from the issue's proposal:
session_timeout_ms, notoperation_timeout_ms. Onethreshold at both layers (receive thread + sync wrappers). Avoids
false positives when
operation_timeout_ms < session_timeout_ms / 3(heartbeat interval).
3 * session_timeout_msper request in the syncwrapper. Catches requests stuck on an otherwise healthy session
(e.g. lost by the server while heartbeats keep arriving).
pushRequestfails just the one caller on backpressure; the request was never
sent.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improve ZooKeeper client timeout handling under heavy load when many requests are pipelined on a single session. The ZooKeeper client now uses a progress-based timeout: as long as any data is received from the server within
session_timeout_ms, the wait is extended. A hard cap of3 * session_timeout_msper request still bounds caller latency. Closes #100466.Documentation entry for user-facing changes
Version info
26.5.1.756(included in26.5and later)26.4.5.163