Cotton code
647 lines · 39.5 KB · RustRaw
use super::*;use crate::test_support::{seeded_file, WORKSPACE};/// 7 Oct 2026, 00:00 UTC.const NOW: i64 = 1_791_331_200_000;// Keep rules must never turn a serving original, a print, a capture, or the last copy into free space.#[test]fn rules_preserve_protected_bytes_and_choose_only_unwanted_originals() {    let db = seeded_file("device:storage-test");    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at) VALUES ('phone',?,'phone','Invented phone','2026-01-01','phone','2026-01-01','2026-01-01'),('mac',?,'mac','Invented Mac','2026-01-01','mac','2026-01-01','2026-01-01')", &[text(WORKSPACE),text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) VALUES ('serving',?,1,'mac','device:mac','2026-01-01')", &[text(WORKSPACE)]).unwrap();    for (tail, tier, opened, captured, pinned) in [        ("photos/old.jpg", "original", None, 0, 0),        (            "photos/open.jpg",            "original",            Some("2026-10-01T00:00:00.000Z"),            0,            0,        ),        ("photos/thumb.jpg", "thumb", None, 0, 0),        ("photos/display.jpg", "display", None, 0, 0),        ("people/print.jpg", "original", None, 0, 0),        ("photos/capture.jpg", "original", None, 1, 0),        ("photos/pinned.jpg", "original", None, 0, 1),        ("photos/last.jpg", "original", None, 0, 0),    ] {        let key = format!("{WORKSPACE}/{tail}");        db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,tier,captured_here,pinned,last_viewed_at) VALUES (?,?,'synthetic','image/jpeg',10,?,'synced','2026-01-01T00:00:00.000Z','2026-01-01T00:00:00.000Z',?,?,?,?)", &[text(&key),text(WORKSPACE),text(&format!("/synthetic/{tail}")),text(tier),captured.into(),pinned.into(),opened.map_or(SqlValue::Null,text)]).unwrap();        if !tail.ends_with("last.jpg") {            db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?, ?, ?, 'mac','original',10,'2026-01-01','2026-01-01')", &[text(&key),text(WORKSPACE),text(&key)]).unwrap();        }    }    db.run(        "UPDATE _media SET state='pending' WHERE captured_here=1",        &[],    )    .unwrap();    db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES ('rule',?,'phone','photo','only_opened','2026-01-01','2026-01-01')", &[text(WORKSPACE)]).unwrap();    let plan = evaluate(&db, WORKSPACE, "phone", 1_791_331_200_000).unwrap();    assert_eq!(plan.candidates.len(), 1);    assert!(plan.candidates[0].key.ends_with("old.jpg"));    // The person's print is a People file: not a tool with bytes, so not listed.    assert_eq!(plan.rows.iter().map(|r| r.held_bytes).sum::<i64>(), 70);    assert_eq!(plan.rows.iter().map(|r| r.freeable_bytes).sum::<i64>(), 10);    assert!(evaluate(&db, WORKSPACE, "mac", 1_791_331_200_000)        .unwrap()        .candidates        .is_empty());    db.run("UPDATE cotton_storage_rules SET keep_rule='all'", &[])        .unwrap();    assert!(evaluate(&db, WORKSPACE, "phone", 1_791_331_200_000)        .unwrap()        .candidates        .is_empty());    db.run(        "UPDATE cotton_storage_rules SET keep_rule='recent_90_days'",        &[],    )    .unwrap();    assert_eq!(        evaluate(&db, WORKSPACE, "phone", 1_791_331_200_000)            .unwrap()            .candidates            .len(),        1    );    db.run(        "UPDATE cotton_devices SET revoked_at='2026-10-01' WHERE device_id='mac'",        &[],    )    .unwrap();    assert!(evaluate(&db, WORKSPACE, "phone", 1_791_331_200_000)        .unwrap()        .candidates        .is_empty());}/// RULE: only a named rule and a date that can be read let bytes go, and what a rule does not keep is held ON DEMAND for thirty days from its last opening — a malformed date cannot silently make a person's original old enough to discard, an original opened this month stays whatever its rule, and one last opened more than thirty days ago goes again (architect's brief, 12 Oct 2026: "evicted after 30 days unopened"; until then "only opened" kept an original for ever once it had been opened).#[test]fn only_named_rules_and_known_old_dates_can_release_bytes() {    let (old, recent) = ("2026-01-01T00:00:00.000Z", "2026-09-20T00:00:00.000Z");    let (this_week, in_august) = ("2026-10-01T00:00:00.000Z", "2026-08-01T00:00:00.000Z");    assert!(KeepRule::parse("old").is_err());    assert!(!KeepRule::Recent90Days.releases(None, None, NOW));    assert!(!KeepRule::Recent90Days.releases(Some("bad-date"), None, NOW));    assert!(!KeepRule::Recent90Days.releases(Some(recent), None, NOW));    assert!(KeepRule::Recent90Days.releases(Some(old), None, NOW));    assert!(KeepRule::OnlyOpened.releases(None, None, NOW));    assert!(!KeepRule::All.releases(Some(old), None, NOW));    // Thirty days from the last opening, for both rules that let anything go.    for rule in [KeepRule::OnlyOpened, KeepRule::Recent90Days] {        assert!(!rule.releases(Some(old), Some(this_week), NOW), "{rule:?} let go of what was opened this week");        assert!(rule.releases(Some(old), Some(in_august), NOW), "{rule:?} kept what nobody opened for two months");        assert!(!rule.releases(Some(old), Some("bad-date"), NOW), "{rule:?}: an opening nobody can date keeps the bytes");    }}// Rule changes must travel independently of the device's own measurements;// a background reading must never overwrite a choice made on another device.#[test]fn rules_sync_and_readings_do_not_reset_them_or_write_when_unchanged() {    let db = seeded_file("device:storage-writer");    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at) VALUES ('remote',?,'remote','Invented remote','2026-01-01','remote','2026-01-01','2026-01-01')",&[text(WORKSPACE)]).unwrap();    let mut ids = crate::protocol::ulid::Monotonic::new(crate::test_support::counter_seed());    set_rule(        &db,        WORKSPACE,        "remote",        "photo",        "only_opened",        1000,        &mut ids,        Held::Replica,    )    .unwrap();    let before = remote_rows(&db, WORKSPACE, "remote").unwrap();    assert_eq!(        before.iter().find(|r| r.tool == "photo").unwrap().keep_rule,        "only_opened"    );    assert!(before.iter().all(|r| r.measured_at.is_none()));    let rows = evaluate(&db, WORKSPACE, "remote", 2000).unwrap().rows;    publish(&db, WORKSPACE, &rows, 2000, &mut ids, Held::Replica).unwrap();    assert_eq!(        remote_rows(&db, WORKSPACE, "remote")            .unwrap()            .iter()            .find(|r| r.tool == "photo")            .unwrap()            .keep_rule,        "only_opened"    );    let stamped = db        .get(            "SELECT _hlc FROM cotton_storage_rules WHERE tool='photo'",            &[],        )        .unwrap()        .unwrap();    publish(&db, WORKSPACE, &rows, 3000, &mut ids, Held::Replica).unwrap();    assert_eq!(        db.get(            "SELECT _hlc FROM cotton_storage_rules WHERE tool='photo'",            &[]        )        .unwrap()        .unwrap()        .text("_hlc"),        stamped.text("_hlc")    );    assert!(        db.get("SELECT count(*) AS n FROM _outbox", &[])            .unwrap()            .unwrap()            .int("n")            .unwrap()            > 0    );    assert!(!crate::schema::table_specs::is_server_only(TABLE));    let peer = seeded_file("device:storage-peer");    // The device can publish its first reading before receiving a remotely    // chosen rule. Its later create must not assert the default over that rule.    peer.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at) VALUES ('remote',?,'remote','Invented remote','2026-01-01','remote','2026-01-01','2026-01-01')",&[text(WORKSPACE)]).unwrap();    let local = evaluate(&peer, WORKSPACE, "remote", 4000).unwrap().rows;    publish(&peer, WORKSPACE, &local, 4000, &mut ids, Held::Replica).unwrap();    let author = db        .get("SELECT author_id AS author FROM _meta", &[])        .unwrap()        .unwrap()        .text("author")        .unwrap()        .to_string();    let page = crate::changes::changes_since(&db, &author, "", 100).unwrap();    let folded = crate::fold::fold_ops(&peer, &page.ops).unwrap();    assert!(folded.rejected.is_empty(), "{folded:?}");    assert_eq!(        peer.get(            "SELECT keep_rule FROM cotton_storage_rules WHERE tool='photo'",            &[]        )        .unwrap()        .unwrap()        .text("keep_rule"),        Some("only_opened")    );    assert!(set_rule(        &db,        WORKSPACE,        "absent",        "photo",        "all",        4000,        &mut ids,        Held::Replica    )    .is_err());    assert!(set_rule(        &db,        WORKSPACE,        "remote",        "wrong",        "all",        4000,        &mut ids,        Held::Replica    )    .is_err());}// Two keys can share one content-addressed file. A kept alias (especially a// print) protects the file even when another alias's original can be dropped.#[test]fn shared_file_is_kept_when_any_alias_is_kept() {    let db = seeded_file("device:storage-test");    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at) VALUES ('phone',?,'phone','Phone','2026-01-01','phone','2026-01-01','2026-01-01'),('mac',?,'mac','Mac','2026-01-01','mac','2026-01-01','2026-01-01')",&[text(WORKSPACE),text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) VALUES ('serving',?,1,'mac','device:mac','2026-01-01')",&[text(WORKSPACE)]).unwrap();    for folder in ["photos", "people"] {        let key = format!("{WORKSPACE}/{folder}/invented.jpg");        db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,tier) VALUES (?,?,'synthetic','image/jpeg',10,'/synthetic/shared.jpg','synced','2026-01-01','2026-01-01','original')",&[text(&key),text(WORKSPACE)]).unwrap();        db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?, ?, ?, 'mac','original',10,'2026-01-01','2026-01-01')",&[text(&key),text(WORKSPACE),text(&key)]).unwrap();    }    db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES ('rule',?,'phone','photo','only_opened','2026-01-01','2026-01-01')",&[text(WORKSPACE)]).unwrap();    let plan = evaluate(&db, WORKSPACE, "phone", 1_791_331_200_000).unwrap();    assert!(plan.candidates.is_empty());    assert_eq!(plan.rows.iter().map(|r| r.held_bytes).sum::<i64>(), 10);    assert_eq!(plan.rows.iter().map(|r| r.freeable_bytes).sum::<i64>(), 0);}/// RULE: Storage lists only the tools that hold bytes — photos, videos, documents and messages — and a rule an older build synced for any other tool frees nothing and is refused by name.#[test]fn storage_lists_only_the_tools_that_hold_bytes_and_another_tools_rule_frees_nothing() {    let db = seeded_file("device:storage-test");    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at) VALUES ('phone',?,'phone','Invented phone','2026-01-01','phone','2026-01-01','2026-01-01'),('mac',?,'mac','Invented Mac','2026-01-01','mac','2026-01-01','2026-01-01')", &[text(WORKSPACE),text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) VALUES ('serving',?,1,'mac','device:mac','2026-01-01')", &[text(WORKSPACE)]).unwrap();    // An unopened original of every tool a file can be classified under, each    // held by the serving Mac: only a keep rule decides whether it may go.    for folder in ["photos", "meetings", "messages", "people", "elsewhere"] {        let key = format!("{WORKSPACE}/{folder}/invented.bin");        db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,tier) VALUES (?,?,'synthetic','application/octet-stream',10,?,'synced','2026-01-01T00:00:00.000Z','2026-01-01T00:00:00.000Z','original')", &[text(&key),text(WORKSPACE),text(&format!("/synthetic/{folder}.bin"))]).unwrap();        db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?, ?, ?, 'mac','original',10,'2026-01-01','2026-01-01')", &[text(&key),text(WORKSPACE),text(&key)]).unwrap();    }    // A rule for every tool, the ones no longer listed among them.    for tool in ["photo", "meeting", "thread", "person", "other"] {        db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES (?,?,'phone',?,'only_opened','2026-01-01','2026-01-01')", &[text(&row_id("phone", tool)),text(WORKSPACE),text(tool)]).unwrap();    }    let plan = evaluate(&db, WORKSPACE, "phone", NOW).unwrap();    assert_eq!(        plan.rows.iter().map(|r| r.tool.as_str()).collect::<Vec<_>>(),        ["photo", "video", "document", "thread"]    );    assert_eq!(        plan.candidates            .iter()            .map(|c| c.key.as_str())            .collect::<Vec<_>>(),        [            format!("{WORKSPACE}/messages/invented.bin").as_str(),            format!("{WORKSPACE}/photos/invented.bin").as_str()        ],        "only a photo's and a chat's original may go"    );    assert_eq!(plan.rows.iter().map(|r| r.held_bytes).sum::<i64>(), 20);    assert_eq!(plan.rows.iter().map(|r| r.freeable_bytes).sum::<i64>(), 20);    let remote = remote_rows(&db, WORKSPACE, "mac").unwrap();    assert_eq!(        remote.iter().map(|r| r.tool.as_str()).collect::<Vec<_>>(),        BYTE_TOOLS    );    assert!(remote.iter().all(|r| r.on_demand_bytes.is_none()), "another device's on-demand bytes are unknown, never 0");    for folder in ["meetings", "people", "elsewhere"] {        let key = format!("{WORKSPACE}/{folder}/invented.bin");        assert!(wants_original(&db, WORKSPACE, "phone", &key, NOW).unwrap());    }    // The background copy pass and the pass that frees agree, tool by tool.    for folder in ["photos", "messages"] {        let key = format!("{WORKSPACE}/{folder}/invented.bin");        assert!(!wants_original(&db, WORKSPACE, "phone", &key, NOW).unwrap());    }    let mut ids = crate::protocol::ulid::Monotonic::new(crate::test_support::counter_seed());    for tool in ["meeting", "person", "other"] {        let refused = set_rule(            &db,            WORKSPACE,            "phone",            tool,            "only_opened",            NOW,            &mut ids,            Held::Replica,        )        .unwrap_err()        .to_string();        assert!(refused.contains(tool), "{refused}");    }    for tool in BYTE_TOOLS {        set_rule(            &db,            WORKSPACE,            "phone",            tool,            "only_opened",            NOW,            &mut ids,            Held::Replica,        )        .unwrap();    }}// ── what a phone keeps of its bytes (architect's brief, 12 Oct 2026) ────const PHONE: &str = "phone";const MAC: &str = "mac";const OLD: &str = "2026-01-05T00:00:00.000Z";const RECENT: &str = "2026-09-20T00:00:00.000Z";const THIS_WEEK: &str = "2026-10-01T00:00:00.000Z";const IN_AUGUST: &str = "2026-08-01T00:00:00.000Z";/// A phone and the Mac that serves it, both live, the serving fact heard.fn household() -> Driver {    let db = seeded_file("device:storage-keep");    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,platform,approved_at,approved_by_device,created_at,updated_at) VALUES ('phone',?,'phone','Invented phone','ios','2026-01-01','phone','2026-01-01','2026-01-01'),('mac',?,'mac','Invented Mac','mac','2026-01-01','mac','2026-01-01','2026-01-01')", &[text(WORKSPACE),text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) VALUES ('serving',?,1,'mac','device:mac','2026-01-01')", &[text(WORKSPACE)]).unwrap();    db}/// Ten bytes this device holds under `{file}/{tail}`, last opened at `opened`,/// and — unless this is the last copy — the serving Mac's original of them.fn held(db: &Driver, tail: &str, tier: Option<&str>, opened: Option<&str>, on_the_mac: bool) -> String {    let key = format!("{WORKSPACE}/{tail}");    db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,tier,last_viewed_at) VALUES (?,?,'synthetic','image/jpeg',10,?,'synced',?,?,?,?)", &[text(&key),text(WORKSPACE),text(&format!("/synthetic/{tail}")),text(THIS_WEEK),text(THIS_WEEK),tier.map_or(SqlValue::Null,text),opened.map_or(SqlValue::Null,text)]).unwrap();    if on_the_mac {        db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?, ?, ?, 'mac','original',10,'2026-01-01','2026-01-01')", &[text(&key),text(WORKSPACE),text(&key)]).unwrap();    }    key}fn chat(db: &Driver, thread: &str) {    db.run("INSERT INTO cotton_msg_threads (id,workspace_id,kind,title,created_at,updated_at) VALUES (?,?,'group','An invented chat','2026-01-01','2026-01-01')", &[text(thread),text(WORKSPACE)]).unwrap();}/// A message of `thread` sent at `sent_at` whose one file is `key`, and the/// line the file's own index keeps of who names a key.fn message(db: &Driver, thread: &str, id: &str, sent_at: &str, key: &str) {    db.run("INSERT INTO cotton_msg_messages (id,thread_id,workspace_id,direction,channel,origin,sent_at,created_at,media) VALUES (?,?,?,'in','whatsapp','imported',?,?,?)", &[text(id),text(thread),text(WORKSPACE),text(sent_at),text(sent_at),text(&serde_json::json!([{ "key": key }]).to_string())]).unwrap();    db.run("INSERT OR IGNORE INTO _media_key_names (key,tbl,row_id) VALUES (?,'cotton_msg_messages',?)", &[text(key),text(id)]).unwrap();}/// The library's row for the picture at `key`, taken long ago — its id, from/// a digest of `mark` — and the line the file's own index keeps of who names/// a key.fn library_photo(db: &Driver, mark: char, key: &str) -> String {    let sha = mark.to_string().repeat(64);    let id = format!("photo:{sha}");    db.run("INSERT INTO cotton_photos (id,workspace_id,key,sha256,content_type,size_bytes,taken_at,created_at,updated_at) VALUES (?,?,?,?,'image/jpeg',10,?,?,?)", &[text(&id),text(WORKSPACE),text(key),text(&sha),text(OLD),text(OLD),text(OLD)]).unwrap();    db.run("INSERT OR IGNORE INTO _media_key_names (key,tbl,row_id) VALUES (?,'cotton_photos',?)", &[text(key),text(&id)]).unwrap();    id}fn keep_rule(db: &Driver, kind: &str, target: &str, rule: &str) {    db.run("INSERT INTO cotton_device_keep (id,workspace_id,device_id,kind,target,rule,created_at,updated_at) VALUES (?,?,'phone',?,?,?,'2026-10-01','2026-10-01')", &[text(&crate::protocol::derived_id::device_keep_id(PHONE, kind, target)),text(WORKSPACE),text(kind),text(target),text(rule)]).unwrap();}fn going(db: &Driver, device: &str) -> Vec<String> {    let mut keys: Vec<String> = evaluate(db, WORKSPACE, device, NOW).unwrap().candidates.into_iter().flat_map(|c| c.aliases).collect();    keys.sort();    keys}fn row(db: &Driver, device: &str, tool: &str) -> StorageRow {    evaluate(db, WORKSPACE, device, NOW).unwrap().rows.into_iter().find(|r| r.tool == tool).unwrap()}/// RULE: a phone nobody gave a rule keeps the last three months of chat media and holds older on demand — a chat's file from a message older than ninety days goes thirty days after it was last opened, one from a recent message stays, nothing is downloaded, the last copy never goes (the serving Mac must hold that exact original), and a Mac keeps all of it; a rule a person stores for Messages replaces the default.#[test]fn a_phone_keeps_three_months_of_chat_media_and_holds_older_on_demand_for_thirty_days() {    let db = household();    chat(&db, "chat-1");    let recent = held(&db, "messages/chat-1/recent.jpg", None, None, true);    let unopened = held(&db, "messages/chat-1/unopened.jpg", None, None, true);    let opened = held(&db, "messages/chat-1/opened.jpg", None, Some(THIS_WEEK), true);    let stale = held(&db, "messages/chat-1/stale.opus", None, Some(IN_AUGUST), true);    let last = held(&db, "messages/chat-1/last.jpg", None, Some(IN_AUGUST), false);    message(&db, "chat-1", "m-recent", RECENT, &recent);    for (id, key) in [("m-unopened", &unopened), ("m-opened", &opened), ("m-stale", &stale), ("m-last", &last)] {        message(&db, "chat-1", id, OLD, key);    }    // The media index's library row for a chat picture does not make it a    // Photos original: it is still the chat's, and Messages' rule decides.    library_photo(&db, 'a', &unopened);    assert_eq!(going(&db, PHONE), [stale.clone(), unopened.clone()], "older than three months and unopened for thirty days");    let messages = row(&db, PHONE, "thread");    assert_eq!(messages.keep_rule, "recent_90_days", "a phone's default, with no rule row");    assert_eq!(messages.name, "Messages");    assert_eq!((messages.held_bytes, messages.freeable_bytes), (50, 20));    assert_eq!(messages.on_demand_bytes, Some(40), "kept: the recent one; on demand: the four older, whether or not they may go yet");    assert_eq!(row(&db, PHONE, "photo").held_bytes, 0, "a chat's picture is counted once, under Messages");    // The background copy pass never undoes it, and never fetches for a phone    // what its rule does not keep.    assert!(wants_original(&db, WORKSPACE, PHONE, &recent, NOW).unwrap());    assert!(wants_original(&db, WORKSPACE, PHONE, &opened, NOW).unwrap());    assert!(!wants_original(&db, WORKSPACE, PHONE, &unopened, NOW).unwrap());    assert_eq!(remote_rows(&db, WORKSPACE, PHONE).unwrap().iter().find(|r| r.tool == "thread").unwrap().keep_rule, "recent_90_days");    // A Mac keeps everything unless a person says otherwise.    db.run("UPDATE cotton_serving_machine SET device_credential_id='other-mac'", &[]).unwrap();    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,platform,approved_at,approved_by_device,created_at,updated_at) VALUES ('other-mac',?,'other-mac','Another invented Mac','mac','2026-01-01','mac','2026-01-01','2026-01-01')", &[text(WORKSPACE)]).unwrap();    db.run("UPDATE cotton_media_holdings SET device_id='other-mac'", &[]).unwrap();    assert!(going(&db, MAC).is_empty());    let on_a_mac = row(&db, MAC, "thread");    assert_eq!((on_a_mac.keep_rule.as_str(), on_a_mac.on_demand_bytes), ("all", Some(0)));    assert_eq!(going(&db, PHONE), [stale, unopened], "and the phone's answer did not depend on which Mac serves");    // A stored rule replaces the default.    db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES (?,?,'phone','thread','all','2026-01-01','2026-01-01')", &[text(&row_id(PHONE, "thread")),text(WORKSPACE)]).unwrap();    assert!(going(&db, PHONE).is_empty());    assert_eq!(row(&db, PHONE, "thread").on_demand_bytes, Some(0));}/// RULE: a status's bytes never stay on a phone — not for having been opened today, not under any Storage rule — while the phone's rules never keep statuses, and they go the moment the serving Mac holds that original (never the last copy); a phone whose owner chose to keep statuses holds them as it holds a chat's file, and a Mac is never asked.#[test]fn a_statuss_bytes_never_stay_on_a_phone() {    let db = household();    let status = held(&db, "messages/statuses/watched.jpg", None, Some(THIS_WEEK), true);    let only_copy = held(&db, "messages/statuses/only-copy.jpg", None, Some(THIS_WEEK), false);    let chat_file = held(&db, "messages/chat-1/today.jpg", None, Some(THIS_WEEK), true);    assert!(crate::keep::status_bytes_never(&db, PHONE, &status).unwrap());    assert!(!crate::keep::status_bytes_never(&db, PHONE, &chat_file).unwrap(), "a chat's file is no status");    assert!(!crate::keep::status_bytes_never(&db, MAC, &status).unwrap(), "a Mac keeps everything");    assert_eq!(going(&db, PHONE), [status.clone()], "opened this week and still going; the only copy stays");    assert_eq!(row(&db, PHONE, "thread").on_demand_bytes, Some(30), "none of the three is kept: {only_copy} only waits for a Mac to hold it");    keep_rule(&db, crate::keep::KIND_TABLE, "cotton_stories", "all");    assert!(!crate::keep::status_bytes_never(&db, PHONE, &status).unwrap(), "the owner's own rule replaces the default");    assert!(going(&db, PHONE).is_empty(), "held on demand like any file nothing here names, and opened this week");}/// RULE: a record or a group kept always pins its bytes — the files of a chat a RECORD rule names, and the pictures of an album a GROUP rule names, are never let go, whatever the tool's rule and however long unopened; the same files outside the pin go. Pinned is not evicted and nothing more: nothing is fetched for it.#[test]fn a_record_or_a_group_kept_always_pins_its_bytes() {    let db = household();    for thread in ["chat-kept", "chat-other"] {        chat(&db, thread);    }    let kept = held(&db, "messages/chat-kept/old.jpg", None, None, true);    let other = held(&db, "messages/chat-other/old.jpg", None, None, true);    message(&db, "chat-kept", "m-kept", OLD, &kept);    message(&db, "chat-other", "m-other", OLD, &other);    // Two library pictures under "only opened", one of them in an album.    db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES (?,?,'phone','photo','only_opened','2026-01-01','2026-01-01')", &[text(&row_id(PHONE, "photo")),text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_media_albums (id,workspace_id,kind,title,starts_at,ends_at,created_at,updated_at) VALUES ('album-1',?,'event','An invented album','2026-01-01','2026-01-02','2026-01-01','2026-01-01')", &[text(WORKSPACE)]).unwrap();    let mut pictures = Vec::new();    let mut ids = Vec::new();    for (name, mark) in [("in-album", 'b'), ("loose", 'c')] {        let key = held(&db, &format!("photos/{name}.jpg"), Some("original"), None, true);        ids.push(library_photo(&db, mark, &key));        pictures.push(key);    }    db.run("INSERT INTO cotton_media_album_items (id,workspace_id,album_id,record_kind,record_id,added_by,sort_at,created_at,updated_at) VALUES ('item-1',?,'album-1','photo',?,'user','2026-01-01','2026-01-01','2026-01-01')", &[text(WORKSPACE),text(&ids[0])]).unwrap();    let mut all = vec![kept.clone(), other.clone(), pictures[0].clone(), pictures[1].clone()];    all.sort();    assert_eq!(going(&db, PHONE), all, "with no pin, all four go");    keep_rule(&db, crate::keep::KIND_RECORD, "cotton_msg_threads:chat-kept", crate::keep::ALWAYS);    keep_rule(&db, crate::keep::KIND_GROUP, "album-1", crate::keep::ALWAYS);    assert_eq!(going(&db, PHONE), [other, pictures[1].clone()], "the kept chat's file and the kept album's picture stay");    assert_eq!(row(&db, PHONE, "thread").on_demand_bytes, Some(10), "a pinned file is kept, not held on demand");    assert_eq!(row(&db, PHONE, "photo").on_demand_bytes, Some(10));}/// RULE: an original no record on a phone names is held on demand — a mail attachment somebody opened lives in the email's own list and in no library row, so no rule keeps it: it stays thirty days from its last opening and then goes (the brief: "attachments — on demand, 30 days"), never the last copy; on a Mac the same file is kept.#[test]fn what_no_record_on_a_phone_names_is_held_on_demand() {    let db = household();    let opened = held(&db, "photos/attachment-opened.jpg", Some("original"), Some(THIS_WEEK), true);    let stale = held(&db, "photos/attachment-stale.jpg", Some("original"), Some(IN_AUGUST), true);    let library = held(&db, "photos/library.jpg", Some("original"), Some(IN_AUGUST), true);    library_photo(&db, 'd', &library);    assert_eq!(going(&db, PHONE), [stale], "the library picture is kept by Photos' rule; {opened} has its thirty days");    let photos = row(&db, PHONE, "photo");    assert_eq!((photos.keep_rule.as_str(), photos.held_bytes, photos.on_demand_bytes), ("all", 30, Some(20)));    db.run("UPDATE cotton_devices SET platform='mac' WHERE device_id='phone'", &[]).unwrap();    assert!(going(&db, PHONE).is_empty(), "a Mac keeps what it holds");}/// RULE: the one SQL reading of "a Mac that keeps everything" names every tool Storage rules — a byte tool missing from it would let a Mac that keeps that tool's bytes on demand count as a keeper, and a phone could let its copy go against it.#[test]fn the_keeper_sql_names_every_byte_tool() {    for tool in BYTE_TOOLS {        assert!(KEEPS_EVERYTHING.contains(&format!("'{tool}'")), "{tool} is missing from KEEPS_EVERYTHING");    }}/// A Mac of this file, by its device key, with every byte tool saying `rule`/// (`None`: no rule rows, which is `all`).fn a_mac(db: &Driver, device: &str, rule: Option<&str>) {    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,platform,approved_at,approved_by_device,created_at,updated_at) VALUES (?,?,?,'Another invented Mac','mac','2026-01-01','mac','2026-01-01','2026-01-01')", &[text(device),text(WORKSPACE),text(device)]).unwrap();    if let Some(rule) = rule {        every_byte_tool(db, device, rule);    }}fn every_byte_tool(db: &Driver, device: &str, rule: &str) {    for tool in BYTE_TOOLS {        db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES (?,?,?,?,?,'2026-01-01','2026-01-01') ON CONFLICT(id) DO UPDATE SET keep_rule=excluded.keep_rule", &[text(&row_id(device, tool)),text(WORKSPACE),text(device),text(tool),text(rule)]).unwrap();    }}/// `device`'s live hold on the original at `key`.fn holds(db: &Driver, device: &str, key: &str) {    db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?,?,?,?,'original',10,'2026-01-01','2026-01-01')", &[text(&crate::media_holdings::holding_id(device, key, crate::media_holdings::Tier::Original)),text(WORKSPACE),text(key),text(device)]).unwrap();}/// RULE: never the last copy, with the bucket no holder and one Mac that keeps everything — a phone or a rows-only Mac lets an original go only when a Mac that keeps everything (other than itself) holds that exact original; a serving Mac's copy, a rows-only Mac's copy or no recorded copy at all never lets it go; the serving Mac lets nothing go even when its row says rows only; and when no Mac keeps everything nothing goes anywhere (sync programme, lane D, 12 Oct 2026; coordinator's ruling the same day on a rows-only serving Mac).#[test]fn the_last_copy_holds_with_one_mac_that_keeps_everything() {    let db = household();    // The serving Mac keeps rows only (the owner's); one other Mac    // keeps everything; another keeps rows only.    every_byte_tool(&db, MAC, "only_opened");    a_mac(&db, "keeper", None);    a_mac(&db, "rows", Some("only_opened"));    every_byte_tool(&db, PHONE, "only_opened");    let kept = held(&db, "photos/kept.jpg", Some("original"), None, false);    let on_the_server = held(&db, "photos/server.jpg", Some("original"), None, false);    let on_a_rows_mac = held(&db, "photos/rows.jpg", Some("original"), None, false);    held(&db, "photos/nowhere.jpg", Some("original"), None, false);    holds(&db, "keeper", &kept);    holds(&db, MAC, &on_the_server);    holds(&db, "rows", &on_a_rows_mac);    assert_eq!(going(&db, PHONE), [kept.clone()], "only a keeper's copy lets a phone's go");    assert_eq!(going(&db, "rows"), [kept.clone()], "and a rows-only Mac's");    assert!(going(&db, MAC).is_empty(), "the serving Mac keeps everything whatever its row says");    assert!(going(&db, "keeper").is_empty(), "a keeper keeps everything");    // The keeper's own copy is no fence for itself, and a keeper that turns    // to rows only is a keeper no more: nothing goes anywhere.    every_byte_tool(&db, "keeper", "only_opened");    for device in [PHONE, "rows", MAC, "keeper"] {        assert!(going(&db, device).is_empty(), "{device} let a copy go with no Mac keeping everything");    }}/// RULE: what a Mac keeps is read off and written as its own Storage rules, one choice for every byte tool — "rows only" is every byte tool only_opened, "everything" every one all, a mix set tool by tool is neither; writing the choice it already says writes nothing; a phone is refused (its keep rules say what it keeps), and so is any choice but the two.#[test]fn what_a_mac_keeps_is_its_byte_tools_rules() {    let db = household();    assert_eq!(mac_keeps(&db, WORKSPACE, MAC).unwrap(), MacKeeps::Everything, "no rule rows: everything");    assert!(keeps_everything(&db, WORKSPACE, MAC).unwrap());    assert!(!keeps_everything(&db, WORKSPACE, PHONE).unwrap(), "a phone is never a keeper");    assert!(mac_keeps_patches(&db, WORKSPACE, PHONE, MacKeeps::RowsOnly, THIS_WEEK).is_err());    assert!(mac_keeps_patches(&db, WORKSPACE, MAC, MacKeeps::PerTool, THIS_WEEK).is_err());    assert!(MacKeeps::parse("per_tool").is_err());    let patches = mac_keeps_patches(&db, WORKSPACE, MAC, MacKeeps::RowsOnly, THIS_WEEK).unwrap();    let mut ids: Vec<String> = patches.iter().map(|(id, _)| id.clone()).collect();    ids.sort();    let mut every: Vec<String> = BYTE_TOOLS.iter().map(|tool| row_id(MAC, tool)).collect();    every.sort();    assert_eq!(ids, every, "one row per byte tool");    assert!(patches.iter().all(|(_, p)| p["keep_rule"] == "only_opened" && p["device_id"] == MAC));    every_byte_tool(&db, MAC, "only_opened");    assert_eq!(mac_keeps(&db, WORKSPACE, MAC).unwrap(), MacKeeps::RowsOnly);    assert!(!keeps_everything(&db, WORKSPACE, MAC).unwrap());    assert!(mac_keeps_patches(&db, WORKSPACE, MAC, MacKeeps::RowsOnly, THIS_WEEK).unwrap().is_empty(), "the same choice writes nothing");    let back = mac_keeps_patches(&db, WORKSPACE, MAC, MacKeeps::Everything, THIS_WEEK).unwrap();    assert_eq!(back.len(), BYTE_TOOLS.len());    assert!(back.iter().all(|(_, p)| p["keep_rule"] == "all" && !p.contains_key("workspace_id")), "existing rows: the rule alone");    db.run("UPDATE cotton_storage_rules SET keep_rule='all' WHERE tool='photo'", &[]).unwrap();    assert_eq!(mac_keeps(&db, WORKSPACE, MAC).unwrap(), MacKeeps::PerTool);    assert!(!keeps_everything(&db, WORKSPACE, MAC).unwrap(), "a Mac that keeps some tools on demand is no keeper");}/// RULE: A Rows only Mac never background-fetches an original, even if opened this week, because its automatic release would otherwise be undone immediately; the serving Mac keeps every original whatever its Files choice.#[test]fn rows_only_macs_do_not_rehydrate_recently_opened_originals() {    let db = household();    a_mac(&db, "rows", Some("only_opened"));    a_mac(&db, "keeper", None);    every_byte_tool(&db, MAC, "only_opened");    assert!(!pulls_every_original(&db, WORKSPACE, "rows").unwrap());    assert!(pulls_every_original(&db, WORKSPACE, MAC).unwrap());    for tail in ["meetings/standup.m4a", "photos/opened.jpg"] {        let key = format!("{WORKSPACE}/{tail}");        db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,state,created_at,updated_at,last_viewed_at) VALUES (?,?,'synthetic','application/octet-stream',10,'synced',?,?,?)", &[text(&key),text(WORKSPACE),text(OLD),text(OLD),text(THIS_WEEK)]).unwrap();        assert!(!wants_original(&db, WORKSPACE, "rows", &key, NOW).unwrap());        assert!(wants_original(&db, WORKSPACE, "keeper", &key, NOW).unwrap());        assert!(wants_original(&db, WORKSPACE, MAC, &key, NOW).unwrap());    }}/// RULE: after stopping keeping, a rule-fetched original follows the thirty-day release rule from arrival until it is opened; unkeep cancels fetching without immediately discarding a fresh download.#[test]fn unkept_rule_download_has_thirty_days_before_release() {    let db = seeded_file("device:kept-release");    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,platform,approved_at,approved_by_device,created_at,updated_at) VALUES ('phone',?,'phone','Synthetic phone','ios','2026-01-01','phone','2026-01-01','2026-01-01'),('mac',?,'mac','Synthetic Mac','macos','2026-01-01','mac','2026-01-01','2026-01-01')", &[text(WORKSPACE),text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) VALUES ('serving',?,1,'mac','device:mac','2026-01-01')", &[text(WORKSPACE)]).unwrap();    let key=format!("{WORKSPACE}/photos/kept.jpg");    db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,tier,fetched_by_rule) VALUES (?,?,'synthetic','image/jpeg',10,'/synthetic/kept.jpg','synced','2026-10-01T00:00:00.000Z','2026-10-01T00:00:00.000Z','original',1)", &[text(&key),text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES ('held',?,?,'mac','original',10,'2026-01-01','2026-01-01')", &[text(WORKSPACE),text(&key)]).unwrap();    db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES ('rule',?,'phone','photo','only_opened','2026-01-01','2026-01-01')", &[text(WORKSPACE)]).unwrap();    assert!(evaluate(&db,WORKSPACE,"phone",NOW).unwrap().candidates.is_empty());    assert_eq!(evaluate(&db,WORKSPACE,"phone",NOW+31*DAY_MS).unwrap().candidates.len(),1);}/// RULE: keeping every WhatsApp original must not widen Instagram; each source's byte rule governs retention as well as fetching, so the two paths never disagree.#[test]fn whatsapp_bytes_can_widen_without_changing_instagram() {    let db=household();chat(&db,"sources");    let wa=held(&db,"messages/sources/wa.jpg",None,None,true);    let ig=held(&db,"messages/sources/ig.jpg",None,None,true);    message(&db,"sources","wa",OLD,&wa);message(&db,"sources","ig",OLD,&ig);    db.run("UPDATE cotton_msg_messages SET channel='instagram' WHERE id='ig'",&[]).unwrap();    assert_eq!(going(&db,PHONE).len(),2);    let mut ids=crate::protocol::ulid::Monotonic::new(crate::test_support::counter_seed());    set_rule(&db,WORKSPACE,PHONE,"whatsapp","all",NOW,&mut ids,Held::Replica).unwrap();    assert_eq!(going(&db,PHONE),vec![ig.clone()]);    assert!(wants_original(&db,WORKSPACE,PHONE,&wa,NOW).unwrap());    assert!(!wants_original(&db,WORKSPACE,PHONE,&ig,NOW).unwrap());    assert_eq!(byte_rule(&db,WORKSPACE,PHONE,"instagram").unwrap(),KeepRule::Recent90Days);    set_rule(&db,WORKSPACE,MAC,"whatsapp","only_opened",NOW+1,&mut ids,Held::Replica).unwrap();    assert!(!keeps_everything(&db,WORKSPACE,MAC).unwrap());    assert_eq!(mac_keeps(&db,WORKSPACE,MAC).unwrap(),MacKeeps::PerTool);}/// RULE: a rule-fetched original outside gallery tools also follows the thirty-day release rule after unkeep; opening it removes its cap charge but preserves its arrival origin for retention.#[test]fn rule_fetched_meeting_audio_is_released_after_unkeep_and_its_grace() {    let db=household();    let key=held(&db,"meetings/meeting/full.m4a",Some("original"),Some(OLD),true);    db.run("UPDATE _media SET fetched_by_rule=1 WHERE key=?",&[text(&key)]).unwrap();    assert!(evaluate(&db,WORKSPACE,PHONE,NOW).unwrap().candidates.is_empty());    assert_eq!(evaluate(&db,WORKSPACE,PHONE,NOW+31*DAY_MS).unwrap().candidates.len(),1);    let opened=js::to_iso_string(NOW+29*DAY_MS).unwrap();    crate::media_ledger::mark_viewed(&db,&key,&opened).unwrap();    assert!(evaluate(&db,WORKSPACE,PHONE,NOW+31*DAY_MS).unwrap().candidates.is_empty());    assert_eq!(evaluate(&db,WORKSPACE,PHONE,NOW+60*DAY_MS).unwrap().candidates.len(),1);}