Cotton code
355 lines · 15.3 KB · RustRaw
//! A workspace file a test can have for the price of a copy.//!//! **Why this exists.** `create_workspace` runs the whole migration ladder from//! zero, and a test that wants a file pays for all of it. Measured on this//! repo's Linux box, mean of ten, a quiet machine://!//! | what a test does to get a file | cost |//! |---|---|//! | `Driver::open` + `create_workspace` | **1,557.1 ms** |//! | the same with `synchronous = OFF` | 785.4 ms |//! | `fs::copy` of a built file, then open | **39.6 ms** |//!//! The file is 2.43 MB, so the copy is a memcpy and the ladder is hundreds of//! statements, the FTS5 virtual tables among them. Thirty-nine times cheaper,//! and it subsumes the pragma: half the ladder's cost is `fsync` and the other//! half is work the copy does not repeat either.//!//! **Why it is on DISK and not in a `OnceLock`.** `cargo nextest` runs every//! test in its OWN PROCESS. A process-local cache is therefore a cache of one,//! and a `OnceLock` template is built once per TEST — the ladder still runs,//! and a copy is paid on top of it. That was measured too, and it is a//! regression: three interleaved A/B runs of cotton-ffi's 875 tests on a//! falling load gave 149.7 s → 310.4 s, 132.0 s → 168.0 s, 93.2 s → 107.3 s,//! the process-local version losing every pair. The cache has to outlive the//! process, so it is a file.//!//! **Why no lock.** Every template built from the same key is interchangeable —//! the identity is rewritten after the copy, and the rest is the ladder's own//! deterministic output — so two builders racing simply build two and//! `fs::rename` over the same name. A rename is atomic on one filesystem and a//! reader mid-copy keeps the inode it opened. The worst case is a few builders//! paying 1.5 s once at start-up instead of one. What that costs nothing to get//! right is that each of them builds under a name NO other builder can have —//! see `building_path`, and the flake that proved a pid and a clock are not one.//!//! **Why the key cannot go stale.** It is a hash of what THIS BUILD's ladder//! is — core migration statements and compiled package SQL — so a change to//! the schema names a different file. The cache directory is shared between//! branches (it is under `CARGO_TARGET_DIR`), which is exactly the shape that//! has bitten this repo before; keying on the ladder's own bytes rather than on//! a version number is what makes sharing it safe.use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicU64, Ordering};use rusqlite::types::Value;use sha2::{Digest, Sha256};use crate::create::create_workspace;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::meta::Meta;use crate::migrate::MIGRATIONS;/// This crate has no I/O error of its own — every path here is a test's own/// scratch directory, so a failure is a broken machine rather than a state to/// model.fn io(what: &'static str) -> impl Fn(std::io::Error) -> StoreError {    move |error| StoreError::refused(format!("cotton-store: could not write {what} — {error}"))}/// A fresh workspace file at `path`, with this `meta` — a copy of the template.////// Equivalent to `Driver::open` followed by `create_workspace`: the ladder is/// pure DDL, so `_meta` is the only thing in a new file that depends on WHICH/// workspace it is, and it is written here. Use it anywhere a TEST wants a/// file. `cotton-store`'s own suites keep calling `create_workspace`, because/// running the ladder from zero is what they are for.pub fn create_workspace_for_test(path: &Path, meta: &Meta) -> Result<Driver> {    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(io("the folder for the copy"))?;    }    std::fs::copy(template()?, path).map_err(io("the copy of the template"))?;    let db = Driver::open(path)?;    stamp(&db, meta)?;    Ok(db)}/// A fresh IN-MEMORY workspace with this `meta` — the template's pages/// restored into a new connection.////// Equivalent to `Driver::open_in_memory` followed by `create_workspace`,/// for the fixtures that never wanted a file on disk. SQLite's backup API/// copies the template page for page, so the ladder does not run here either:/// 3.5 ms against 111 ms for the in-memory ladder on this repo's Mac, with/// SQLite optimised (`crates/Cargo.toml`), and the ladder is the larger share/// of a `cotton-tools` or `cotton-server` test's own time.pub fn create_workspace_in_memory_for_test(meta: &Meta) -> Result<Driver> {    let mut conn = rusqlite::Connection::open_in_memory()?;    conn.restore(        rusqlite::MAIN_DB,        template()?,        None::<fn(rusqlite::backup::Progress)>,    )?;    let db = Driver::from_connection(conn, false)?;    stamp(&db, meta)?;    Ok(db)}/// A fresh IN-MEMORY copy of a file that `build` makes once from the/// ladder's template — stamped with `meta`, then whatever a suite's fixture/// writes on top (cotton-tools' harness: the shell and the kit, 13 s a test/// on this repo's Mac, up to 85 s on the loaded CI runner, which pushed a/// guards shard past its fifteen minutes on run 5971).////// The built file is cached beside the ladder's template as/// `<ladder>-<family>-<version>.db`: `family` names whose fixture it is (the/// ids its rows carry) and `version` everything `build` depends on (the code/// that writes it), so a rebuild names a new file ([`built_for_test`]).pub fn cached_in_memory_for_test(family: &str, version: &str, meta: &Meta, build: impl FnOnce(&Driver) -> Result<()>) -> Result<Driver> {    let path = built_for_test(family, version, meta, build)?;    let mut conn = rusqlite::Connection::open_in_memory()?;    conn.restore(rusqlite::MAIN_DB, &path, None::<fn(rusqlite::backup::Progress)>)?;    Driver::from_connection(conn, false)}/// [`cached_in_memory_for_test`] as a file at `path`, for the fixtures a/// controller opens from disk (cotton-ffi's seeded phone: the shell and the/// kit, which every one of its tests paid again — a minute each on the/// loaded Linux box, 6 Nov 2026).pub fn cached_for_test(path: &Path, family: &str, version: &str, meta: &Meta, build: impl FnOnce(&Driver) -> Result<()>) -> Result<Driver> {    let built = built_for_test(family, version, meta, build)?;    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(io("the folder for the copy"))?;    }    std::fs::copy(built, path).map_err(io("the copy of the built fixture"))?;    Driver::open(path)}/// The cached file `build` makes once from the ladder's template, stamped/// with `meta`: built under a name no other builder can have and renamed into/// place, so no reader sees a half; building a new version removes the/// family's older ones (each is tens of MB) once nothing can still be/// reading them.////// ONE BUILDER AT A TIME, unlike the template's (see the module): a fixture/// that imports the kit is seconds of work, not one and a half, and nextest/// starts a part's eight first tests together, each of which found no file/// and built its own (eight kit imports at once, on a box already loaded)./// So a builder holds `<file>.lock` while it builds and the others wait on/// it, then find the file and copy it. The lock is advisory and only orders/// the work: two builders that miss each other still each build a file that/// serves, and the rename keeps either.fn built_for_test(family: &str, version: &str, meta: &Meta, build: impl FnOnce(&Driver) -> Result<()>) -> Result<PathBuf> {    let prefix = format!("{}-{family}-", ladder_fingerprint());    let path = template_path().with_file_name(format!("{prefix}{version}.db"));    if path.exists() {        return Ok(path);    }    let template = template()?;    let lock = std::fs::OpenOptions::new()        .create(true)        .truncate(false)        .write(true)        .open(lock_path(&path))        .map_err(io("the fixture's lock"))?;    lock.lock().map_err(io("the fixture's lock"))?;    if path.exists() {        return Ok(path);    }    retire_older(&path, &prefix);    let building = Building::at(building_path(&path));    std::fs::copy(template, building.path()).map_err(io("the copy of the template"))?;    let db = Driver::open(building.path())?;    stamp(&db, meta)?;    build(&db)?;    db.checkpoint_truncate()?;    drop(db);    std::fs::rename(building.path(), &path).map_err(io("the built fixture into place"))?;    building.renamed();    Ok(path)}/// Where a builder of the cached file at `path` holds its lock.fn lock_path(path: &Path) -> PathBuf {    let mut name = path.as_os_str().to_owned();    name.push(".lock");    PathBuf::from(name)}/// The family's other versions (and their locks), older than any test still/// reading one.fn retire_older(path: &Path, prefix: &str) {    let Some(folder) = path.parent() else { return };    let Ok(entries) = std::fs::read_dir(folder) else { return };    let settled = std::time::SystemTime::now() - std::time::Duration::from_secs(600);    for entry in entries.flatten() {        let name = entry.file_name();        let name = name.to_string_lossy();        let old = entry.metadata().and_then(|stat| stat.modified()).is_ok_and(|at| at < settled);        let mine = entry.path() == path || entry.path() == lock_path(path);        if name.starts_with(prefix) && (name.ends_with(".db") || name.ends_with(".db.lock")) && !mine && old {            let _ = std::fs::remove_file(entry.path());        }    }}/// Write the identity a new file is born with over the template's own.fn stamp(db: &Driver, meta: &Meta) -> Result<()> {    db.run(        "UPDATE _meta SET workspace_id = ?, owner_id = ?, device_id = ?, last_server_seq = ?, \         last_hlc = ?",        &[            Value::Text(meta.workspace_id.clone()),            Value::Text(meta.owner_id.clone()),            Value::Text(meta.device_id.clone()),            Value::Integer(meta.last_server_seq),            meta.last_hlc.clone().map_or(Value::Null, Value::Text),        ],    )?;    Ok(())}/// The cached file every copy comes from, built on first use.fn template() -> Result<PathBuf> {    let path = template_path();    if path.exists() {        return Ok(path);    }    std::fs::create_dir_all(path.parent().expect("the cache directory"))        .map_err(io("the template cache directory"))?;    // Built under a name nobody else can be writing, then renamed over the    // shared one. Two builders racing produce two equivalent files and the    // second rename wins; neither can be seen half-written.    let building = Building::at(building_path(&path));    let db = Driver::open(building.path())?;    create_workspace(        &db,        &Meta {            workspace_id: "00000000-0000-4000-8000-00000000template".to_string(),            owner_id: "owner:template".to_string(),            device_id: "device:template".to_string(),            last_server_seq: 0,            last_hlc: None,        },    )?;    // The file is about to be copied BY PATH, so everything has to be in it    // rather than in a `-wal` sidecar the copy would leave behind.    db.checkpoint_truncate()?;    drop(db);    std::fs::rename(building.path(), &path).map_err(io("the template into place"))?;    building.renamed();    Ok(path)}/// A name for the file being built that no other builder can be using — not/// another process, and not another THREAD of this one.////// The pid and the clock alone were not enough, and the failure was a flake:/// `cargo test` runs a crate's whole suite as threads of ONE process, so on a/// cold cache every test that wants a file reaches [`template`] at the same/// moment with the same pid — and `SystemTime::now()` is MICROSECOND-grained on/// macOS, so sixteen threads asking at once get the same number (measured on/// this repo's Mac: 917 collisions in 1024 samples). Two builders then held one/// path, and the second one's `create_workspace` ran the ladder over the file/// the first had already made: `table _meta already exists`, raised through/// whichever test happened to be second — a different one each run, green when/// re-run because by then the template was on disk.////// The counter is what makes the name unique inside the process; the pid and/// the clock keep it unique between processes and across a pid the OS has/// handed out again, which is what a `.building` file left by a killed run/// would otherwise collide with.fn building_path(template: &Path) -> PathBuf {    static NEXT: AtomicU64 = AtomicU64::new(0);    template.with_extension(format!(        "{}.{}.{}.building",        std::process::id(),        NEXT.fetch_add(1, Ordering::Relaxed),        std::time::SystemTime::now()            .duration_since(std::time::UNIX_EPOCH)            .map(|since| since.as_nanos())            .unwrap_or_default()    ))}/// The half-built template, and its sidecars, removed unless the build reached/// its rename — a ladder that fails partway leaves nothing behind in a cache/// directory every branch on this machine shares.struct Building(Option<PathBuf>);impl Building {    fn at(path: PathBuf) -> Self {        Self(Some(path))    }    fn path(&self) -> &Path {        self.0.as_deref().expect("the name is taken only on the way out")    }    /// The file is at its shared name now; there is nothing left to remove.    fn renamed(mut self) {        self.0 = None;    }}impl Drop for Building {    fn drop(&mut self) {        if let Some(path) = self.0.take() {            for suffix in ["", "-wal", "-shm"] {                let mut sidecar = path.clone().into_os_string();                sidecar.push(suffix);                let _ = std::fs::remove_file(PathBuf::from(sidecar));            }        }    }}fn template_path() -> PathBuf {    let root = std::env::var_os("CARGO_TARGET_DIR")        .map(PathBuf::from)        .unwrap_or_else(std::env::temp_dir);    root.join("cotton-test-templates")        .join(format!("{}.db", ladder_fingerprint()))}/// What this build's ladder IS, as sixteen hex characters.////// Every migration's version and statements, plus the compiled package SQL/// that workspace creation applies after the core. A schema change moves it, which is what lets one cache directory/// serve branches that disagree about the schema.fn ladder_fingerprint() -> String {    // These inputs are compiled into the process; parsing every package for    // every copied fixture would turn a warm test cache into repeated work.    static FINGERPRINT: std::sync::OnceLock<String> = std::sync::OnceLock::new();    FINGERPRINT.get_or_init(|| {        let shapes = crate::schema::package_tables::builtin_shapes().expect("compiled package shapes");        ladder_fingerprint_with_shapes(&shapes)    }).clone()}fn ladder_fingerprint_with_shapes(    shapes: &[(String, Vec<crate::schema::package_tables::PackageTable>)],) -> String {    let mut hasher = Sha256::new();    for migration in MIGRATIONS {        hasher.update(migration.version.to_le_bytes());        for statement in migration.statements {            hasher.update(statement.as_bytes());            hasher.update([0]);        }    }    for (_, tables) in shapes {        for statement in crate::schema::package_tables::generate(tables, true).expect("compiled package SQL") {            hasher.update(statement.as_bytes());            hasher.update([0]);        }    }    hex::encode(hasher.finalize())[..16].to_string()}#[cfg(test)]#[path = "test_template_tests.rs"]mod tests;