Cotton code
380 lines · 15.1 KB · RustRaw
//! A RECEIPT'S BYTES ARE MADE ONCE, BY `mint`, AND NEVER AGAIN. A receipt is//! the write (design 3.1-3.4): every device holds it byte for byte as minted,//! a forwarded one travels as its minted bytes, and keys will sign them. So//! no statement may `UPDATE` the `bytes` of a stored receipt — in `_writes`,//! `_tombstones`, `_outbox`, `_parked` or `_gone` — nor//! `REPLACE` a row of one, and nothing outside the one encoder's home may//! encode a receipt: a path that decoded a stored receipt and encoded it//! again would make new bytes for an old write.//!//! The one upsert allowed is named below with its reason. Test modules are//! not scanned; production source under `crates/*/src` is.use std::path::{Path, PathBuf};/// The tables that hold a receipt's bytes.const RECEIPT_TABLES: [&str; 5] = ["_writes", "_tombstones", "_outbox", "_parked", "_gone"];/// `(file, table, why)`: an `INSERT … ON CONFLICT DO UPDATE` that may set/// `bytes`, because it puts a DIFFERENT receipt in the row, never new bytes/// for the same one.const ALLOWED_UPSERTS: [(&str, &str, &str); 1] = [(    "cotton-store/src/receipts.rs",    "_tombstones",    "a row keeps only its highest retract (3.4): a higher retract REPLACES the lower one, op id, actor and bytes together, each as its own writer minted them",)];/// The files that may call the encoder (`canonical::encode`): its own home,/// whose decode checks that bytes are already canonical by encoding them/// again and comparing, and `wire::from_receipt`, the one place bytes are/// made for a receipt `mint` has just built.const ENCODERS: [&str; 3] = ["cotton-store/src/canonical.rs", "cotton-store/src/wire.rs", IMPLIED];/// The one place a stored receipt's bytes are cleared and put back/// (TRIM, 21 Nov 2026, schema 151): a receipt the object served is IMPLIED —/// its bytes cleared — only after encoding it again from its row gave its/// minted bytes exactly, and is put back to those same bytes (made from the/// row the same way) before anything else touches its row. Never new bytes/// for a write: the bytes as minted, kept elsewhere for a while. It encodes,/// so it is an encoder; it updates `_writes.bytes`, so it is named here.const IMPLIED: &str = "cotton-store/src/receipts/implied.rs";/// The files that may call `wire::from_receipt`: its home, `mint`, and/// `mint`'s clock hook, whose release pass MINTS a re-dated receipt — a new/// receipt with a new op id naming the old one (`restamps`), never the old/// one's bytes rewritten.const FROM_RECEIPT_CALLERS: [&str; 3] = [    "cotton-store/src/wire.rs",    "cotton-store/src/mint.rs",    "cotton-store/src/mint_clock.rs",];fn crates_root() -> PathBuf {    cotton_store::manifest_dir()        .parent()        .expect("cotton-store sits in the crates directory")        .to_path_buf()}/// One production source file: its path from `crates/`, its code with every/// comment and string literal blanked, and its string literals.struct Source {    path: String,    code: String,    literals: Vec<String>,}/// Every production source file under `crates/*/src`, with any trailing/// `#[cfg(test)] mod … {` cut off.fn sources() -> Vec<Source> {    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<Source>) {    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('\\', "/");        let (code, literals) = lex(&before_test_module(&text));        found.push(Source {            path: relative,            code,            literals,        });    }}/// The text before an inline `#[cfg(test)] mod … {`.fn before_test_module(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].join("\n")}/// Split Rust source into its code (comments and literals blanked) and its/// string literals (plain, byte and raw). A small lexer, enough for SQL text:/// escapes are kept as written.fn lex(text: &str) -> (String, Vec<String>) {    let chars: Vec<char> = text.chars().collect();    let mut code = String::with_capacity(text.len());    let mut literals = Vec::new();    let mut i = 0;    while i < chars.len() {        let c = chars[i];        let next = chars.get(i + 1).copied();        if c == '/' && next == Some('/') {            while i < chars.len() && chars[i] != '\n' {                i += 1;            }            continue;        }        if c == '/' && next == Some('*') {            let mut depth = 0;            while i < chars.len() {                if chars[i] == '/' && chars.get(i + 1) == Some(&'*') {                    depth += 1;                    i += 2;                } else if chars[i] == '*' && chars.get(i + 1) == Some(&'/') {                    depth -= 1;                    i += 2;                    if depth == 0 {                        break;                    }                } else {                    i += 1;                }            }            code.push(' ');            continue;        }        let ident_before = i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_');        // A raw string: r"…", r#"…"#, br#"…"#.        if !ident_before && (c == 'r' || (c == 'b' && next == Some('r'))) {            let mut j = if c == 'b' { i + 2 } else { i + 1 };            let mut hashes = 0;            while chars.get(j) == Some(&'#') {                hashes += 1;                j += 1;            }            if chars.get(j) == Some(&'"') {                let close: Vec<char> = std::iter::once('"').chain(std::iter::repeat_n('#', hashes)).collect();                let start = j + 1;                let mut k = start;                while k < chars.len() && chars[k..].iter().take(close.len()).ne(close.iter()) {                    k += 1;                }                literals.push(chars[start..k.min(chars.len())].iter().collect());                code.push_str("\"\"");                i = (k + close.len()).min(chars.len());                continue;            }        }        if c == '"' {            let start = i + 1;            let mut k = start;            while k < chars.len() && chars[k] != '"' {                if chars[k] == '\\' {                    k += 1;                }                k += 1;            }            literals.push(chars[start..k.min(chars.len())].iter().collect());            code.push_str("\"\"");            i = k + 1;            continue;        }        // A char literal ('"', '\'', 'x') — not a lifetime.        if c == '\'' {            if next == Some('\\') {                let mut k = i + 2;                while k < chars.len() && chars[k] != '\'' {                    k += 1;                }                i = k + 1;                code.push_str("' '");                continue;            }            if chars.get(i + 2) == Some(&'\'') {                i += 3;                code.push_str("' '");                continue;            }        }        code.push(c);        i += 1;    }    (code, literals)}/// A literal as SQL to read: lower case, every run of white space (and a/// line-continuation backslash) one space.fn sql(literal: &str) -> String {    literal        .replace("\\n", " ")        .replace("\\t", " ")        .replace('\\', " ")        .to_lowercase()        .split_whitespace()        .collect::<Vec<_>>()        .join(" ")}/// Whether `text` assigns the `bytes` column (`bytes =`, `bytes=`).fn assigns_bytes(text: &str) -> bool {    let mut from = 0;    while let Some(at) = text[from..].find("bytes") {        let at = from + at;        let before = text[..at].chars().next_back();        let after = text[at + "bytes".len()..].trim_start();        let word = before.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '.'));        if word && after.starts_with('=') && !after.starts_with("==") {            return true;        }        from = at + "bytes".len();    }    false}/// What a statement in `literal` does to a receipt's bytes that it may not:/// `(table, what)` for each.fn rewrites(literal: &str) -> Vec<(String, &'static str)> {    let text = sql(literal);    let mut found = Vec::new();    for table in RECEIPT_TABLES.iter().map(|t| t.to_string()).chain(std::iter::once("{".to_string())) {        let update = format!("update {table}");        if let Some(at) = text.find(&update) {            let rest = &text[at + update.len()..];            let boundary = table == "{" || rest.chars().next().is_none_or(|c| !(c.is_alphanumeric() || c == '_'));            if boundary {                if let Some(set) = rest.find(" set ") {                    if assigns_bytes(&rest[set..]) {                        found.push((table.clone(), "an UPDATE that sets bytes"));                    }                }            }        }        if table == "{" {            continue;        }        for into in [format!("replace into {table}"), format!("insert or replace into {table}")] {            if text.contains(&format!("{into} ")) || text.contains(&format!("{into}(")) {                found.push((table.clone(), "a REPLACE of a stored receipt"));            }        }        let insert = format!("insert into {table}");        if let Some(at) = text.find(&insert) {            let rest = &text[at..];            if let Some(upsert) = rest.find("do update set") {                if assigns_bytes(&rest[upsert..]) {                    found.push((table.clone(), "an upsert that sets bytes"));                }            }        }    }    found}/// Whether `code` names the canonical module's encoder, as a call or an/// import.fn names_encoder(code: &str) -> bool {    if code.contains("canonical::encode") {        return true;    }    // `use …::canonical::{…, encode, …}`.    let mut from = 0;    while let Some(at) = code[from..].find("canonical::{") {        let at = from + at;        let list = &code[at..code[at..].find('}').map_or(code.len(), |end| at + end)];        if list            .split(|c: char| !(c.is_alphanumeric() || c == '_'))            .any(|word| word == "encode")        {            return true;        }        from = at + 1;    }    false}/// RULE: A stored receipt's bytes are never rewritten after mint; only the named upsert and encoder entry points may write them./// A receipt's bytes are never rewritten after mint: no production statement UPDATEs or REPLACEs the bytes of a stored receipt (_writes, _tombstones, _outbox, _parked, _gone) outside the one named upsert, and only canonical.rs and wire.rs call the encoder and only wire.rs, mint.rs and mint's clock hook call from_receipt, so nothing re-encodes a stored receipt.#[test]fn receipt_bytes_are_never_rewritten_after_mint() {    let mut offenders = Vec::new();    for source in sources() {        for literal in &source.literals {            for (table, what) in rewrites(literal) {                let allowed = ALLOWED_UPSERTS                    .iter()                    .any(|(path, t, _)| *path == source.path && *t == table && what == "an upsert that sets bytes")                    || (source.path == IMPLIED && table == "_writes" && what == "an UPDATE that sets bytes");                if !allowed {                    offenders.push(format!("{}: {what} in {table}: {}", source.path, sql(literal)));                }            }        }        if names_encoder(&source.code) && !ENCODERS.contains(&source.path.as_str()) {            offenders.push(format!("{}: calls the receipt encoder (canonical::encode)", source.path));        }        if source.code.contains("from_receipt(") && !FROM_RECEIPT_CALLERS.contains(&source.path.as_str()) {            offenders.push(format!("{}: calls wire::from_receipt, which makes new bytes", source.path));        }    }    assert!(        offenders.is_empty(),        "a receipt's bytes are made once, by `mint`, and stored as made — move this through `mint` or keep the stored bytes:\n{}",        offenders.join("\n")    );}/// RULE: The scan above still sees what it guards: each allowed upsert, encoder and from_receipt caller is still where the lists say, and the scanner flags an UPDATE, a REPLACE and an upsert of bytes when shown one, so an entry leaves a list with the change that removes it.#[test]fn the_rewrite_scan_still_sees_its_sites() {    let all = sources();    let at = |path: &str| all.iter().find(|s| s.path == path).unwrap_or_else(|| panic!("{path} is gone"));    for (path, table, _) in ALLOWED_UPSERTS {        assert!(            at(path).literals.iter().any(|l| rewrites(l).iter().any(|(t, _)| t == table)),            "{path} no longer upserts {table}'s bytes — take it off ALLOWED_UPSERTS"        );    }    for path in ENCODERS {        let source = at(path);        assert!(            names_encoder(&source.code) || (path.ends_with("canonical.rs") && source.code.contains("encode(")),            "{path} no longer calls the encoder — take it off ENCODERS"        );    }    for path in FROM_RECEIPT_CALLERS {        assert!(at(path).code.contains("from_receipt("), "{path} no longer calls from_receipt");    }    for (statement, flagged) in [        ("UPDATE _writes SET bytes = ? WHERE op_id = ?", true),        ("UPDATE _outbox\n   SET attempts = attempts + 1, bytes=? WHERE op_id = ?", true),        ("UPDATE {table} SET bytes = ?", true),        ("INSERT OR REPLACE INTO _parked (op_id, bytes) VALUES (?, ?)", true),        ("INSERT INTO _gone (op_id, bytes) VALUES (?, ?) ON CONFLICT(op_id) DO UPDATE SET bytes = excluded.bytes", true),        ("UPDATE _outbox SET attempts = attempts + 1, last_error = ? WHERE op_id = ?", false),        ("INSERT INTO _writes (op_id, bytes) VALUES (?, ?)", false),        ("SELECT op_id, bytes FROM _outbox WHERE bytes = ?", false),    ] {        assert_eq!(!rewrites(statement).is_empty(), flagged, "{statement}");    }}