Cotton code
184 lines · 7.3 KB · RustRaw
//! Slice 2c's guard: there is ONE write path, `cotton_store::mint::mint`.//! The old doors — `outbox::write_local` (a device's write), `outbox::write_here`//! (a file-local fact) and a caller's own `outbox::queue_ops` — are gone, and//! this scan keeps them gone: a write that folds without `mint` would carry no//! actor, could stamp under the wrong author, and could queue what a served//! file must not.use std::collections::BTreeSet;use std::path::{Path, PathBuf};/// The names a production file may not call. `queue_ops` is the store's own/// door onto `_outbox` and is `pub(crate)`; outside the store its name is a/// call that cannot compile, inside it [`QUEUE_CALLERS`] says who may.const GONE: [&str; 3] = ["write_local(", "write_here(", "outbox::queue_ops("];/// The store files that may call `queue_ops`: its definition, `mint` (a/// replica's mint queues what it folded, and the author fact), `mint`'s clock/// hook (the release pass queues what it released and re-dated, which mint/// held back), and the retry that re-queues a push the fold let through.const QUEUE_CALLERS: [&str; 4] = [    "cotton-store/src/outbox.rs",    "cotton-store/src/mint.rs",    "cotton-store/src/mint_clock.rs",    "cotton-store/src/rejected.rs",];fn crates_root() -> PathBuf {    cotton_store::manifest_dir()        .parent()        .expect("cotton-store sits in the crates directory")        .to_path_buf()}/// Every production source file under `crates/*/src`, as (path from `crates/`,/// text with any trailing `#[cfg(test)] mod …` cut off and comments blanked).fn sources() -> Vec<(String, String)> {    let root = crates_root();    let mut found = Vec::new();    let mut crates: Vec<PathBuf> = std::fs::read_dir(&root)        .expect("the crates directory")        .filter_map(Result::ok)        .map(|entry| entry.path().join("src"))        .filter(|src| src.is_dir())        .collect();    crates.sort();    for src in crates {        walk(&src, &root, &mut found);    }    assert!(        found.len() > 200,        "the scan found only {} files",        found.len()    );    found}fn walk(dir: &Path, root: &Path, found: &mut Vec<(String, String)>) {    let Ok(entries) = std::fs::read_dir(dir) else {        return;    };    let mut paths: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect();    paths.sort();    for path in paths {        if path.is_dir() {            walk(&path, root, found);            continue;        }        let name = path            .file_name()            .and_then(|n| n.to_str())            .unwrap_or_default();        if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" {            continue;        }        let Ok(text) = std::fs::read_to_string(&path) else {            continue;        };        let relative = path            .strip_prefix(root)            .unwrap_or(&path)            .to_string_lossy()            .replace('\\', "/");        found.push((relative, production_text(&text)));    }}/// The text before an inline `#[cfg(test)] mod … {`, with every `//` comment/// blanked so a sentence about the type is not a literal.fn production_text(text: &str) -> String {    let lines: Vec<&str> = text.lines().collect();    let mut end = lines.len();    for (index, line) in lines.iter().enumerate() {        if line.trim() != "#[cfg(test)]" {            continue;        }        let next = lines[index + 1..].iter().find(|l| !l.trim().is_empty());        if next.is_some_and(|l| l.trim_start().starts_with("mod ") && l.trim_end().ends_with('{')) {            end = index;            break;        }    }    lines[..end]        .iter()        .map(|line| match line.find("//") {            Some(at) => &line[..at],            None => line,        })        .collect::<Vec<_>>()        .join("\n")}/// Every line of `text` that names one of [`GONE`].fn gone_calls(text: &str) -> Vec<(usize, &'static str)> {    let mut found = Vec::new();    for (index, line) in text.lines().enumerate() {        for name in GONE {            if line.contains(name) {                found.push((index + 1, name));            }        }    }    found}/// RULE: No write path bypasses mint: no production source calls write_local, write_here or outbox::queue_ops, so every change to a file is minted with an actor, stamped by the file's author and queued only where a replica's mint queues it.#[test]fn no_write_path_bypasses_mint() {    let mut offenders = Vec::new();    for (path, text) in sources() {        for (line, name) in gone_calls(&text) {            // The store's own queue callers are judged by name below, not here.            if name == "outbox::queue_ops(" && path.starts_with("cotton-store/src/") {                continue;            }            offenders.push(format!("{path}:{line} calls `{name}`"));        }    }    assert!(        offenders.is_empty(),        "a write path that bypasses `mint` — route it through `cotton_store::mint::mint`:\n{}",        offenders.join("\n")    );}/// RULE: The store queues an op only from mint (its release pass included) and from the retry that re-queues a push: queue_ops is pub(crate) and these are the only files that name it, so a new caller shows up here first.#[test]fn the_store_queues_only_from_mint() {    let callers: BTreeSet<String> = sources()        .into_iter()        .filter(|(path, text)| path.starts_with("cotton-store/src/") && text.contains("queue_ops("))        .map(|(path, _)| path)        .collect();    let allowed: BTreeSet<String> = QUEUE_CALLERS.iter().map(|s| s.to_string()).collect();    assert_eq!(callers, allowed, "who calls queue_ops in the store");    let outbox = std::fs::read_to_string(crates_root().join("cotton-store/src/outbox.rs"))        .expect("outbox.rs");    assert!(        outbox.contains("pub(crate) fn queue_ops("),        "queue_ops is the store's own door, never public"    );}/// RULE: Every store writer selects its HLC only after the transaction that commits its receipt has begun; otherwise a lock wait can put a synced row before its own commit (architect, 18 Oct 2026).#[test]fn store_writers_select_the_stamp_inside_their_transaction() {    let source = production_text(&std::fs::read_to_string(crates_root().join("cotton-store/src/mint.rs")).expect("mint.rs"));    for function in ["pub fn first_author", "fn mint_in_the_file"] {        let body = source.split(function).nth(1).expect("writer function");        let transaction = body.find("db.transaction(").expect("writer opens a transaction");        let stamping = body.find("clock::stamping(").expect("writer selects a stamp");        assert!(transaction < stamping, "{function} selected its HLC before BEGIN");    }}#[test]fn the_scan_refuses_what_it_says_it_refuses() {    let planted = "    let ops = cotton_store::outbox::write_local(db, &changes, &opts, &mut clock, &mut ids)?;\n    // write_here( in a comment is not a call\n    queue_ops(db, &ops, &at)?;";    let text = production_text(planted);    let found = gone_calls(&text);    assert_eq!(found, vec![(1, "write_local(")]);    assert!(gone_calls(&production_text("    cotton_store::outbox::queue_ops(db, &ops, &at)?;")).len() == 1);    assert!(gone_calls(&production_text("    mint(db, &act, &clock, &mut ids, held)?;")).is_empty());}