Skip to content

Use progress-based timeout in ZooKeeper client to avoid killing healthy sessions under load - #104351

Merged
antonio2368 merged 12 commits into
masterfrom
keeper-progress-timeout
May 18, 2026
Merged

antonio2368 merged 12 commits into
masterfrom
keeper-progress-timeout

Conversation

@antonio2368

@antonio2368 antonio2368 commented May 8, 2026 •

Copy link
Copy Markdown
Member

Closes #100466. See the issue for full problem analysis and motivation.

Implementation differences from the issue's proposal:

  • Threshold is session_timeout_ms, not operation_timeout_ms. One
    threshold at both layers (receive thread + sync wrappers). Avoids
    false positives when operation_timeout_ms < session_timeout_ms / 3
    (heartbeat interval).
  • Hard cap of 3 * session_timeout_ms per request in the sync
    wrapper.
    Catches requests stuck on an otherwise healthy session
    (e.g. lost by the server while heartbeats keep arriving).
  • Queue-full timeout no longer kills the session. pushRequest
    fails just the one caller on backpressure; the request was never
    sent.

Changelog category (leave one):

  • Improvement

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 of 3 * session_timeout_ms per request still bounds caller latency. Closes #100466.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.756 (included in 26.5 and later)
  • Backported to: 26.4.5.163

antonio2368 and others added 7 commits April 17, 2026 12:53
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]>
@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [722e7d6]

Summary: ✅


AI Review

Summary

This PR replaces per-operation waiting in sync ZooKeeper wrappers with progress-based waiting and adds a per-request hard cap in receiveThread to avoid expiring otherwise healthy sessions under heavy pipelining. The main direction looks correct, but there are still unresolved contract and evidence gaps: timeout behavior regresses for implementations without progress tracking (notably TestKeeper), and the PR still lacks focused regression tests for the new timeout invariants.

Findings

❌ Blockers

  • src/Common/ZooKeeper/IKeeper.h:770, src/Common/ZooKeeper/ZooKeeper.cpp:117, src/Common/ZooKeeper/TestKeeper.h:34: waitForFutureWithProgress now uses session_timeout_ms and relies on getLastReceivedTimestamp, but IKeeper defaults this method to 0 and TestKeeper does not override it. That changes sync timeout behavior from operation_timeout_ms to session_timeout_ms for TestKeeper and any other non-overriding implementation, violating the previous per-operation timeout contract.
    Suggested fix: either implement getLastReceivedTimestamp in TestKeeper, or make waitForFutureWithProgress explicitly fall back to operation_timeout_ms when progress tracking is unavailable.
Tests
  • ⚠️ No focused regression tests were added for the new timeout invariants. Please add targeted coverage that proves:
    1. continuous global progress (responses/heartbeats/watch events) does not cause false session finalization under deep pipelining;
    2. a genuinely stuck request still fails within the 3 * session_timeout_ms cap.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Restore correct timeout behavior for implementations without progress tracking (or implement tracking in those implementations).
  2. Add focused regression tests for both progress-path and stuck-request-path timeout behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 8, 2026
Comment thread src/Common/ZooKeeper/ZooKeeperImpl.cpp Resolved
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]>
@antonio2368
antonio2368 marked this pull request as ready for review May 11, 2026 06:58
@alesapin alesapin self-assigned this May 11, 2026

@alesapin alesapin 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.

Good idea

Comment thread src/Common/ZooKeeper/ZooKeeperImpl.h Outdated
/// 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};

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.

Maybe show that it's timestamp? last_received_at_time?

Comment thread src/Common/ZooKeeper/ZooKeeperImpl.cpp Outdated
/// 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)

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.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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.

I don't see why stuck_request cannot be nullptr here...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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)

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.

Don't we terminate connection now in case of no requests for session timeout? (idle_deadline)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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; }

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.

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

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.

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

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.

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:

  1. a healthy, high-pipeline session does not expire while responses/heartbeats continue;
  2. 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.

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.

I rechecked current HEAD (722e7d6933b57b584bcd0b6d8590eff06fe77c77) and still don’t see regression coverage for the new timeout invariants.

Please add focused tests proving both behaviors:

  1. continuous global progress (responses/heartbeats/watch events) does not trigger false session finalization under deep pipelining;
  2. a genuinely stuck request still fails within the 3 * session_timeout_ms hard cap.

Without these, it’s hard to validate that we fixed the false-positive path without introducing long-hang regressions.

@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.20% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 54.97% (94/171) | lost baseline coverage: 52 line(s) · Uncovered code

Full report · Diff report

@antonio2368
antonio2368 enabled auto-merge May 18, 2026 15:08
@antonio2368
antonio2368 added this pull request to the merge queue May 18, 2026
Merged via the queue into master with commit 70ff838 May 18, 2026
327 of 328 checks passed
@antonio2368
antonio2368 deleted the keeper-progress-timeout branch May 18, 2026 15:28
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 18, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 17, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 17, 2026
alexey-milovidov added a commit that referenced this pull request Jul 24, 2026
Backport #104351 to 26.4: Use progress-based timeout in ZooKeeper client to avoid killing healthy sessions under load
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Aug 16, 2026
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]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…Keeper client to avoid killing healthy sessions under load
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Keeper client kills healthy sessions under load due to wall-clock operation timeout

5 participants