Skip to content

Keep a cluster node's lease on a thread of its own - #8631

Merged
piscisaureus merged 1 commit into
mainfrom
piscisaureus/cluster-lease-thread
Nov 20, 2026
Merged

piscisaureus merged 1 commit into
mainfrom
piscisaureus/cluster-lease-thread

Conversation

@piscisaureus

@piscisaureus piscisaureus commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

This PR moves cluster lease renewal to its own thread so work on the
server event loop cannot delay renewal and fence an otherwise healthy
node. It is a cluster-only alternative to #8564 + #8594 for the lease
problem: instead of shortening event-loop turns and changing how tokio
is scheduled, it takes renewal off that loop entirely.

Background

In cluster mode, several nodes share a bucket such as S3, R2, or GCS.
Each Durable Object has one owner node. Every node regularly extends
the expiry time in its bucket record; that expiry time is its lease.

Peers consider a node live while its lease holds. If the node cannot
renew, it must stop, or "fence", before expiry so that two nodes cannot
run the same Durable Object.

On main, renewal runs on the server's KJ event loop, with a tokio
runtime on the same thread. While one KJ turn is running, such as
synchronous JavaScript, a slow SQLite query, or an fsync on a slow
disk, nothing else on that thread runs. Tokio only runs when the KJ
queue is empty. A busy or blocked event loop can therefore delay
renewal and fence a healthy node, dropping every Durable Object it
owned. This was the main remaining cause of cluster-test CI flakes.

What changes

  • A new cluster-lease thread has its own tokio runtime and bucket
    client in cluster/keeper.rs. It writes the node's record, runs
    renewal rounds, and publishes the lease expiry through an atomic.
    The event loop reads that atomic in Cluster::lease_holds.
  • The event loop sends the thread commands for work it previously did
    itself: renewal at join, the drain announcement, and deregistration.
    Each command runs as a task beside the renewal rounds.
  • Renewal rounds begin at join instead of when the node starts serving.
    This keeps the lease alive throughout startup linking, which opens
    every namespace's storage under the lease and can take longer than a
    lease on a slow disk. The renewal before serving is removed. This
    covers the startup failure addressed differently by Keep a cluster node's storage work from starving its lease #8564's first
    commit, which opens storage without a lease until the node serves.
  • If the lease cannot be kept, the lease thread ends the process with
    _exit, because the event loop may be in a turn that never ends.
    Before logging the reason, it arms the exit on another thread, which
    ends the process after at most 200 ms or the remaining lease time
    minus slack, whichever is less. A blocked log write therefore cannot
    keep the node serving past its lease. Under structured
    logging, the reason also goes to stderr as JSON, where supervisors
    read startup failures. The exit status remains 1, as it was when
    main lost a lease.
  • The lease thread logs through the event-loop thread's logger, so its
    output is JSON when structured logging is enabled.
  • Dropping the cluster stops the lease thread and cancels its requests.
    It waits at most one second for the thread to finish, then leaves it
    behind.
  • Peer listing remains on the event loop in its own
    Cluster::list_loop. A late listing now only delays routing to a new
    peer; it no longer sits between two renewals.
  • If the bucket fails after join while the node is linking, the node
    now logs the reason and fences instead of returning a startup error.
    A bucket failure at join still returns a startup error.

The trade-off

The lease now proves that the process is running and can reach the
bucket, not that its event loop is taking turns. If an event loop is
wedged permanently, the node keeps its lease and its Durable Objects
until something else stops it. On main, peers took over those objects
after one lease.

A loop watchdog with a bound well above the lease would restore that
protection. The watchdog is follow-up work and is not part of this PR.

Tests

  • keeper-test.rs verifies that the lease thread renews independently,
    fences with time remaining when the bucket refuses writes, and waits
    for the thread to end when dropped. Its leases last a few hundred
    milliseconds, so the tests add under one second.
  • cluster-test.rs verifies that the lease remains valid however long
    startup takes after join. It fails if renewal rounds do not begin at
    join.
  • lease-test.rs and the server cluster tests cover the remaining-time
    calculation and bounded wait for logging.
  • cluster-test.mjs verifies that a node continues serving after one
    request runs JavaScript for longer than a lease, which fences the
    node on main. It also checks that lease-thread warnings are JSON
    under structured logging, and that total renewal failure produces a
    JSON "leaving the cluster" line on stderr and exit code 1.
  • The GCS token-refresh check accounts for the third bucket client on
    each node.
  • Crate tests that drive a Cluster over their own bucket continue to
    keep the lease on their own thread and renew it manually.

Results

In #8564's stress test, 64 Durable Objects are opened at once on one
node and the test checks that the node retains its lease. Each version
ran 500 times on bazelflare.

Version Lease losses
main 53
#8564 1
#8594 1
#8564 + #8594 0
this PR 0

None of this PR's 500 logs contained a failed renewal.

Cluster targets pass 40 runs on bazelflare, with 200 runs of
cluster-test. //src/workerd/server/... also passes.

The cluster crate's cluster_test unit tests take about 40 seconds in
debug and ASan builds; the new lease-thread tests add under one second.

