From ab12a787c63f7dd684a58f4bca1ac1edadd662c1 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:37:42 +0100 Subject: [PATCH] perf(worktree): write checkouts in parallel, durably A checkout wrote its files one at a time, creating each one's directory on the way, and left them to the page cache: a crash could leave a working copy pointing at a revision whose files never reached the disk. Checkouts now create the directories first, then write the files in parallel, a contiguous run per core, which keeps threads off each other's directory locks and is 40% faster than handing files out one at a time. They are durable, with one batch sync of the files and the directories whose entries changed, before the checkout returns. A large checkout syncs its first half in the background while it writes the second, so the final barrier has less left to wait for. The `workspace` benchmark checks a 20,000-file tree out into an empty directory. --- apps/origin-src/Cargo.toml | 4 + apps/origin-src/benches/workspace.rs | 54 ++++++++++ apps/origin-src/src/workspace/mod.rs | 2 +- apps/origin-src/src/worktree.rs | 149 +++++++++++++++++++++++---- 4 files changed, 186 insertions(+), 23 deletions(-) create mode 100644 apps/origin-src/benches/workspace.rs diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index fbab1ea8..30ed0d94 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -53,5 +53,9 @@ harness = false name = "packs" harness = false +[[bench]] +name = "workspace" +harness = false + [lints] workspace = true diff --git a/apps/origin-src/benches/workspace.rs b/apps/origin-src/benches/workspace.rs new file mode 100644 index 00000000..54e8c03c --- /dev/null +++ b/apps/origin-src/benches/workspace.rs @@ -0,0 +1,54 @@ +//! Checking a 20k-file tree out into an empty directory, durably, by +//! writing every file from the store. + +use std::sync::LazyLock; + +use divan::Bencher; +use divan::counter::ItemsCount; +use origin_platform::Native; +use origin_shared::{Record, Tree, TreeId}; +use origin_src::fixture::FixtureTree; +use origin_src::store::Store; +use origin_src::tree::FileChange; +use origin_src::worktree::{StatCache, Worktree}; + +fn main() { + divan::main(); +} + +const TREE: FixtureTree = FixtureTree::LARGE; + +/// The main working copy: the fixture, snapshotted. +struct Main { + dir: tempfile::TempDir, + /// Every file of the snapshot, as checking it out adds them. + changes: Vec, +} + +static MAIN: LazyLock
= LazyLock::new(|| { + let dir = tempfile::tempdir().unwrap(); + TREE.write(dir.path()).unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let empty = Tree::default().encode(); + store.write_all(std::slice::from_ref(&empty)).unwrap(); + let (root, _) = Worktree::new(dir.path(), &store) + .snapshot(&StatCache::default()) + .unwrap(); + let changes = store.diff(TreeId::from(empty.id()), root).unwrap(); + Main { dir, changes } +}); + +/// Every file read from the store, decompressed, verified and written. +#[divan::bench(sample_count = 10, sample_size = 1)] +fn from_store(bencher: Bencher<'_, '_>) { + let store = Store::new(MAIN.dir.path().join(".origin"), Native::default()); + bencher + .counter(ItemsCount::new(MAIN.changes.len())) + .with_inputs(|| tempfile::tempdir().unwrap()) + .bench_local_refs(|workspace| { + Worktree::new(workspace.path(), &store) + .checkout(&MAIN.changes) + .unwrap(); + }); +} diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 20f0b8b2..11070df6 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -346,7 +346,7 @@ impl Workspace { Ok(()) } - /// Makes the files match `to`, given that they match `from`. + /// Makes the files match `to`, given that they match `from`, durably. fn checkout(&self, from: TreeId, to: TreeId) -> Result<(), WorkspaceError> { let changes = self.store.diff(from, to)?; Ok(Worktree::new(&self.root, &self.store).checkout(&changes)?) diff --git a/apps/origin-src/src/worktree.rs b/apps/origin-src/src/worktree.rs index 96889fe6..d27cd7cf 100644 --- a/apps/origin-src/src/worktree.rs +++ b/apps/origin-src/src/worktree.rs @@ -5,14 +5,18 @@ //! copy. To keep that fast, a stat cache remembers each file's metadata and //! blob id, so only files whose metadata changed are read and hashed, and //! every phase runs in parallel. +//! +//! Checkouts write files from the store, in parallel, and the files they +//! write are durable once they return. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::ffi::OsStr; use std::fs::{self, File}; use std::io; use std::ops::Range; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink}; +use std::panic; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -54,6 +58,12 @@ impl Stat { } } +/// A file a checkout writes. +struct Write { + path: PathBuf, + entry: TreeEntry, +} + /// The stat cache: what each file looked like when it was last hashed, and /// the snapshot those files made. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -233,6 +243,10 @@ impl<'a, P: Platform> Worktree<'a, P> { /// Below this many items, threads cost more than they save. const PARALLEL_THRESHOLD: usize = 64; + /// From this many files on, a checkout syncs the first half of them + /// while it writes the second. + const EARLY_SYNC: usize = 1024; + /// The working copy rooted at `root`. #[must_use] pub fn new(root: &'a Path, store: &'a Store

) -> Self { @@ -460,13 +474,18 @@ impl<'a, P: Platform> Worktree<'a, P> { /// Makes the files match a snapshot, given how they differ from it: /// removes the files `changes` remove, then writes the ones they add or - /// modify. Directories left empty are removed. + /// modify, in parallel. Directories left empty are removed. Once it + /// returns, the files and directories it changed are durable, at the + /// cost of one batch sync. /// /// # Errors /// /// Fails if a file's content cannot be read from the store, or a file - /// cannot be removed or written. + /// cannot be removed, written or synced. pub fn checkout(&self, changes: &[FileChange]) -> Result<(), SnapshotError> { + if changes.is_empty() { + return Ok(()); + } // Removing first frees the paths of files that become directories, // and of directories that become files. for change in changes.iter().filter(|change| change.new.is_none()) { @@ -479,11 +498,99 @@ impl<'a, P: Platform> Worktree<'a, P> { } } } + let writes: Vec<_> = changes + .iter() + .filter_map(|change| { + Some(Write { + path: self.absolute(&change.path), + entry: change.new?, + }) + }) + .collect(); + // Creating the directories first lets the files be written in any + // order. + let mut dirs: Vec<_> = writes + .iter() + .filter_map(|write| write.path.parent()) + .collect(); + dirs.sort_unstable(); + dirs.dedup(); + for dir in dirs { + fs::create_dir_all(dir).map_err(|source| SnapshotError::Io { + path: dir.to_owned(), + source, + })?; + } + // Many files take long to sync: the first half is written back + // while the second is written, so the final sync, the barrier, has + // less left to wait for. + let half = if writes.len() >= Self::EARLY_SYNC { + writes.len() / 2 + } else { + 0 + }; + let (first, second) = writes.split_at(half); + self.write_files(first)?; + thread::scope(|scope| { + let early = (!first.is_empty()).then(|| { + scope.spawn(|| { + let files = first + .iter() + .filter(|write| write.entry.kind != EntryKind::Symlink); + self.store + .platform + .sync_batch(files.map(|write| write.path.as_path())) + }) + }); + let written = self.write_files(second); + let synced = early.map(|early| { + early + .join() + .unwrap_or_else(|panic| panic::resume_unwind(panic)) + }); + written?; + synced.transpose().map_err(StoreError::from)?; + Ok::<_, SnapshotError>(()) + })?; + self.sync(changes, &writes) + } + + /// Writes `writes`, a contiguous run of files per core, rather than + /// files handed out one at a time: creating files locks their + /// directory, and a run mostly keeps to directories of its own, which + /// is 40% faster. + fn write_files(&self, writes: &[Write]) -> Result<(), SnapshotError> { + Store::

::on_every_core(writes, |chunk| { + chunk.iter().try_for_each(|write| self.write_file(write)) + }) + .into_iter() + .collect() + } + + /// Makes what a checkout of `changes` wrote, `writes`, durable: the + /// files, but symlinks, whose content their directory holds, and every + /// directory up to the root whose entries may have changed. + fn sync(&self, changes: &[FileChange], writes: &[Write]) -> Result<(), SnapshotError> { + let write = self.store.durable_write(); + for file in writes { + if file.entry.kind != EntryKind::Symlink { + write.sync_with(&file.path); + } + } + let mut dirs = BTreeSet::new(); for change in changes { - if let Some(entry) = change.new { - self.write_file(&change.path, entry)?; + let path = self.absolute(&change.path); + for dir in path.ancestors().skip(1) { + if !dirs.insert(dir.to_owned()) || dir == self.root { + break; + } } } + // Those a removal emptied are gone, with their entries. + for dir in dirs.into_iter().filter(|dir| dir.is_dir()) { + write.sync_with(dir); + } + write.commit().map_err(StoreError::from)?; Ok(()) } @@ -502,30 +609,28 @@ impl<'a, P: Platform> Worktree<'a, P> { } } - /// Writes the file `entry` describes at `path`, replacing any file - /// there. - fn write_file(&self, path: &RepoPath, entry: TreeEntry) -> Result<(), SnapshotError> { + /// Writes the file `write` describes, whose directory exists, replacing + /// any file there. + fn write_file(&self, write: &Write) -> Result<(), SnapshotError> { + let Write { path, entry } = write; + let (path, entry) = (path.as_path(), *entry); + let io_error = |source| SnapshotError::Io { + path: path.to_owned(), + source, + }; + // Never write through a symlink, or keep the old file's mode. + Self::remove(path)?; let blob = self.store.read(entry.id)?; let content = blob.blob_content().map_err(|source| StoreError::Decode { id: entry.id, source, })?; - let path = self.absolute(path); - let io_error = |source| SnapshotError::Io { - path: path.clone(), - source, - }; - // Never write through a symlink, or keep the old file's mode. - Self::remove(&path)?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(io_error)?; - } match entry.kind { - EntryKind::Symlink => symlink(OsStr::from_bytes(content), &path).map_err(io_error), - EntryKind::Executable => fs::write(&path, content) - .and_then(|()| fs::set_permissions(&path, fs::Permissions::from_mode(0o755))) + EntryKind::Symlink => symlink(OsStr::from_bytes(content), path).map_err(io_error), + EntryKind::Executable => fs::write(path, content) + .and_then(|()| fs::set_permissions(path, fs::Permissions::from_mode(0o755))) .map_err(io_error), - EntryKind::File | EntryKind::Tree => fs::write(&path, content).map_err(io_error), + EntryKind::File | EntryKind::Tree => fs::write(path, content).map_err(io_error), } }