Cotton code
813 lines · 31.1 KB · RustRaw
//! The holdings vocabulary, against a real seeded file.//!//! Every instant is explicit and every row is synthetic//! ([nothing-real-ever-goes-in-cotton-s-public-tree]): the crate reads no clock,//! so a failure here is reproducible.use super::*;use std::cell::RefCell;use crate::mint::Held;use crate::outbox::IdSource;use crate::protocol::ulid::Monotonic;use crate::test_support::{counter_seed, fold_create, seeded_file, SEED_AUTHOR, SEED_MS, WORKSPACE};/// The one id source a test thread holds (see `IDS`).type ThreadIds = Monotonic<Box<dyn FnMut(&mut [u8])>>;thread_local! {    /// ONE id source per test thread, as the app holds one per process: the    /// ids are monotonic within a source and every stamp here is explicit, so    /// a fresh source per call would hand out the same id twice.    static IDS: RefCell<ThreadIds> =        RefCell::new(Monotonic::new(Box::new(counter_seed())));}/// The thread's id source, as an [`IdSource`] a call can borrow.struct Ids;impl IdSource for Ids {    fn next_op_id(&mut self, now_ms: i64) -> crate::error::Result<String> {        IDS.with_borrow_mut(|ids| ids.next_op_id(now_ms))    }}/// This file's old AUTHOR id — what `_meta.device_id` names, and what the old/// writers stamped and held under. Production-shaped: `device:<ulid>`, and no/// device row. A write made now is stamped with the author its first mint/// minted (`_meta.author_id`), which is a different id.const THIS_FILE: &str = "device:01J0000000000000000000000A";/// This phone's DEVICE KEY — the id its `cotton_devices` row carries and the/// one its holdings name it by. 43 synthetic characters.const THIS_PHONE: &str = "PhoneKey___________________________________";const THE_MAC: &str = "MacKey_____________________________________";const AN_OLD_PHONE: &str = "OldPhoneKey________________________________";/// A device key nobody approved in this workspace.const A_STRANGER: &str = "StrangerKey________________________________";/// 2026-09-16T09:00:00.000Z, as milliseconds.const T0: i64 = 1_789_549_200_000;const MINUTE: i64 = 60_000;fn object() -> String {    format!("{WORKSPACE}/photos/{}.heic", "a".repeat(64))}fn other_object() -> String {    format!("{WORKSPACE}/photos/{}.heic", "b".repeat(64))}/// A file written by `THIS_FILE` on the phone `THIS_PHONE`, with three/// approved devices in it — by their keys, never by the author id.fn file() -> Driver {    let db = seeded_file(THIS_FILE);    for (device, name) in [        (THIS_PHONE, "The invented phone"),        (THE_MAC, "The invented Mac"),        (AN_OLD_PHONE, "An older invented phone"),    ] {        approve(&db, device, name);    }    db}fn approve(db: &Driver, device_id: &str, name: &str) {    fold_create(        db,        "cotton_devices",        &format!("dev:{device_id}"),        serde_json::json!({            "id": format!("dev:{device_id}"),            "workspace_id": WORKSPACE,            "device_id": device_id,            "name": name,            "approved_at": "2026-09-01T09:00:00.000Z",            "approved_by_device": THIS_PHONE,            "created_at": "2026-09-01T09:00:00.000Z",            "updated_at": "2026-09-01T09:00:00.000Z",        }),        SEED_AUTHOR,        SEED_MS,    );}fn revoke(db: &Driver, device_id: &str) {    db.run(        "UPDATE cotton_devices SET revoked_at = ? WHERE device_id = ?",        &[text("2026-09-15T09:00:00.000Z"), text(device_id)],    )    .expect("the revocation");}/// A hold recorded by a device that is NOT this file — what a peer's op folds/// to when it arrives. Written straight in, because the point of the API is/// that this file's own writer refuses to do it.fn a_peers_hold(db: &Driver, device_id: &str, object_key: &str, tier: Tier, at: &str) {    let id = holding_id(device_id, object_key, tier);    fold_create(        db,        "cotton_media_holdings",        &id,        serde_json::json!({            "id": id,            "workspace_id": WORKSPACE,            "object_key": object_key,            "device_id": device_id,            "tier": tier.as_str(),            "bytes": 4_194_304,            "verified_at": at,            "created_at": at,            "updated_at": at,        }),        device_id,        1_789_556_400_000,    );}fn rows_for(db: &Driver, object_key: &str) -> i64 {    db.get(        "SELECT COUNT(*) AS n FROM cotton_media_holdings WHERE object_key = ?",        &[text(object_key)],    )    .expect("reads")    .and_then(|row| row.int("n"))    .expect("a count")}fn holder_ids(holders: &[Holder]) -> Vec<&str> {    holders        .iter()        .map(|holder| holder.device_id.as_str())        .collect()}#[test]fn a_tier_round_trips_through_the_word_the_column_stores() {    for tier in Tier::ALL {        assert_eq!(Tier::parse(tier.as_str()), Some(tier));        assert_eq!(tier.to_string(), tier.as_str());    }    assert_eq!(Tier::parse("blur"), None, "a word this build cannot name");}#[test]fn a_recorded_hold_carries_a_stamp_so_it_can_travel() {    let db = file();    let key = object();    let id = record_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("the hold");    assert_eq!(id, format!("hold:original:{THIS_PHONE}:{key}"));    let row = db        .get(            "SELECT * FROM cotton_media_holdings WHERE id = ?",            &[text(&id)],        )        .expect("reads")        .expect("a row");    assert_eq!(row.text("device_id"), Some(THIS_PHONE));    assert_eq!(row.text("tier"), Some("original"));    assert_eq!(row.int("bytes"), Some(4_096));    assert_eq!(row.text("verified_at"), Some("2026-09-16T09:00:00.000Z"));    assert_eq!(row.text("dropped_at"), None);    // The whole reason the write goes through the fold rather than an INSERT:    // a row with an empty `_hlc` is in the `origin` author's stream and reaches    // no peer under its own name.    // The file's author, minted by its first write as `device:<ulid>` — not    // the device id `_meta` names.    let author = crate::mint::file_author(&db).expect("the file's author");    assert_ne!(author, THIS_FILE);    let stamp = row.text("_hlc").unwrap_or_default();    assert!(        stamp.ends_with(&format!(":{author}")),        "the hold is stamped by the file that wrote it: {stamp}"    );}#[test]fn a_second_record_of_the_same_hold_is_a_restatement_not_a_second_row() {    let db = file();    let key = object();    let first = record_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("the hold");    let again = record_holding(        &db,        WORKSPACE,        THIS_PHONE,        &key,        Tier::Original,        4_096,        T0 + MINUTE,        &mut Ids,        Held::Served,    )    .expect("the same hold, restated");    assert_eq!(first, again, "the id is derived, so it is the same row");    assert_eq!(rows_for(&db, &key), 1);    let row = db        .get(            "SELECT created_at, verified_at, updated_at FROM cotton_media_holdings WHERE id = ?",            &[text(&first)],        )        .expect("reads")        .expect("a row");    assert_eq!(        row.text("created_at"),        Some("2026-09-16T09:00:00.000Z"),        "the fact being restated is the same fact, so it keeps the instant it was first recorded"    );    assert_eq!(        row.text("verified_at"),        Some("2026-09-16T09:01:00.000Z"),        "what moves is when the device last confirmed the file is really there"    );    assert_eq!(row.text("updated_at"), Some("2026-09-16T09:01:00.000Z"));    // And it is still one holder, not two.    assert_eq!(        holder_ids(&holders_of(&db, WORKSPACE, &key, Tier::Original).expect("reads")),        vec![THIS_PHONE]    );}#[test]fn a_dropped_hold_is_a_column_not_a_delete() {    let db = file();    let key = object();    let id = record_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("the hold");    assert!(        drop_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, T0 + MINUTE, &mut Ids, Held::Served)            .expect("the eviction")    );    assert_eq!(        rows_for(&db, &key),        1,        "the row stays: \"I had these bytes and I no longer do\" is a fact the other devices need"    );    let row = db        .get(            "SELECT dropped_at, bytes FROM cotton_media_holdings WHERE id = ?",            &[text(&id)],        )        .expect("reads")        .expect("a row");    assert_eq!(row.text("dropped_at"), Some("2026-09-16T09:01:00.000Z"));    assert_eq!(row.int("bytes"), Some(4_096), "what it weighed is still known");    assert!(        holders_of(&db, WORKSPACE, &key, Tier::Original)            .expect("reads")            .is_empty(),        "a dropped hold is not a holder"    );    assert!(        db.get(            "SELECT tbl FROM _tombstones WHERE row_id = ?",            &[text(&id)]        )        .expect("reads")        .is_none(),        "and it is not a delete, so there is no tombstone to prune the fact away with"    );    // Recording it again makes this device a holder again — an eviction is not    // a one-way door.    record_holding(        &db,        WORKSPACE,        THIS_PHONE,        &key,        Tier::Original,        4_096,        T0 + 2 * MINUTE,        &mut Ids,        Held::Served,    )    .expect("the bytes are back");    assert_eq!(        holder_ids(&holders_of(&db, WORKSPACE, &key, Tier::Original).expect("reads")),        vec![THIS_PHONE]    );}#[test]fn dropping_a_hold_this_device_never_recorded_says_so_rather_than_failing() {    let db = file();    assert!(        !drop_holding(&db, WORKSPACE, THIS_PHONE, &object(), Tier::Original, T0, &mut Ids, Held::Served)            .expect("no hold is not an error"),        "a device evicting a file it never recorded has nothing to say"    );    assert_eq!(rows_for(&db, &object()), 0, "and it invents no row to say it");}/// RULE: A media holding is refused unless it names a live device key of the workspace, so the store never holds a row no reader could see.#[test]fn a_hold_no_reader_could_see_is_refused() {    let db = file();    let key = object();    revoke(&db, AN_OLD_PHONE);    // The file's own AUTHOR id is no device row: a hold under it is the row    // that hid eleven thousand originals from every standby (todo 77f48a68).    for (device, why) in [        (THIS_FILE, "no device of this database"),        (A_STRANGER, "no device of this database"),        (AN_OLD_PHONE, "revoked"),    ] {        let refused = record_holding(&db, WORKSPACE, device, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served)            .expect_err("a hold no reader could see is refused");        assert!(refused.to_string().contains(why), "{device}: {refused}");        let refused = drop_holding(&db, WORKSPACE, device, &key, Tier::Original, T0, &mut Ids, Held::Served)            .expect_err("and so is a drop");        assert!(refused.to_string().contains(why), "{device}: {refused}");    }    assert_eq!(rows_for(&db, &key), 0, "nothing was written either way");    // A live device key is accepted, and every reader sees it.    record_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("a live device key holds");    assert_eq!(        holder_ids(&holders_of(&db, WORKSPACE, &key, Tier::Original).expect("reads")),        vec![THIS_PHONE]    );}#[test]fn a_devices_standing_is_live_revoked_or_absent() {    let db = file();    revoke(&db, AN_OLD_PHONE);    let standing = |device| device_standing(&db, WORKSPACE, device).expect("reads");    assert_eq!(standing(THIS_PHONE), DeviceStanding::Live);    assert_eq!(standing(AN_OLD_PHONE), DeviceStanding::Revoked);    assert_eq!(standing(THIS_FILE), DeviceStanding::Absent);    assert_eq!(        device_standing(&db, "another-workspace", THIS_PHONE).expect("reads"),        DeviceStanding::Absent,        "a row in one workspace is no row in another"    );}/// RULE: A file's holds written under its own author id are retired, and only those, and only when that author id is no device row.#[test]fn author_id_holds_are_retired_and_nothing_else_is() {    let db = file();    let one = object();    let two = other_object();    // What the old writers left: this file's rows under its author id.    a_peers_hold(&db, THIS_FILE, &one, Tier::Original, "2026-09-10T08:00:00.000Z");    a_peers_hold(&db, THIS_FILE, &two, Tier::Thumb, "2026-09-10T08:00:00.000Z");    // Rows that are not the author's: a peer's, and this phone's own by key.    a_peers_hold(&db, THE_MAC, &one, Tier::Original, "2026-09-10T08:00:00.000Z");    record_holding(&db, WORKSPACE, THIS_PHONE, &two, Tier::Original, 4_096, T0, &mut Ids, Held::Served).expect("a hold");    // Later than every row's stamp, as a retirement is: the rows were written    // before holdings named a machine by its key.    let later = T0 + 180 * MINUTE;    let retired = retire_author_holdings(&db, WORKSPACE, 100, later, &mut Ids, Held::Served).expect("the retirement");    assert_eq!(        retired,        vec![            RetiredHold {                object_key: one.clone(),                tier: Tier::Original,                bytes: 4_194_304,                created_at: "2026-09-10T08:00:00.000Z".to_string(),            },            RetiredHold {                object_key: two.clone(),                tier: Tier::Thumb,                bytes: 4_194_304,                created_at: "2026-09-10T08:00:00.000Z".to_string(),            },        ]    );    assert!(!is_live_hold(&db, THIS_FILE, &one, Tier::Original).expect("reads"));    assert!(!is_live_hold(&db, THIS_FILE, &two, Tier::Thumb).expect("reads"));    assert!(is_live_hold(&db, THE_MAC, &one, Tier::Original).expect("reads"), "a peer's row");    assert!(is_live_hold(&db, THIS_PHONE, &two, Tier::Original).expect("reads"), "a key row");    assert_eq!(rows_for(&db, &one), 2, "a column, never a delete");    // Stamped by this file, so it is this file's own write.    let stamp = db        .get(            "SELECT _hlc FROM cotton_media_holdings WHERE id = ?",            &[text(&holding_id(THIS_FILE, &one, Tier::Original))],        )        .expect("reads")        .and_then(|row| row.text("_hlc").map(str::to_string))        .unwrap_or_default();    let author = crate::mint::file_author(&db).expect("the file's author");    assert!(stamp.ends_with(&format!(":{author}")), "{stamp}");    assert!(        retire_author_holdings(&db, WORKSPACE, 100, later + MINUTE, &mut Ids, Held::Served)            .expect("again")            .is_empty(),        "a second pass has nothing to retire"    );}#[test]fn a_file_whose_author_id_is_a_device_row_retires_nothing() {    // A joined Mac's file is authored by its own key, so its rows were always    // visible and are not clutter.    let db = seeded_file(THIS_PHONE);    approve(&db, THIS_PHONE, "The invented phone");    record_holding(&db, WORKSPACE, THIS_PHONE, &object(), Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("a hold");    assert!(retire_author_holdings(&db, WORKSPACE, 100, T0 + MINUTE, &mut Ids, Held::Served)        .expect("reads")        .is_empty());    assert!(is_live_hold(&db, THIS_PHONE, &object(), Tier::Original).expect("reads"));}#[test]fn a_revoked_device_is_not_a_holder() {    let db = file();    let key = object();    record_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("this phone's hold");    a_peers_hold(&db, THE_MAC, &key, Tier::Original, "2026-09-16T08:00:00.000Z");    a_peers_hold(        &db,        AN_OLD_PHONE,        &key,        Tier::Original,        "2026-09-16T08:00:00.000Z",    );    assert_eq!(        holder_ids(&holders_of(&db, WORKSPACE, &key, Tier::Original).expect("reads")),        vec![THE_MAC, AN_OLD_PHONE, THIS_PHONE],        "three live devices hold it, in device-id order"    );    revoke(&db, AN_OLD_PHONE);    // The revoked phone's ROWS are untouched — only that phone may write them,    // and it may never come back. The reader is what makes the revoke correct,    // the instant the device row folds.    assert_eq!(        rows_for(&db, &key),        3,        "a revoke writes nothing to somebody else's holdings"    );    assert_eq!(        holder_ids(&holders_of(&db, WORKSPACE, &key, Tier::Original).expect("reads")),        vec![THE_MAC, THIS_PHONE]    );    assert_eq!(        objects_with_fewer_than(&db, WORKSPACE, 3, Tier::Original).expect("reads"),        vec![key.clone()],        "two live holders is fewer than three"    );}#[test]fn the_work_list_is_the_objects_fewer_than_n_live_devices_hold() {    let db = file();    let one = object();    let two = other_object();    record_holding(&db, WORKSPACE, THIS_PHONE, &one, Tier::Original, 4_096, T0, &mut Ids, Held::Served).expect("a hold");    record_holding(        &db,        WORKSPACE,        THIS_PHONE,        &two,        Tier::Original,        8_192,        T0 + MINUTE,        &mut Ids,        Held::Served,    )    .expect("a hold");    a_peers_hold(&db, THE_MAC, &two, Tier::Original, "2026-09-16T08:00:00.000Z");    assert_eq!(        objects_with_fewer_than(&db, WORKSPACE, 2, Tier::Original).expect("reads"),        vec![one.clone()],        "one object is on one machine only"    );    // A tier is asked about on its own: the same object at a different tier is    // a different question, and phase 2 asks this one about originals.    assert!(        objects_with_fewer_than(&db, WORKSPACE, 2, Tier::Display)            .expect("reads")            .is_empty()    );    // Once the Mac holds it too, the replicator is done with it.    a_peers_hold(&db, THE_MAC, &one, Tier::Original, "2026-09-16T08:30:00.000Z");    assert!(objects_with_fewer_than(&db, WORKSPACE, 2, Tier::Original)        .expect("reads")        .is_empty());    // And an eviction puts it back on the list.    drop_holding(        &db,        WORKSPACE,        THIS_PHONE,        &one,        Tier::Original,        T0 + 2 * MINUTE,        &mut Ids,        Held::Served,    )    .expect("the eviction");    assert_eq!(        objects_with_fewer_than(&db, WORKSPACE, 2, Tier::Original).expect("reads"),        vec![one]    );}#[test]fn an_object_nobody_has_recorded_is_unknown_here_rather_than_unheld() {    // The honest limit, written as a test so nobody reads the query as "every    // original that needs a second copy". It answers over the rows the table    // HAS; an object with no holdings row cannot come back from it, and the    // caller that wants the full sweep drives it from the records themselves.    let db = file();    assert!(objects_with_fewer_than(&db, WORKSPACE, 2, Tier::Original)        .expect("reads")        .is_empty());}#[test]fn a_holder_carries_the_name_the_person_gave_the_device() {    let db = file();    let key = object();    record_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served).expect("a hold");    let holders = holders_of(&db, WORKSPACE, &key, Tier::Original).expect("reads");    assert_eq!(holders.len(), 1);    assert_eq!(holders[0].name, "The invented phone");    assert_eq!(holders[0].bytes, 4_096);    assert_eq!(        holders[0].verified_at.as_deref(),        Some("2026-09-16T09:00:00.000Z")    );}#[test]fn a_hold_naming_a_tier_the_file_does_not_know_is_refused_by_the_file_itself() {    // The `CHECK` is on the column rather than only in the enum, so a row that    // reached the file any other way still cannot carry a fourth tier.    let db = file();    assert!(db        .run(            "INSERT INTO cotton_media_holdings (id, workspace_id, object_key, device_id, tier, \             bytes, created_at, updated_at) VALUES ('hold:blur:x:y', ?, 'y', 'x', 'blur', 1, ?, ?)",            &[                text(WORKSPACE),                text("2026-09-16T09:00:00.000Z"),                text("2026-09-16T09:00:00.000Z"),            ],        )        .is_err());}/// RULE: The copy pass takes the newest objects first, by each object's first hold time, with the key as the tie-break.#[test]fn the_work_list_is_newest_first() {    // A picture taken this week is the one a person opens next and the one    // with no second copy anywhere yet. A media key is content-addressed, so    // key order alone would be effectively random.    let db = file();    let newer = other_object();    let older = object();    a_peers_hold(&db, THE_MAC, &older, Tier::Original, "2019-04-02T08:00:00.000Z");    a_peers_hold(&db, THE_MAC, &newer, Tier::Original, "2026-09-16T08:00:00.000Z");    assert_eq!(        objects_with_fewer_than(&db, WORKSPACE, 2, Tier::Original).expect("reads"),        vec![newer.clone(), older.clone()],        "the newer hold comes first whatever its key sorts as"    );    assert_eq!(        objects_held_elsewhere(&db, WORKSPACE, THIS_PHONE, Tier::Original)            .expect("reads")            .into_iter()            .map(|(key, _)| key)            .collect::<Vec<_>>(),        vec![newer, older],        "one order for what to copy"    );}#[test]fn a_standby_is_owed_every_object_another_live_device_holds_however_many_hold_it() {    // A standby Mac is a FULL copy, so "short of a second holder" is the wrong    // question for it: an object two machines already hold is still an object    // it must be able to serve alone. What it is NOT owed is an object only it    // holds (nobody to ask), one whose only other holder dropped it, or one    // held only by a revoked device, which may never answer again.    let db = file();    let shared = object();    let only_the_mac = other_object();    let only_here = format!("{WORKSPACE}/photos/{}.heic", "c".repeat(64));    let dropped_elsewhere = format!("{WORKSPACE}/photos/{}.heic", "d".repeat(64));    let only_revoked = format!("{WORKSPACE}/photos/{}.heic", "e".repeat(64));    let a_thumb_elsewhere = format!("{WORKSPACE}/photos/{}.t256.jpg", "f".repeat(64));    record_holding(&db, WORKSPACE, THIS_PHONE, &shared, Tier::Original, 4_096, T0, &mut Ids, Held::Served).expect("a hold");    a_peers_hold(&db, THE_MAC, &shared, Tier::Original, "2026-09-16T08:00:00.000Z");    a_peers_hold(&db, THE_MAC, &only_the_mac, Tier::Original, "2019-04-02T08:00:00.000Z");    record_holding(&db, WORKSPACE, THIS_PHONE, &only_here, Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("a hold");    a_peers_hold(&db, THE_MAC, &dropped_elsewhere, Tier::Original, "2026-09-16T08:00:00.000Z");    db.run(        "UPDATE cotton_media_holdings SET dropped_at = ? WHERE object_key = ?",        &[text("2026-09-16T08:30:00.000Z"), text(&dropped_elsewhere)],    )    .expect("the peer evicted it");    a_peers_hold(&db, AN_OLD_PHONE, &only_revoked, Tier::Original, "2026-09-16T08:00:00.000Z");    revoke(&db, AN_OLD_PHONE);    a_peers_hold(&db, THE_MAC, &a_thumb_elsewhere, Tier::Thumb, "2026-09-16T08:00:00.000Z");    assert_eq!(        objects_held_elsewhere(&db, WORKSPACE, THIS_PHONE, Tier::Original).expect("reads"),        vec![(shared, 4_194_304), (only_the_mac, 4_194_304)],        "newest first, with the weight a holder recorded, and only what a live device \         other than this one holds"    );    assert_eq!(        objects_held_elsewhere(&db, WORKSPACE, THIS_PHONE, Tier::Thumb).expect("reads"),        vec![(a_thumb_elsewhere, 4_194_304)],        "one tier at a time"    );}#[test]fn a_live_hold_is_a_point_read_and_a_dropped_one_is_not_live() {    let db = file();    let key = object();    assert!(!is_live_hold(&db, THIS_PHONE, &key, Tier::Original).expect("reads"));    record_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, 4_096, T0, &mut Ids, Held::Served).expect("a hold");    assert!(is_live_hold(&db, THIS_PHONE, &key, Tier::Original).expect("reads"));    assert!(        !is_live_hold(&db, THIS_PHONE, &key, Tier::Thumb).expect("reads"),        "one tier is not another"    );    assert!(        !is_live_hold(&db, THE_MAC, &key, Tier::Original).expect("reads"),        "and one device is not another"    );    drop_holding(&db, WORKSPACE, THIS_PHONE, &key, Tier::Original, T0 + MINUTE, &mut Ids, Held::Served).expect("dropped");    assert!(!is_live_hold(&db, THIS_PHONE, &key, Tier::Original).expect("reads"));}#[test]fn a_devices_own_live_holds_are_its_rows_that_are_not_dropped() {    let db = file();    let kept = object();    let dropped = other_object();    record_holding(&db, WORKSPACE, THIS_PHONE, &kept, Tier::Original, 4_096, T0, &mut Ids, Held::Served).expect("a hold");    record_holding(&db, WORKSPACE, THIS_PHONE, &dropped, Tier::Original, 4_096, T0, &mut Ids, Held::Served)        .expect("a hold");    drop_holding(&db, WORKSPACE, THIS_PHONE, &dropped, Tier::Original, T0 + MINUTE, &mut Ids, Held::Served)        .expect("dropped");    a_peers_hold(&db, THE_MAC, &kept, Tier::Thumb, "2026-09-16T08:00:00.000Z");    assert_eq!(        live_holds_of(&db, WORKSPACE, THIS_PHONE).expect("reads"),        vec![(kept, Tier::Original)],        "not the dropped one, and never another device's"    );}/// RULE: A device row whose revoked_at is set to anything, the empty string included, is revoked for the hold writers exactly as it is for every reader.#[test]fn a_blank_revocation_is_a_revocation_for_writers_and_readers_alike() {    let db = file();    let key = object();    a_peers_hold(&db, AN_OLD_PHONE, &key, Tier::Original, "2026-09-16T08:00:00.000Z");    db.run(        "UPDATE cotton_devices SET revoked_at = '' WHERE device_id = ?",        &[text(AN_OLD_PHONE)],    )    .expect("a blank revocation");    assert_eq!(        device_standing(&db, WORKSPACE, AN_OLD_PHONE).expect("reads"),        DeviceStanding::Revoked,        "one answer to \"is this device revoked\""    );    assert!(        holders_of(&db, WORKSPACE, &key, Tier::Original).expect("reads").is_empty(),        "and the readers agree"    );    assert!(record_holding(&db, WORKSPACE, AN_OLD_PHONE, &key, Tier::Original, 1, T0, &mut Ids, Held::Served).is_err());}/// RULE: Retiring a file's author-id holds takes at most the batch asked for per call, and the next call takes the rest.#[test]fn a_retirement_takes_a_bounded_batch_and_the_next_call_the_rest() {    let db = file();    for letter in ['a', 'b', 'c'] {        let key = format!("{WORKSPACE}/photos/{}.heic", letter.to_string().repeat(64));        a_peers_hold(&db, THIS_FILE, &key, Tier::Original, "2026-09-10T08:00:00.000Z");    }    let later = T0 + 180 * MINUTE;    assert_eq!(retire_author_holdings(&db, WORKSPACE, 2, later, &mut Ids, Held::Served).expect("a batch").len(), 2);    assert_eq!(retire_author_holdings(&db, WORKSPACE, 2, later + 1, &mut Ids, Held::Served).expect("the rest").len(), 1);    assert!(retire_author_holdings(&db, WORKSPACE, 2, later + 2, &mut Ids, Held::Served).expect("level").is_empty());}/// RULE: A restated hold keeps the instant its object was first held; a hold recorded fresh takes now.#[test]fn a_restated_hold_keeps_its_first_held_instant_and_a_fresh_one_takes_now() {    let db = file();    restate_holding(&db, WORKSPACE, THIS_PHONE, &object(), Tier::Original, 1, "2019-04-02T08:00:00.000Z", T0, &mut Ids, Held::Served)        .expect("restated");    record_holding(&db, WORKSPACE, THIS_PHONE, &other_object(), Tier::Original, 1, T0, &mut Ids, Held::Served).expect("new");    let first = |key: &str| {        db.get(            "SELECT created_at FROM cotton_media_holdings WHERE id = ?",            &[text(&holding_id(THIS_PHONE, key, Tier::Original))],        )        .expect("reads")        .and_then(|row| row.text("created_at").map(str::to_string))    };    assert_eq!(first(&object()).as_deref(), Some("2019-04-02T08:00:00.000Z"));    assert_eq!(first(&other_object()).as_deref(), Some("2026-09-16T09:00:00.000Z"));}/// `n` holdings of `device_id` at every tier in turn, `dropped` or live —/// written raw, as a bulk fixture: what is under test is the read.fn bulk_holds(db: &Driver, device_id: &str, prefix: &str, n: i64, dropped: bool) {    db.run(        "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?3)         INSERT INTO cotton_media_holdings (id, workspace_id, object_key, device_id, tier, bytes, dropped_at, created_at, updated_at)         SELECT ?2 || '-' || i, ?1, 'photos/' || ?2 || '/' || printf('%064d', i) || '.heic', ?4,                CASE i % 3 WHEN 0 THEN 'original' WHEN 1 THEN 'display' ELSE 'thumb' END,                4194304, ?5, printf('2026-09-%02dT08:00:00.000Z', 1 + i % 28), '2026-10-12T00:00:00.000Z'         FROM n",        &[            text(WORKSPACE),            text(prefix),            rusqlite::types::Value::Integer(n),            text(device_id),            if dropped { text("2026-10-01T00:00:00.000Z") } else { rusqlite::types::Value::Null },        ],    )    .expect("the bulk holds");}/// RULE: What a standby asks the holdings ledger grows with the live holds, never with the ledger: a dropped hold is never read, and the read is answered from `idx_cotton_media_holdings_live` alone, never a holding's row.////// The owner's serving Mac, 12 Oct 2026 (0.29.35): `a hold took 6.1 s — nothing/// that named itself; 2,534,989 steps … SELECT h.object_key, MAX(h.bytes) FROM/// cotton_media_holdings h JOIN cotton_devices d …` — every one of 94k holdings/// walked once per tier, 68k of them dropped, to find ~10k live ones.#[test]fn a_standbys_read_of_the_ledger_costs_the_live_holds_never_the_dropped_ones() {    let db = file();    revoke(&db, AN_OLD_PHONE);    let read = |db: &Driver| {        let before = db.steps();        let mut found = 0;        for tier in [Tier::Original, Tier::Display, Tier::Thumb] {            found += objects_held_elsewhere(db, WORKSPACE, THIS_PHONE, tier).expect("reads").len();        }        (found, db.steps() - before)    };    bulk_holds(&db, THE_MAC, "live", 3_000, false);    let (alone, alone_steps) = read(&db);    assert_eq!(alone, 3_000);    // 500k holdings in all: what a long-lived household's ledger becomes.    bulk_holds(&db, THE_MAC, "gone", 440_000, true);    bulk_holds(&db, AN_OLD_PHONE, "revoked", 30_000, false);    bulk_holds(&db, AN_OLD_PHONE, "revoked-gone", 7_000, true);    bulk_holds(&db, THIS_PHONE, "mine", 20_000, false);    let (found, steps) = read(&db);    assert_eq!(found, 3_000, "only the live holds of another live device are owed");    assert!(        steps <= alone_steps * 30,        "read {steps} steps among 500,000 holdings, {alone_steps} among 3,000 live ones alone"    );    let plan: Vec<String> = db        .all(            &format!(                "EXPLAIN QUERY PLAN SELECT h.object_key AS object_key, MAX(h.bytes) AS bytes \                 {LIVE_HOLDINGS} AND h.workspace_id = ? AND h.tier = ? AND h.device_id <> ? \                 GROUP BY h.object_key {WHAT_TO_COPY_FIRST}"            ),            &[text(WORKSPACE), text("original"), text(THIS_PHONE)],        )        .expect("plans")        .iter()        .filter_map(|row| row.text("detail").map(str::to_string))        .collect();    assert!(        plan.iter().any(|step| step.contains("COVERING INDEX idx_cotton_media_holdings_live")),        "{plan:?}"    );}