Skip to content

Commit 5e431f3

Browse files
committed
Keep syncs and file system work off a cluster node's event loop
* 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.
1 parent f09a9f0 commit 5e431f3

17 files changed

Lines changed: 754 additions & 94 deletions

‎src/workerd/server/BUILD.bazel‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,7 @@ wd_cc_library(
377377
],
378378
visibility = ["//visibility:public"],
379379
deps = [
380+
"//src/workerd/util:strong-bool",
380381
"@capnp-cpp//src/kj",
381382
],
382383
)

‎src/workerd/server/cluster/capture-test.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -408,8 +408,13 @@ impl Sim {
408408
return Err(format!("{} is live but not captured", d.lane));
409409
}
410410
let spool = self.dir.join(format!("restore-{}", self.session));
411-
let (end, lanes) = block(crate::log::restore(&self.log, self.session, &spool))
412-
.map_err(|e| format!("restore: {e}"))?;
411+
let (end, lanes) = block(crate::log::restore(
412+
&self.log,
413+
self.session,
414+
&spool,
415+
&(std::sync::Arc::new(()) as crate::owner::Share),
416+
))
417+
.map_err(|e| format!("restore: {e}"))?;
413418
let got: BTreeMap<_, _> = lanes
414419
.iter()
415420
.map(|(lane, path)| (lane.clone(), std::fs::read(path).unwrap()))