Kind Lines Where
Implementation 733 cluster keeper/lease/registry, server, factory
Tests 454 keeper, cluster, lease unit tests; cluster tests
Documentation 5 server AGENTS.md

@codecov-commenter

codecov-commenter commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0.91533% with 433 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.04%. Comparing base (6f40a3b) to head (088fe06).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
src/workerd/server/cluster/keeper.rs 0.00% 273 Missing ⚠️
src/workerd/server/cluster/cluster.rs 0.00% 48 Missing ⚠️
src/workerd/server/server/log.rs 7.89% 35 Missing ⚠️
src/workerd/server/server/cluster.rs 0.00% 25 Missing ⚠️
src/workerd/server/tests/cluster/cluster-worker.js 0.00% 17 Missing ⚠️
src/workerd/server/factory/bootstrap.c++ 0.00% 14 Missing ⚠️
src/workerd/server/cluster/logic/lease.rs 0.00% 11 Missing ⚠️
src/workerd/server/cluster/registry.rs 0.00% 4 Missing ⚠️
src/workerd/server/server/bridge.rs 0.00% 3 Missing ⚠️
src/workerd/server/server/run.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8631      +/-   ##
==========================================
- Coverage   67.13%   67.04%   -0.09%     
==========================================
  Files         822      820       -2     
  Lines      212065   211936     -129     
  Branches    32461    32379      -82     
==========================================
- Hits       142362   142103     -259     
- Misses      50673    50852     +179     
+ Partials    19030    18981      -49     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@piscisaureus
piscisaureus force-pushed the piscisaureus/cluster-lease-thread branch 4 times, most recently from 18fda85 to 98b6d48 Compare November 18, 2026 20:24
@piscisaureus
piscisaureus marked this pull request as ready for review November 18, 2026 20:56
@piscisaureus
piscisaureus requested review from a team as code owners November 18, 2026 20:56
@piscisaureus
piscisaureus requested a review from ry November 18, 2026 20:56

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of ce76f072.

This review, of 98b6d481

💬 Approved with comments — The lease-thread design is sound and well tested. Two INFO notes on the fence path: a fence with little lease left exits without logging why, and the process is not fenced if the lease thread dies outside a spawned task.

Findings: 2 info (2 are inline comments on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 2 info

The commands, the shared expiry atomic and the fence path fit together correctly. Two gaps remain in the fence path.

Recommendation: 💬 Optional Nits

  • [INFO] A fenced node exits without logging any reason when its lease has 20 ms or less left. (src/workerd/server/server/cluster.rs:443)
  • [INFO] Nothing fences the process if the lease thread ends outside a spawned task. (src/workerd/server/cluster/keeper.rs:333)
View full review

The keeper thread, its commands, the Held atomic and the armed-exit fence fit together correctly. Two smaller gaps remain in the fence path:

  • Silent exit. fence_log_wait returns None when the lease has FENCE_SLACK (20 ms) or less left. The fence closure then calls cli_exit(1) without logging anything. A lease that lapsed before it could be renewed is the case most likely to reach this branch, and it is the one an operator most needs explained. On main, leaving the cluster: … was always logged.
  • Lease thread death. If the lease thread dies outside a spawned task (in serve, the runtime, or within), no fence runs. Thread::send drops its error, so lease_holds() only blocks opening new storage, while Durable Objects that are already running keep serving after peers may take them over.

✅ All other checks passed

🔒 Security: ✅ LGTM

The change adds no injection, authentication bypass, secret exposure or data-exposure problem.


📖 AGENTS.md: ✅ LGTM

No issues found.


⚡ Performance: ✅ LGTM

The change adds one thread, one current-thread tokio runtime and one bucket client per node. All blocking waits are bounded, and the renewal and listing cadences are unchanged.


📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: 98b6d481

Comment thread src/workerd/server/server/cluster.rs Resolved
Comment thread src/workerd/server/cluster/keeper.rs Resolved
@piscisaureus
piscisaureus force-pushed the piscisaureus/cluster-lease-thread branch from 98b6d48 to ce76f07 Compare November 18, 2026 21:15

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 1728f154.

This review, of ce76f072

✅ Approved — Both earlier fence-path notes are fixed at this commit and no new issues were found.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

The change adds no injection, authentication, secret-exposure or data-exposure problem.


📖 AGENTS.md: ✅ LGTM

No issues found.


📋 Code Quality: ✅ LGTM

The earlier notes on the silent exit and on the lease thread ending outside a task are both fixed:

  • Silent exit: server/cluster.rs now calls fatal_nonblocking before cli_exit(1).
  • Lease thread ending: the Watch drop guard in keeper.rs fences the process. keeper-test.rs tests a closed command channel, a panic outside a task, an end before the rounds start, an end after leaving, and fencing only once.

⚡ Performance: ✅ LGTM

  • The change adds one thread, one current-thread tokio runtime and one bucket client per node.
  • lease_holds is now one atomic load.
  • The teardown wait and the fence wait are both bounded.

📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: ce76f072

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

[AI] Approving. This matches celld, whose ownership actor keeps the node lease on its own current_thread runtime, and the exit is stricter than celld's: celld hands the fence to its main runtime, which flushes logs and calls exit, while this calls _exit from the lease thread with the log wait bounded. Needs a rebase.

Comment thread src/workerd/server/cluster/keeper.rs Resolved
@piscisaureus
piscisaureus force-pushed the piscisaureus/cluster-lease-thread branch from ce76f07 to 1728f15 Compare November 19, 2026 23:35
@piscisaureus
piscisaureus requested a review from jasnell November 19, 2026 23:35

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 088fe065.

This review, of 1728f154

✅ Approved — No issues in the code changed since the last review, and the earlier fence-path fixes are still in place.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security issues in the changed code.


📖 AGENTS.md: ✅ LGTM

No issues found.


📋 Code Quality: ✅ LGTM

run.rs drops the renewal before serving and the event-loop exit task. The lease thread now handles both. The new cluster-test.mjs tests have time limits and clean up nodes that do not exit.


⚡ Performance: ✅ LGTM

start_cluster no longer waits for a renewal before serving, so startup does less work. The new tests poll with time limits.


📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: 1728f154

A cluster node renewed its lease from a task on the server's event
loop, so a renewal waited for whatever turn the loop was in. One turn
longer than the lease's slack (a Worker that computes synchronously, a
slow SQLite query, an fsync or a directory removal on a slow disk)
fenced the node, which then dropped every object it owned.

