Repository navigation
Keep a cluster node's storage work from starving its lease - #8564
piscisaureus wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Superseded by the review of
1c6fd5c5.
This review, of c180a34d
💬 Approved with comments — No BLOCKING or WARNING findings. Three INFO notes cover the scope of the startup directory wipe, a missing test for a wake latched during a busy poll, and doc-comment wording.
Findings: 3 info (3 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.
🔒 Security: 💬 1 info
No exploitable issues. One low-severity note on the scope of the new startup directory wipe.
Recommendation: 💬 Optional Nits
- [INFO] clear_directory recursively deletes everything in a newly claimed directory, but claim_directory refuses only directories holding non-metadata *.sqlite files (
src/workerd/server/server/actor.rs:593)
View full review
The new startup wipe runs clear_directory right after claim_directory. It recursively removes everything in a clustered namespace's directory except .cluster. claim_directory refuses only an unmarked directory that holds .sqlite files other than metadata.sqlite. Any other content of an unmarked directory is therefore deleted on first claim. Exploiting this needs control of the config or the directory, so the risk is low. I found nothing exploitable in the lease gating, the disabled syncs, the epoch directories or the restore spools.
📋 Code Quality: 💬 1 info
No correctness bugs. One coverage gap in the busy-poll path that skips Tokio.
Recommendation: 💬 Optional Nits
- [INFO] No test covers a cross-thread wake that arrives while a busy poll skips Tokio and leaves the wake latched (
src/rust/cxx/kj-rs-tokio/tokio-event-port.c++:129)
View full review
When the loop is runnable and Tokio is not due, TokioEventPort::poll() returns false without calling rustPort->poll(). A cross-thread wake() stays latched until the next poll that runs Tokio, about 20 ms later. The header documents this, but no test checks that the latched wake is still reported. I found no problems in the lease gating, the Hold/HoldEntry locking, the SyncFacetIndex plumbing or the new actor_storage_clear_at FFI.
📝 Documentation: 💬 1 info
The poll_once comments overstate what one scheduler yield guarantees.
Recommendation: 💬 Optional Nits
- [INFO] Describe poll_once as giving ready tasks and drivers an opportunity to run, not as running each once (
src/rust/cxx/kj-rs-tokio/port.rs:291)
View full review
The comments at port.rs:291 and ffi.rs:152 say ready tasks and drivers "run once". pump(1) is a single yield, and Tokio does not guarantee how many times its drivers are polled.
✅ All other checks passed
📖 AGENTS.md: ✅ LGTM
The src/workerd/server/AGENTS.md update is consistent with the change.
⚡ Performance: ✅ LGTM
No performance issues found.
Reviewed commit: c180a34d
c180a34 to
1c6fd5c
Compare
There was a problem hiding this comment.
Superseded by the review of
b1c6ad68.
This review, of 1c6fd5c5
💬 Approved with comments — No BLOCKING or WARNING findings. The new test is sound, and three INFO notes carry over unchanged from the last review.
Findings: 3 info
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
🔒 Security: 💬 1 info
No new concerns. One INFO about the scope of the startup directory wipe still applies.
Recommendation: 💬 Optional Nits
- [INFO] clear_directory recursively deletes everything in a newly claimed directory, but claim_directory refuses only unmarked directories that hold non-metadata *.sqlite files (
src/workerd/server/server/actor.rs:593)
View full review
actor.rs:593:clear_directoryruns right afterclaim_directoryand removes everything except.cluster.claim_directoryrefuses an unmarked directory only when it holds.sqlitefiles other thanmetadata.sqlite, so on the first claim any other content of an unmarked directory is deleted. Exploiting this needs control of the config or the directory, so the risk is low.
📋 Code Quality: 💬 1 info
The new port-test.rs test is sound. One INFO about a missing test for a latched wake still applies.
Recommendation: 💬 Optional Nits
- [INFO] No test covers a cross-thread wake that arrives during a busy poll that skips Tokio and leaves the wake latched (
src/rust/cxx/kj-rs-tokio/tokio-event-port.c++:129)
View full review
tokio-event-port.c++:129: when the loop is runnable and Tokio is not due,poll()returnsfalsewithout polling Rust. A cross-threadwake()stays latched until the next poll that runs Tokio. The header documents this, but no test checks that the latched wake is still reported later.poll_once_runs_a_ready_local_taskinport-test.rsis correct.
📝 Documentation: 💬 1 info
The poll_once doc comments overstate what one yield guarantees.
Recommendation: 💬 Optional Nits
- [INFO] Describe poll_once as giving ready tasks and drivers an opportunity to run, not as running each once (
src/rust/cxx/kj-rs-tokio/port.rs:290)
View full review
port.rs:290andffi.rs:152say ready tasks and drivers "run once".pump(1)is a single yield, and Tokio does not guarantee how many times its drivers are polled.
✅ All other checks passed
📖 AGENTS.md: ✅ LGTM
The src/workerd/server/AGENTS.md update matches the change.
⚡ Performance: ✅ LGTM
No performance issues found.
Reviewed commit: 1c6fd5c5
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #8564 +/- ##
==========================================
- Coverage 66.72% 66.68% -0.05%
==========================================
Files 797 797
Lines 204156 204299 +143
Branches 31724 31711 -13
==========================================
- Hits 136231 136229 -2
- Misses 49329 49473 +144
- Partials 18596 18597 +1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
1c6fd5c to
b1c6ad6
Compare
There was a problem hiding this comment.
Superseded by the review of
58fc388d.
This review, of b1c6ad68
💬 Approved with comments — No BLOCKING or WARNING findings. All three earlier notes are fixed, and one optional comment-formatting suggestion remains.
Findings: 1 suggestion (1 is an inline comment on the diff)
Not opened by the correctness review: 2 changed files it was meant to read
src/workerd/server/factory/worker-factory-actor.c++src/workerd/server/server/actor.rs
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
📋 Code Quality: 💬 1 suggestion
The wake-latch note is fixed; one comment-formatting suggestion.
Recommendation: 💬 Optional Nits
- [SUGGESTION] Edited bullet in tokio-event-port.h runs to about 155 columns and joins two thoughts (
src/rust/cxx/kj-rs-tokio/tokio-event-port.h:20)
View full review
A busy poll that skips Tokio now consumes and reports the wake latch (tokio-event-port.c++:126-146). The new test in tokio-event-port-test.c++ checks that a cross-thread fulfill reaches a busy loop within a few turns.
One remaining suggestion: a bullet edited in tokio-event-port.h has a line about 155 columns wide.
✅ All other checks passed
🔒 Security: ✅ LGTM
claim_directory now refuses an unmarked directory unless it is empty or holds only metadata.sqlite and its -wal, -shm and -journal files. When it refuses, the error names the files it found. As a result, clear_directory runs only on a directory this node owns.
📖 AGENTS.md: ✅ LGTM
The update to src/workerd/server/AGENTS.md matches the change.
⚡ Performance: ✅ LGTM
Busy-poll gating costs one coarse-clock read and one atomic swap per turn, and Tokio runs at most every 20 ms. allows_actors is a constant-time check.
📝 Documentation: ✅ LGTM
No issues found.
Reviewed commit: b1c6ad68
b1c6ad6 to
58fc388
Compare
There was a problem hiding this comment.
Superseded by the review of
5e431f39.
This review, of 58fc388d
✅ Approved — No findings in any area. The previous suggestion is fixed, and the code added since the last review introduces no issues.
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
claim_directory refuses an unmarked directory unless it is empty or holds only regular metadata.sqlite files and their -wal, -shm and -journal files. It also refuses directories and symlinks. As a result, clear_directory cannot delete data this node does not own.
📖 AGENTS.md: ✅ LGTM
The update to src/workerd/server/AGENTS.md matches the change.
📋 Code Quality: ✅ LGTM
- kj-hyper body abort:
BodyAbortis now a shared, cloneable handle.ChannelBody::poll_framechecks for an abort before it checks the data channel. A pump that aborts its stream therefore fails the body instead of letting it be framed as complete.- The new Rust and C++ tests cover this case.
server/cluster.rs:Retiresets up its eviction guard before the detached task runs. Because the drop is guarded bysame_channel, a claim waiting on an eviction never sees a gap.worker-factory-actor.c++:- Syncs are off only for replicated namespaces.
clearObjectworks on its own directory, so it is safe to run on the blocking pool.evictsyncs an object's files before keeping it.
owner.rs:Holdentries remove themselves on the last drop. A claim waits for an eviction before it takes a hold, so the two cannot deadlock.tokio-event-port.h: the bullet that was too long is now split and wrapped.
⚡ Performance: ✅ LGTM
- A busy poll costs one coarse-clock read and one atomic swap per turn, and Tokio runs at most every 20 ms.
- Takeover file work now runs on the blocking pool, and the eviction semaphore still limits how many run at once.
- The
holdsandevictingmaps remove their entries on drop, so they do not grow without bound.
📝 Documentation: ✅ LGTM
No issues found.
Reviewed commit: 58fc388d
58fc388 to
5e431f3
Compare
There was a problem hiding this comment.
Superseded by the review of
a0d00cc9.
This review, of 5e431f39
✅ Approved — No findings in any area. The code changed since the last review (cluster owner holds and eviction, peer bootstrap reuse) is correct.
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
open_epoch_dir and open_spool build their paths only from the node's own database path, a numeric epoch and a restore counter, and they delete only inside the object's own directories. The bootstrap change does not affect which peers or calls are allowed.
📖 AGENTS.md: ✅ LGTM
The update to src/workerd/server/AGENTS.md matches the change.
📋 Code Quality: ✅ LGTM
- Bootstrap: the bootstrap handle is initialized after
rpcSystemand destroyed before it, and both call sites reuse it. - Holds:
Holdnever holds the mutex across an await, and its entries remove themselves once the last lock is dropped. - Eviction: the guard ordering in
evictmeans waiters never see an object that is neither open nor dormant.
⚡ Performance: ✅ LGTM
No issues found.
📝 Documentation: ✅ LGTM
No issues found.
Reviewed commit: 5e431f39
Linking opens every clustered namespace's storage, and each open needed the lease that join() took. On a slow or loaded machine linking outlasts that lease, and the opens failed: SQLite reported SQLITE_CANTOPEN, or the namespace that this instance's lease had lapsed. Until the node serves, it has run no actor and claimed nothing, under a node id new to this process, so no peer can have taken anything over from it. The lease only has to hold once its actors may run. * The lease records that its actors now need it (`requires_live_lease`); renew_to_serve() sets that after renewing. * Storage opens and actor starts check actors_may_run(): always true before the node serves, then true while the lease holds.
The lease loop listed the cluster after each renewal and only then started the wait for the next one, so a slow listing, up to its timeout, pushed every renewal back by as much. Under load, a slow renewal (its requests sent again) followed by a listing that timed out left about 750 ms of the lease's margin at the divided test timings. * The listing now runs alongside the wait. The next renewal starts once both are done, so the two still never overlap. * After a failed renewal the loop skips the listing, so that a slow one cannot hold up the retry.
* A clustered namespace's SQLite opens with syncs off. An object's commits are durable once the bucket holds them, and a node reuses its files only within the process that wrote them, so a sync guards against no crash. Each sync blocked the event loop: on a loaded Windows runner, opening a new Durable Object took three syncs of 100-420 ms in all, and a commit's WAL sync up to 235 ms. Opening 64 at once blocked the loop for 3-8 s of a 10 s burst, in turns of up to 670 ms, and the node's lease lapsed * A cluster namespace's directory is emptied as it links, but for its `.cluster` marker. An earlier process's files go unread: the bucket holds the objects and their alarms, and written with no syncs, any of them may be torn after a crash of the machine. The alarm scheduler's database, which a later process would open, could keep the node from starting; a facet index, which a takeover reads to find the facets' databases it removes, could fail the takeover or leave stale facets. Only a directory the cluster marked is emptied: an unmarked one is claimed only if it is empty or holds nothing but the alarm scheduler's database, which is all workerd leaves in a namespace with no objects, and the node refuses to start over any other * A cluster's facet indexes skip their syncs too. So does the checkpoint that folds a cloned facet's WAL * An object workerd evicts for being idle, kept to resume over its files, has them synced first, on the blocking pool. A sync is where a failed writeback reports its I/O error; if it fails, the object is not kept, and the next request restores it from the bucket. The cluster crate's tests skip the sync: their files are scratch, and on macOS and Windows a sync waits for the device, which made the owner simulation, with its hundreds of evictions, half again as slow * A claim that finds an eviction of the object at its epoch still running, uploading or syncing, waits for it to settle, then resumes the object over its files rather than restoring it from the bucket at the next epoch. The eviction awaits nothing a claim holds, so the wait cannot deadlock; if its sync failed, the claim restores the object from the bucket as before. An eviction counts as running from when workerd retires the object, before the task that runs it starts * A takeover runs on the blocking pool what it can: removing the object's files (through a directory it opens there), creating its copies' directory, creating and removing the restore's downloads, and moving restored databases into place. Creating the copies' directory took up to 334 ms on that runner * A takeover, and an eviction's sync, holds the object: each task it starts on the blocking pool, its restore's replay included, shares a per-object lock, so a takeover cancelled meanwhile holds it until the last such task is done, and the next one, at the next epoch or a retry at the same one, waits rather than have the earlier one's removal, move or replay run beside its own. An epoch cannot guard these: the object's files have the same paths whatever the epoch, and a check before each operation leaves a gap before the operation. The lock's entry goes with its last holder, a blocking task's included * Each restore has a spool of its own, numbered per process. A download's writer, which the bucket client starts and nothing awaits once a takeover is cancelled, so writes only its own restore's files. Earlier spools are removed where they can be: nothing reads them, and on Windows an open file cannot be removed * Copies, whose directories an epoch names, are not held. A takeover keeps later epochs', empties its own, and removes earlier ones' where it can: an earlier epoch's eviction may still be uploading from its copies or its compaction writing them. An eviction's upload, which can take long, so holds up no takeover at the next epoch * What stays on the event loop: numbering a restored facet, which goes through the namespace's storage, cloning a facet, which is synchronous for the actor that asks, and SQLite opening an object's files With these, that burst takes about 0.4 s with no turn of 100 ms or more. A cluster test opens 64 DOs at once on one node and checks that the node keeps its lease. In 500 runs each on a remote executor, it lost the lease in 53 without this change and the two before it, and in 1 with them. That one was a renewal that timed out while the loop stayed busy: the lease loop runs on tokio, which runs only once the KJ loop idles.
5e431f3 to
a0d00cc
Compare
There was a problem hiding this comment.
✅ Approved — No findings in any area; the static helper refactor in worker-factory-impl.h is consistent with its call sites, and the earlier inline notes are addressed.
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 issues found.
📖 AGENTS.md: ✅ LGTM
No issues found.
📋 Code Quality: ✅ LGTM
The newly static helpers in worker-factory-impl.h use only their arguments and each other. cloneFacet stays non-static because it needs actors and vfs. The SyncFacetIndex dependency is declared in BUILD.bazel.
⚡ Performance: ✅ LGTM
The changes move blocking file-system and sync work off the event loop.
📝 Documentation: ✅ LGTM
No issues found.
Reviewed commit: a0d00cc9
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. * 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. * 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.
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 process exits without logging. 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. * 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.
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 process exits without logging. 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. * 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.
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.
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.
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.
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.
This PR keeps a healthy cluster node from losing its lease when startup,
cluster listing, or local disk work keeps its event loop busy. This is
the most common cluster-test CI flake: 84 failing jobs in two weeks, 70
on Windows, mostly at startup. Tests have a 2.25 s lease budget;
production has the same weakness with roughly 9 s.
Background
In cluster mode, several workerd nodes share one bucket, such as S3, R2,
or GCS. Each Durable Object (DO) has exactly one owner node at a time.
Each node keeps renewing a lease file at
nodes/<node>.jsonin thatbucket. A peer treats the node as live while that lease is valid. If it
expires, peers may take over the node's DOs and bump their "epoch". This
makes any late writes from the old owner land where nothing reads them.
The old owner must therefore stop serving its DOs as soon as its lease
lapses. This is "fencing": the safe response that prevents two nodes
from running the same DO. The problem here was healthy nodes fencing
themselves because renewals ran late.
Renewal happens in a tokio "lease loop". On the main thread, tokio runs
only when KJ's event loop has nothing else to do. #8594 lets tokio run
between KJ turns, but a long turn, such as a blocking disk sync, still
delays renewal for the turn's full length. This PR removes those long
turns and contains the cluster-only fixes; #8594 is the event-loop half.
It replaces #8510 without changing the time divisor; #8510 was rejected
because it made tests slower.
Startup
At startup, "linking" opens every clustered namespace's storage. Each
open required the lease obtained by
join(), so on a slow or loadedmachine, linking could outlast the lease. Opens then failed with
SQLITE_CANTOPENor "this instance's lease had lapsed".Storage opens now do not require a live lease until the node starts
serving. Once it starts serving, storage opens and actor starts require
one. This is safe because, before serving, the node has run no actor and
claimed nothing, and it uses a node ID new to this process. No peer can
have taken anything over from it.
Listing
The lease loop used to renew, list the cluster to find peers, and only
then wait for the next renewal. A slow listing, up to its timeout,
pushed every renewal back. Under load, a slow renewal followed by a
timed-out listing left only about 750 ms of margin at test timings.
The listing now runs alongside the wait. The next renewal starts only
after both finish, so renewals still never overlap. After a failed
renewal, the loop skips the listing so it cannot delay the retry.
Disk work
SQLite normally uses
fsyncso committed writes survive a power cut.Every sync blocked the event loop. On a loaded Windows runner, opening
one new DO took three syncs totaling 100-420 ms, while a commit's WAL
sync took up to 235 ms. Opening 64 DOs at once blocked the loop for
3-8 s of a 10 s burst, in turns as long as 670 ms, and the lease lapsed.
For clustered namespaces, SQLite now runs with syncs off. A clustered
write is confirmed only after the bucket holds it, and a node reuses
local files only within the process that wrote them. After a restart it
starts from the bucket, not leftover files, so local sync protects
against no crash.
File-system work during takeover now runs on tokio's blocking thread
pool: removing an object's files, creating directories, handling restore
downloads, and moving restored databases into place. Creating one
directory took up to 334 ms on that runner.
Dropping syncs and moving file work off the loop needs three
follow-ups:
.clustermarker. It claimsan unmarked directory only when it is empty or contains just the
alarm scheduler's database, which is all workerd leaves in a
namespace with no objects. Otherwise, the node refuses to start, so
it never deletes files it does not own.
node syncs them on the blocking pool. If the sync fails, it does not
keep the object, and the next request restores it from the bucket. A
claim that finds such an eviction still running at its epoch waits
for it to settle instead of bumping the epoch.
restore has its own download spool. This stops a cancelled takeover
from racing the takeover that follows it.
Numbering a restored facet, cloning a facet, and SQLite opening an
object's files remain on the event loop.
Results
A new cluster test opens 64 DOs at once on one node and checks that the
node keeps its lease. In 500 runs each on a remote executor, the node
lost its lease 53 times on main, once with this PR, and zero times with
this PR plus #8594. The one remaining failure was a renewal timing out
while the loop stayed busy, which is the part addressed by #8594.
Opening 64 DOs now blocks the loop for about 0.4 s in total, with no
single turn of 100 ms or more, down from 3-8 s with turns up to 670 ms.
Non-cluster storage keeps its syncs and behaviour. Shared deletion
helpers in
worker-factory-actor.c++became static, with no change fornon-cluster namespaces. All cluster targets pass 40 runs on bazelflare.
Lines changed