‎src/workerd/server/cluster/cluster.rs‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,15 @@ impl Cluster {
159159
// Named open here, but not open here. Evicted here with the bucket
160160
// holding the epoch: resume it (`take_over`); a stale owner that
161161
// writes on cannot acknowledge, since every acknowledgement rereads
162-
// own.json. Otherwise, dropped after a failure or evicted before its
163-
// upload completed: recover it at the next epoch.
162+
// own.json. Otherwise, dropped after a failure, evicted before its
163+
// upload completed or its files failed to sync: recover it at the
164+
// next epoch. An eviction of the epoch still running decides which.
165+
if let Claim::Owned(owned) = &claim
166+
&& owned.recover.is_none()
167+
&& !self.owners.holds(ns, actor)
168+
{
169+
self.owners.evicted(ns, actor, owned.epoch).await;
170+
}
164171
if let Claim::Owned(owned) = &claim
165172
&& owned.recover.is_none()
166173
&& !self.owners.holds(ns, actor)
@@ -317,6 +324,12 @@ impl Cluster {
317324
self.owners.tier().await;
318325
}
319326

327+
/// Counts an eviction of an object as running, for the claims here to
328+
/// wait for, until the guard is dropped (`Owners::evicting`).
329+
pub fn evicting(&self, ns: &str, actor: &str, epoch: u64) -> crate::Evicting {
330+
self.owners.evicting(ns, actor, epoch)
331+
}
332+
320333
/// Keep an object workerd evicted, uploading what the bucket lacks.
321334
pub async fn evict_actor(&self, ns: &str, actor: &str, epoch: u64) {
322335
self.owners.evict(ns, actor, epoch).await;

‎src/workerd/server/cluster/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,10 @@ pub use cluster::open_bucket;
7474
pub use log::DB;
7575
pub use log::facet_path;
7676
pub use log::facet_prefix;
77+
pub use owner::Evicting;
7778
pub use owner::Layout;
7879
pub use owner::Owners;
80+
pub use owner::Removal;
7981
pub use ownership::Claim;
8082
pub use ownership::Ownership;
8183
pub use registry::NodeRecord;

‎src/workerd/server/cluster/log.rs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ use crate::Bucket;
4545
use crate::Error;
4646
use crate::Result;
4747
use crate::Sequence;
48+
use crate::owner::Share;
49+
use crate::owner::blocking_sharing;
4850

4951
/// A database's lane, after its facet's prefix.
5052
pub const DB: &str = "db";
@@ -765,18 +767,21 @@ impl Log {
765767
/// Restores `session` of the log into `spool`, created empty: the plan's
766768
/// files downloaded, then replayed on the blocking pool. The frame the log
767769
/// continues from, 0 for an empty log, and each live lane's name and
768-
/// database, under `spool`.
770+
/// database, under `spool`. Each task it starts on the blocking pool keeps
771+
/// a clone of `share` until it ends, but for the downloads' writers.
769772
pub async fn restore(
770773
log: &Log,
771774
session: u32,
772775
spool: &Path,
776+
share: &Share,
773777
) -> Result<(Sequence, Vec<(String, PathBuf)>)> {
774778
let plan = plan(&log.files(session).await?);
775779
if plan.is_empty() {
776780
return Ok((0, Vec::new()));
777781
}
778782
let downloads = spool.join("files");
779-
std::fs::create_dir_all(&downloads)?;
783+
let created = downloads.clone();
784+
blocking_sharing(share, move || Ok(std::fs::create_dir_all(&created)?)).await?;
780785
let files: Vec<_> = (0..plan.len())
781786
.map(|i| (plan[i], downloads.join(i.to_string())))
782787
.collect();
@@ -786,15 +791,15 @@ pub async fn restore(
786791
.try_collect::<()>()
787792
.await?;
788793
let lanes = spool.join("lanes");
789-
let restored = crate::owner::blocking(move || {
794+
let restored = blocking_sharing(share, move || {
790795
let mut replay = Replay::new(&lanes)?;
791796
for (f, path) in &files {
792797
replay.apply(f, path)?;
793798
}
794799
replay.finish()
795800
})
796801
.await;
797-
let _ = std::fs::remove_dir_all(&downloads);
802+
let _ = blocking_sharing(share, move || Ok(std::fs::remove_dir_all(&downloads)?)).await;
798803
restored
799804
}
800805

‎src/workerd/server/cluster/log_tests.rs‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -334,10 +334,15 @@ fn upload_snapshot(store: &Bucket, to: Sequence) {
334334
.unwrap();
335335
}
336336

337+
/// A share of no hold.
338+
fn share() -> crate::owner::Share {
339+
std::sync::Arc::new(())
340+
}
341+
337342
/// Restores the log's lanes into a spool, moving the root's to `out`.
338343
fn restore_db(store: &Bucket, out: &Path) -> crate::Result<Sequence> {
339344
let spool = crate::log::with_suffix(out, ".spool");
340-
let (end, lanes) = runtime().block_on(restore(&log(store), 0, &spool))?;
345+
let (end, lanes) = runtime().block_on(restore(&log(store), 0, &spool, &share()))?;
341346
for (lane, path) in lanes {
342347
if lane == DB {
343348
std::fs::rename(path, out)?;
@@ -751,11 +756,14 @@ impl Layout for Root {
751756
Ok(self.0.clone())
752757
}
753758

754-
fn clear(&self) -> crate::Result<()> {
755-
for suffix in ["", "-wal", "-shm"] {
756-
let _ = std::fs::remove_file(crate::log::with_suffix(&self.0, suffix));
757-
}
758-
Ok(())
759+
fn clear(&self) -> crate::Result<crate::owner::Removal> {
760+
let path = self.0.clone();
761+
Ok(Box::new(move || {
762+
for suffix in ["", "-wal", "-shm"] {
763+
let _ = std::fs::remove_file(crate::log::with_suffix(&path, suffix));
764+
}
765+
Ok(())
766+
}))
759767
}
760768
}
761769

@@ -779,7 +787,7 @@ fn remove(path: &Path) {
779787
/// Every lane the log restores, with its rows.
780788
fn restored_lanes(store: &Bucket, name: &str) -> BTreeMap<String, (i64, i64, i64)> {
781789
let (_, lanes) = runtime()
782-
.block_on(restore(&log(store), 0, &scratch(name)))
790+
.block_on(restore(&log(store), 0, &scratch(name), &share()))
783791
.unwrap();
784792
let open = |path: PathBuf| rows(&Connection::open(path.to_str().unwrap()));
785793
lanes.into_iter().map(|(l, path)| (l, open(path))).collect()

‎src/workerd/server/cluster/owner-test.rs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -158,11 +158,14 @@ impl Layout for Files {
158158
Ok(path.clone())
159159
}
160160

161-
fn clear(&self) -> crate::Result<()> {
161+
fn clear(&self) -> crate::Result<crate::owner::Removal> {
162162
self.placed.borrow_mut().clear();
163-
std::fs::remove_dir_all(&self.dir)?;
164-
std::fs::create_dir_all(&self.dir)?;
165-
Ok(())
163+
let dir = self.dir.clone();
164+
Ok(Box::new(move || {
165+
std::fs::remove_dir_all(&dir)?;
166+
std::fs::create_dir_all(&dir)?;
167+
Ok(())
168+
}))
166169
}
167170
}
168171

0 commit comments

Comments
 (0)