The lease is now kept by a `cluster-lease` thread with its own tokio
runtime and its own bucket client (`cluster/keeper.rs`):

* The thread writes the node's record and runs the renewal rounds. It
  publishes the lease's expiry through an atomic, which the loop reads
  where it used to read the lease (`Cluster::lease_holds`).
* The loop sends it commands for what it used to do itself: the
  renewal at join, the drain announcement and the deregistration. Each
  runs as a task beside the rounds.
* The rounds start at join, not once the node serves, so the lease
  holds however long linking takes: it opens every namespace's storage,
  which opens only under the lease, and on a slow disk took longer than
  one. The renewal before serving that made up for that is gone, and
  storage need not open without a lease until the node serves, as
  #8564 has it do.
* A lease that cannot be kept ends the process from the lease thread,
  with `_exit`, since the loop may be in a turn that does not end. The
  exit is armed on a thread of its own before the reason is logged, so
  that a log write that blocks cannot delay it, for 200 ms or until
  shortly before the lease stops holding, whichever comes first. With
  no time left, the reason goes to stderr in one write that does not
  block (none on Windows) before the process exits. Under structured
  logging the reason also goes to stderr, where a supervisor looks for
  why a process ended, as it does for a failed start.
* A lease thread that ends without being told to stop, by a panic
  outside its tasks or otherwise, fences the node as rounds that end
  do, unless its rounds have not started or the node left the cluster.
  The fence runs once, whichever comes first.
* The thread logs through the loop thread's logger, which it installs
  as KJ does for a thread of its own (`getThreadInitializer`, through
  the server's bridge): under structured logging its lines are JSON.
* Dropping the cluster stops the thread, cancelling its requests, and
  waits a second at most for it to end, leaving it behind after that.
* The peer listing stays on the loop, in a loop of its own
  (`Cluster::list_loop`): a late listing only delays routing to a new
  peer. It no longer sits between two renewals.

This changes what the lease attests: that the process runs and reaches
the bucket, not that its event loop takes turns. A node whose loop is
stuck for good keeps its lease and its objects until something else
stops it; before, peers took its objects over after a lease.

A bucket that fails after join, while the node links, now fences it
like a serving node (it logs why and exits) instead of failing the
renewal before serving with an error. A bucket that fails at join still
fails startup with an error.

Tests of the crate that drive a `Cluster` over their own bucket keep
the lease on their own thread and renew by hand, as before. The lease
thread's own tests use leases of a few hundred ms.
@piscisaureus
piscisaureus force-pushed the piscisaureus/cluster-lease-thread branch from 1728f15 to 088fe06 Compare November 20, 2026 06:51

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved — No findings in the code changed since the last review. The lease-thread design and the earlier fence-path fixes are still in place.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

The change is internal lease handling, and its log writes go only to stderr and stdout. No security issues found.


📖 AGENTS.md: ✅ LGTM

No issues found.


📋 Code Quality: ✅ LGTM

No issues found in the changed code.


⚡ Performance: ✅ LGTM

  • Lease thread: it runs a single-thread runtime, and its commands are low-volume control messages.
  • Shutdown: the drop wait for the lease thread is capped at 1 s and runs only at shutdown.
  • Reads on the event loop: lease_holds and membership now read atomics instead of a RefCell.
  • Extra bucket client: the lease thread opens a third bucket client per node, a one-time cost.
  • Listing: list_loop keeps the same request cadence as before.

📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: 088fe065

@piscisaureus
piscisaureus merged commit 55fd817 into main Nov 20, 2026
23 checks passed
@piscisaureus
piscisaureus deleted the piscisaureus/cluster-lease-thread branch November 20, 2026 16:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants