Cotton code
750 lines · 25.2 KB · RustRaw
//! The budget pass, against a real replica and a fake unlink.//!//! Every fixture is synthetic and the clock is fixed//! ([nothing-real-ever-goes-in-cotton-s-public-tree]): no file is written, no//! file is deleted, and what this device "holds" is what its own ledger rows//! say it weighs — which is exactly what the pass measures.//!//! **Every row weighs one gibibyte**, so a budget is a COUNT of files and an//! assertion reads as one: four rows against the two-gigabyte choice is two//! files over.use std::sync::{Arc, Mutex};use cotton_store::media_holdings::{holding_id, record_holding, Tier};use rusqlite::types::Value as SqlValue;use super::*;use crate::seams::FixedClock;use crate::test_support::{open_test_replica, WORKSPACE};/// This phone, by its DEVICE KEY — 43 synthetic characters.const THIS_PHONES_KEY: &str = "PhoneKey___________________________________";const THE_MAC: &str = "device:01J00000000000000000000MAC";const A_REVOKED_PHONE: &str = "device:01J0000000000000000000OLD";/// What one fixture row weighs. See the module header.const ONE: i64 = 1024 * 1024 * 1024;fn key(letter: char) -> String {    format!("{WORKSPACE}/photos/{}.heic", letter.to_string().repeat(64))}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn approve(db: &cotton_store::driver::Driver, device_id: &str) {    approve_in(db, WORKSPACE, device_id);}fn approve_in(db: &cotton_store::driver::Driver, workspace: &str, device_id: &str) {    db.run(        "INSERT OR IGNORE INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \         approved_by_device, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",        &[            text(&format!("dev:{device_id}")),            text(workspace),            text(device_id),            text("An invented device"),            text("2026-09-08T09:00:00.000Z"),            text(device_id),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),        ],    )    .expect("the device row");}/// Somebody else's hold, written straight in — the way a peer's op folds.fn a_peers_hold(db: &cotton_store::driver::Driver, device_id: &str, object_key: &str) {    a_peers_hold_in(db, WORKSPACE, device_id, object_key);}fn a_peers_hold_in(    db: &cotton_store::driver::Driver,    workspace: &str,    device_id: &str,    object_key: &str,) {    approve_in(db, workspace, device_id);    db.run(        "INSERT OR REPLACE INTO cotton_media_holdings (id, workspace_id, object_key, device_id, \         tier, bytes, verified_at, created_at, updated_at, _hlc) \         VALUES (?,?,?,?,'original',?,?,?,?,?)",        &[            text(&holding_id(device_id, object_key, Tier::Original)),            text(workspace),            text(object_key),            text(device_id),            SqlValue::Integer(ONE),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),            text(&format!("1789549200000:0001:{device_id}")),        ],    )    .expect("the peer's hold");    cotton_tools::test_fixtures::reconcile(&db, "cotton_media_holdings");}/// A fake unlink: deletions are remembered rather than performed, and the/// filesystem can be made to refuse.#[derive(Debug, Default)]struct FakeDisk {    deleted: Mutex<Vec<String>>,    refuse: Mutex<Option<String>>,}impl FakeDisk {    fn deleted(&self) -> Vec<String> {        self.deleted.lock().expect("the log").clone()    }}impl MediaEvictDeps for FakeDisk {    fn remove_file(&self, path: &std::path::Path) -> std::io::Result<()> {        if let Some(reason) = self.refuse.lock().expect("the switch").clone() {            return Err(std::io::Error::other(reason));        }        self.deleted            .lock()            .expect("the log")            .push(path.to_string_lossy().to_string());        Ok(())    }}struct Bench {    dir: tempfile::TempDir,    layout: crate::Layout,    replica: Arc<Mutex<crate::Replica>>,    device_id: String,    clock: FixedClock,}fn bench() -> Bench {    let (dir, layout, replica) = open_test_replica();    // THIS PHONE'S DEVICE KEY — the id its holds name it by, approved in the    // file — never the replica's author id, which is no device row.    let device_id = THIS_PHONES_KEY.to_string();    approve(&replica.driver, &device_id);    Bench {        dir,        layout,        replica: Arc::new(Mutex::new(replica)),        device_id,        clock: FixedClock::default_start(),    }}/// One `_media` row this device holds a file for.////// `tier` defaults to `original`, which is what a fetched picture's row says —/// a row with NO tier is not an original and is never a candidate, which/// `a_row_that_names_no_rendition_is_never_taken` is about.struct Held<'a> {    key: &'a str,    tier: Option<&'a str>,    pinned: bool,    captured_here: bool,    last_viewed_at: Option<&'a str>,}impl Default for Held<'_> {    fn default() -> Held<'static> {        Held {            key: "",            tier: Some("original"),            pinned: false,            captured_here: false,            last_viewed_at: None,        }    }}impl Bench {    fn with_file<T>(&self, f: impl FnOnce(&cotton_store::driver::Driver) -> T) -> T {        let held = self.replica.lock().expect("the replica");        f(&held.driver)    }    /// File a row AND record this device's own hold of it, which is what a    /// fetched original looks like.    fn hold(&self, row: &Held<'_>) {        let held = self.replica.lock().expect("the replica");        hold_in(&held.driver, self.dir.path(), WORKSPACE, &self.device_id, row);    }}/// [`Bench::hold`], in the file of whichever database `workspace` names.fn hold_in(    db: &cotton_store::driver::Driver,    dir: &std::path::Path,    workspace: &str,    device_id: &str,    row: &Held<'_>,) {    // A REAL file, a few bytes long: the pass takes this device's hold    // off anything whose file is not there, so a row naming a path to    // nothing would be a hold the pass rightly drops.    let path = dir.join(row.key.replace('/', "_"));    std::fs::write(&path, b"invented").expect("the file");    db.run(        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, \         local_path, state, attempts, created_at, updated_at, tier, pinned, \         last_viewed_at, captured_here) VALUES (?,?,?,?,?,?,'synced',0,?,?,?,?,?,?)",        &[            text(row.key),            text(workspace),            text(&"f".repeat(64)),            text("image/heic"),            SqlValue::Integer(ONE),            text(&path.display().to_string()),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),            row.tier.map_or(SqlValue::Null, text),            SqlValue::Integer(i64::from(row.pinned)),            row.last_viewed_at.map_or(SqlValue::Null, text),            SqlValue::Integer(i64::from(row.captured_here)),        ],    )    .expect("the ledger row");    record_holding(        db,        workspace,        device_id,        row.key,        Tier::Original,        ONE,        1_789_200_000_000,        &mut crate::test_support::fresh_ids(),        cotton_store::mint::Held::Replica,    )    .expect("this device's own hold");}impl Bench {    /// Say the Mac holds these too, which is what unlocks the fence.    fn also_on_the_mac(&self, keys: &[&String]) {        self.with_file(|db| {            for object in keys {                a_peers_hold(db, THE_MAC, object);            }        });    }    fn run(&self, disk: &Arc<FakeDisk>, budget: u64) -> EvictPass {        self.run_beside(disk, budget, None)    }    /// [`Self::run`], on a device that holds other databases too.    fn run_beside(        &self,        disk: &Arc<FakeDisk>,        budget: u64,        others: Option<OtherReplicas>,    ) -> EvictPass {        set_budget(&self.layout, budget).expect("the budget");        let sweep = EvictSweep {            deps: Arc::clone(disk) as Arc<dyn MediaEvictDeps>,            layout: self.layout.clone(),            device_key: crate::identity::DeviceKey::fixed(Some(self.device_id.clone())),            random: Arc::new(crate::seams::SeededRandom::default()),            others,        };        evict_pass(&self.replica, &sweep, &self.clock)    }    fn local_path(&self, key: &str) -> Option<String> {        self.with_file(|db| {            cotton_store::media_ledger::media_by_key(db, key)                .expect("the read")                .expect("a row")                .local_path        })    }    fn still_a_holder(&self, key: &str) -> bool {        self.with_file(|db| {            cotton_store::media_holdings::holders_of(db, WORKSPACE, key, Tier::Original)                .expect("the holders")                .iter()                .any(|holder| holder.device_id == self.device_id)        })    }}// ─────────────────────────────────────────────────────────────────────────────#[test]fn nothing_happens_while_this_device_is_inside_its_budget() {    let bench = bench();    let object = key('a');    bench.hold(&Held {        key: &object,        ..Held::default()    });    bench.also_on_the_mac(&[&object]);    // One gibibyte against the two-gigabyte choice. Everything else about this    // row says it could go; the budget says it does not have to.    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 0);    assert_eq!(pass.last_copy, 0, "the fence was never even asked");    assert!(!pass.over_budget);    assert_eq!(pass.media_bytes, GIB);    assert!(disk.deleted().is_empty());}#[test]fn a_photo_this_phone_captured_is_never_evicted() {    let bench = bench();    // `mine` sorts FIRST — key 'a', never viewed — so if a capture were a    // candidate it is the one that would go. It is not, so 'b' goes instead.    let mine = key('a');    let theirs = key('b');    let also_theirs = key('c');    bench.hold(&Held {        key: &mine,        captured_here: true,        ..Held::default()    });    for object in [&theirs, &also_theirs] {        bench.hold(&Held {            key: object,            ..Held::default()        });    }    // The whole household holds all three, so the fence is not what stops this.    bench.also_on_the_mac(&[&mine, &theirs, &also_theirs]);    // Three gibibytes against two: one file has to go.    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 1);    assert!(        bench.local_path(&mine).is_some(),        "the photo this phone took stayed, although it was the least recently viewed"    );    assert!(bench.local_path(&theirs).is_none());    assert!(bench.local_path(&also_theirs).is_some());    assert!(bench.still_a_holder(&mine));}#[test]fn nothing_is_evicted_while_this_device_is_the_only_holder() {    let bench = bench();    let only_here = key('a');    let also_on_a_revoked_phone = key('b');    let third = key('c');    for object in [&only_here, &also_on_a_revoked_phone, &third] {        bench.hold(&Held {            key: object,            ..Held::default()        });    }    bench.with_file(|db| {        a_peers_hold(db, A_REVOKED_PHONE, &also_on_a_revoked_phone);        db.run(            "UPDATE cotton_devices SET revoked_at = ? WHERE device_id = ?",            &[text("2026-09-08T09:30:00.000Z"), text(A_REVOKED_PHONE)],        )        .expect("the revocation");        cotton_tools::test_fixtures::reconcile(&db, "cotton_devices");    });    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 0);    assert_eq!(        pass.last_copy, 3,        "a revoked phone is not a second holder, and neither is nobody"    );    assert!(pass.over_budget, "and the pass says so rather than pretending");    assert!(disk.deleted().is_empty());    for object in [&only_here, &also_on_a_revoked_phone, &third] {        assert!(bench.local_path(object).is_some());    }}#[test]fn least_recently_viewed_goes_first_and_pinned_never_goes() {    let bench = bench();    let never_viewed = key('a');    let viewed_long_ago = key('b');    let viewed_today = key('c');    let pinned = key('d');    bench.hold(&Held {        key: &viewed_today,        last_viewed_at: Some("2026-09-08T09:00:00.000Z"),        ..Held::default()    });    bench.hold(&Held {        key: &viewed_long_ago,        last_viewed_at: Some("2026-01-01T09:00:00.000Z"),        ..Held::default()    });    bench.hold(&Held {        key: &never_viewed,        ..Held::default()    });    bench.hold(&Held {        key: &pinned,        pinned: true,        ..Held::default()    });    bench.also_on_the_mac(&[&never_viewed, &viewed_long_ago, &viewed_today, &pinned]);    // Four gibibytes against two: exactly two files go.    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 2);    assert_eq!(disk.deleted().len(), 2);    assert!(        bench.local_path(&never_viewed).is_none(),        "the one nobody ever opened goes first"    );    assert!(        bench.local_path(&viewed_long_ago).is_none(),        "then the oldest view"    );    assert!(        bench.local_path(&viewed_today).is_some(),        "today's stays — the budget was met before it was reached"    );    assert!(        bench.local_path(&pinned).is_some(),        "and the pinned one never goes, although it was never viewed either"    );    assert!(        !bench.still_a_holder(&never_viewed),        "the hold was dropped too, or the household would go on believing this phone has it"    );    assert!(bench.still_a_holder(&viewed_today));}#[test]fn eviction_stops_the_moment_the_budget_is_met() {    let bench = bench();    let objects: Vec<String> = ('a'..='e').map(key).collect();    for (index, object) in objects.iter().enumerate() {        bench.hold(&Held {            key: object,            last_viewed_at: Some(&format!("2026-0{}-01T09:00:00.000Z", index + 1)),            ..Held::default()        });    }    bench.also_on_the_mac(&objects.iter().collect::<Vec<&String>>());    // Five gibibytes against two: three go, and the two most recently viewed    // stay although the fence would have allowed them.    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 3);    assert_eq!(pass.bytes, 3 * GIB);    assert!(!pass.over_budget);    assert_eq!(pass.media_bytes, 2 * GIB);    for object in objects.iter().take(3) {        assert!(bench.local_path(object).is_none(), "the three oldest views went");    }    for object in objects.iter().skip(3) {        assert!(bench.local_path(object).is_some(), "and the rest stayed");    }}#[test]fn thumbs_are_never_candidates_and_do_not_count() {    let bench = bench();    let originals: Vec<String> = ['a', 'b', 'c'].into_iter().map(key).collect();    let thumb = key('t');    for object in &originals {        bench.hold(&Held {            key: object,            ..Held::default()        });    }    bench.hold(&Held {        key: &thumb,        tier: Some("thumb"),        ..Held::default()    });    bench.also_on_the_mac(&[&originals[0], &originals[1], &originals[2], &thumb]);    // Three gibibytes of originals and one of thumbnails, against a    // two-gigabyte budget. ONE file goes. If the thumbnail counted the total    // would be four and TWO would go — which is the whole assertion.    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 1);    assert_eq!(        pass.media_bytes,        2 * GIB,        "the thumbnail's gibibyte was never in the total"    );    assert!(bench.local_path(&thumb).is_some(), "a thumbnail is never taken");    assert!(bench.local_path(&originals[0]).is_none());    assert!(bench.local_path(&originals[1]).is_some());}#[test]fn a_row_that_names_no_rendition_is_never_taken() {    let bench = bench();    // Every row written before schema v12, and every object with no tier    // ladder — a document, a meeting's audio, a film's poster. `None` is not    // `Original`, and reading it as one would start the first pass on the    // oldest rows in the file.    let no_tier = key('a');    bench.hold(&Held {        key: &no_tier,        tier: None,        ..Held::default()    });    let plain = key('b');    let third = key('c');    for object in [&plain, &third] {        bench.hold(&Held {            key: object,            ..Held::default()        });    }    bench.also_on_the_mac(&[&no_tier, &plain, &third]);    // Only TWO gibibytes are in the budget's total at all, which is the    // budget — so nothing is over and nothing goes.    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 0);    assert_eq!(        pass.media_bytes,        2 * GIB,        "the untiered row's gibibyte was never in the total"    );    assert!(bench.local_path(&no_tier).is_some());}#[test]fn a_rendition_this_build_cannot_name_is_never_taken() {    let bench = bench();    // A future version's tier, arriving on a device running this one. The row    // is not a candidate — a file this build cannot name is a file it must not    // delete — so the pass stays over budget rather than guessing.    let unknown = key('a');    bench.hold(&Held {        key: &unknown,        tier: Some("d3200"),        ..Held::default()    });    let plain = key('b');    bench.hold(&Held {        key: &plain,        ..Held::default()    });    bench.also_on_the_mac(&[&unknown, &plain]);    let disk = Arc::new(FakeDisk::default());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 0);    assert_eq!(        pass.media_bytes,        GIB,        "only the rendition this build can name is in the total"    );    assert!(bench.local_path(&unknown).is_some());    // Push it over with rows this build DOES understand, and it is still only    // those that go: the unnameable one is not a candidate at any budget.    for letter in ['c', 'd'] {        let more = key(letter);        bench.hold(&Held {            key: &more,            ..Held::default()        });        bench.also_on_the_mac(&[&more]);    }    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 1, "three nameable gibibytes against two");    assert!(bench.local_path(&unknown).is_some());    assert!(bench.local_path(&plain).is_none(), "the earliest candidate went");}#[test]fn a_file_the_disk_will_not_take_keeps_its_row_and_ends_the_pass() {    let bench = bench();    let objects: Vec<String> = ['a', 'b', 'c'].into_iter().map(key).collect();    for object in &objects {        bench.hold(&Held {            key: object,            ..Held::default()        });    }    bench.also_on_the_mac(&[&objects[0], &objects[1], &objects[2]]);    let disk = Arc::new(FakeDisk::default());    *disk.refuse.lock().expect("the switch") = Some("the file is busy".to_string());    let pass = bench.run(&disk, 2 * GIB);    assert_eq!(pass.removed, 0);    assert!(pass.over_budget);    assert!(pass.last_error.is_some());    for object in &objects {        assert!(            bench.local_path(object).is_some(),            "the file is still there, so the row still names it"        );        assert!(bench.still_a_holder(object));    }}#[test]fn the_budget_is_one_of_the_offered_choices_or_it_is_refused() {    let (dir, layout, _replica) = open_test_replica();    assert_eq!(read_budget(&layout), MEDIA_BUDGET_DEFAULT_BYTES);    assert_eq!(set_budget(&layout, 8 * GIB).expect("a choice"), 8 * GIB);    assert_eq!(read_budget(&layout), 8 * GIB);    let refusal = set_budget(&layout, 3 * GIB).expect_err("not a choice");    assert!(refusal.contains("2, 4, 8, 16"), "{refusal}");    assert_eq!(        read_budget(&layout),        8 * GIB,        "and a refused write leaves the stored value alone"    );    // ZERO is the one a clamp would have quietly accepted, and it is the one    // that would make the phone delete everything it is allowed to.    assert!(set_budget(&layout, 0).is_err());    // A file somebody edited by hand into a value that is not a choice reads as    // the default rather than as itself — the same refusal, one layer out.    std::fs::write(        layout.media_budget_json(),        serde_json::to_string(&StoredBudget { bytes: 0 }).expect("the json"),    )    .expect("the budget file");    assert_eq!(read_budget(&layout), MEDIA_BUDGET_DEFAULT_BYTES);    drop(dir);}/// RULE: A device's own hold on bytes it no longer has, such as one that came back with a restored copy of the database, is dropped, so no other machine counts it as a copy.#[test]fn a_hold_whose_file_is_not_on_this_device_is_dropped_and_nobody_counts_it() {    // A replica re-bootstrap: the snapshot brings this phone's key-named hold    // back, and `claim_snapshot` cleared `_media`, so there is no file.    let bench = bench();    let object = key('r');    bench.with_file(|db| {        record_holding(            db,            WORKSPACE,            &bench.device_id,            &object,            Tier::Original,            ONE,            1_789_200_000_000,            &mut crate::test_support::fresh_ids(),            cotton_store::mint::Held::Replica,        )            .expect("the hold the snapshot carried");    });    bench.also_on_the_mac(&[&object]);    assert!(bench.still_a_holder(&object));    let disk = Arc::new(FakeDisk::default());    bench.run(&disk, 2 * GIB);    assert!(!bench.still_a_holder(&object), "the phone is not a copy of it");    let holders: Vec<String> = bench.with_file(|db| {        cotton_store::media_holdings::holders_of(db, WORKSPACE, &object, Tier::Original)            .expect("the holders")            .into_iter()            .map(|holder| holder.device_id)            .collect()    });    assert_eq!(holders, vec![THE_MAC.to_string()], "the Mac is the one holder left");    assert!(disk.deleted().is_empty(), "and nothing was deleted to say so");}/// A second database this phone holds beside its own — a project's.const A_PROJECT: &str = "66666666-6666-4666-8666-666666666666";/// RULE: The media budget is one number per device — measured over every database's replica it holds and taken least recently viewed first across all of them.#[test]fn budget_spans_every_replica() {    let bench = bench();    let project = crate::test_support::open_replica_for(&bench.layout, bench.dir.path(), A_PROJECT);    approve_in(&project.driver, A_PROJECT, &bench.device_id);    let project = Arc::new(Mutex::new(project));    let in_project = |letter: char| format!("{A_PROJECT}/photos/{}.heic", letter.to_string().repeat(64));    // Two gibibytes in each database: each file alone is inside the budget,    // and the device is two files over it.    let (kept_mine, old_mine) = (key('a'), key('b'));    let (kept_theirs, unseen_theirs) = (in_project('c'), in_project('d'));    bench.hold(&Held {        key: &kept_mine,        last_viewed_at: Some("2026-09-03T09:00:00.000Z"),        ..Held::default()    });    bench.hold(&Held {        key: &old_mine,        last_viewed_at: Some("2026-09-01T09:00:00.000Z"),        ..Held::default()    });    bench.also_on_the_mac(&[&kept_mine, &old_mine]);    {        let held = project.lock().expect("the project");        hold_in(&held.driver, bench.dir.path(), A_PROJECT, &bench.device_id, &Held {            key: &kept_theirs,            last_viewed_at: Some("2026-09-02T09:00:00.000Z"),            ..Held::default()        });        hold_in(&held.driver, bench.dir.path(), A_PROJECT, &bench.device_id, &Held {            key: &unseen_theirs,            ..Held::default()        });        for object in [&kept_theirs, &unseen_theirs] {            a_peers_hold_in(&held.driver, A_PROJECT, THE_MAC, object);        }    }    let disk = Arc::new(FakeDisk::default());    let beside = Arc::clone(&project);    let pass = bench.run_beside(        &disk,        2 * GIB,        Some(Arc::new(move || vec![Arc::clone(&beside)])),    );    assert_eq!(pass.removed, 2, "{pass:?}");    assert_eq!(pass.media_bytes, 2 * GIB, "the device is level with its one budget");    assert!(!pass.over_budget);    // Never viewed goes first, then the oldest view — whichever file each is in.    let held = project.lock().expect("the project");    let path_of = |db: &cotton_store::driver::Driver, key: &str| {        cotton_store::media_ledger::media_by_key(db, key)            .expect("the read")            .expect("a row")            .local_path    };    assert!(path_of(&held.driver, &unseen_theirs).is_none());    assert!(bench.local_path(&old_mine).is_none());    assert!(path_of(&held.driver, &kept_theirs).is_some());    assert!(bench.local_path(&kept_mine).is_some());    // The dropped hold is written in the file the object's row is in.    assert!(        !cotton_store::media_holdings::holders_of(&held.driver, A_PROJECT, &unseen_theirs, Tier::Original)            .expect("the holders")            .iter()            .any(|holder| holder.device_id == bench.device_id)    );}