Cotton code
441 lines · 19.0 KB · RustRaw
use super::*;/// RULE: an original must fit wholly within Space for kept things; opened bytes are not charged to this budget.#[test]fn a_rule_original_never_crosses_the_cap() {    assert!(allowed(Some(100), 90, 10));    assert!(!allowed(Some(100), 90, 11));    assert!(!allowed(Some(100), 100, 1));    assert!(!allowed(Some(100), u64::MAX, 1));    assert!(allowed(None, 100, 500));}use crate::seams::{FixedClock, SeededRandom};use crate::test_support::{open_test_replica, WORKSPACE};#[derive(Debug, Default)]struct Bytes {    asked: Mutex<Vec<String>>,    actual: usize,    free: Option<u64>,}impl MediaHydrateDeps for Bytes {    fn fetch_object_to(        &self,        _: &str,        key: &str,        dest: &Path,    ) -> Result<(), crate::transport::ServerRefusal> {        self.asked.lock().unwrap().push(key.into());        std::fs::write(            dest,            vec![key.rsplit('/').next().unwrap().as_bytes()[0]; self.actual],        )        .unwrap();        Ok(())    }    fn free_bytes(&self, _: &Path) -> Option<u64> {        Some(            self.free                .unwrap_or(super::super::hydrate::HYDRATE_DISK_FLOOR_BYTES * 2),        )    }}fn setup() -> (    tempfile::TempDir,    Arc<Mutex<Replica>>,    KeepFetchSweep,    Arc<Bytes>,) {    let (dir, layout, replica) = open_test_replica();    let db = &replica.driver;    db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,platform,approved_at,approved_by_device,created_at,updated_at,kept_space_bytes) VALUES ('phone',?,'phone','Synthetic phone','ios','2026-09-08','phone','2026-09-08','2026-09-08',10)",&[text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_storage_rules (id,workspace_id,device_id,tool,keep_rule,created_at,updated_at) VALUES ('photos',?,'phone','photo','only_opened','2026-09-08','2026-09-08')",&[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',?,'trip','Synthetic album','2026-09-01','2026-09-08','2026-09-08','2026-09-08')",&[text(WORKSPACE)]).unwrap();    db.run("INSERT INTO cotton_device_keep (id,workspace_id,device_id,kind,target,rule,created_at,updated_at) VALUES ('keep',?,'phone','group','album','always','2026-09-08','2026-09-08')",&[text(WORKSPACE)]).unwrap();    for (letter, at) in [        ('a', "2026-09-01"),        ('b', "2026-09-02"),        ('c', "2026-09-03"),    ] {        let sha = letter.to_string().repeat(64);        let id = format!("photo:{sha}");        let key = format!("{WORKSPACE}/photos/{sha}.heic");        db.run("INSERT INTO cotton_photos (id,workspace_id,key,sha256,content_type,size_bytes,taken_at,created_at,updated_at) VALUES (?,?,?,?,'image/heic',5,?,?,?)",&[text(&id),text(WORKSPACE),text(&key),text(&sha),text(at),text(at),text(at)]).unwrap();        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 (?,?,'album','photo',?,'derived','2026-09-08','2026-09-08','2026-09-08')",&[text(&format!("item:{letter}")),text(WORKSPACE),text(&id)]).unwrap();    }    cotton_tools::test_fixtures::reconcile(db, "cotton_photos");    let bytes = Arc::new(Bytes {        actual: 5,        ..Bytes::default()    });    let sweep = KeepFetchSweep {        deps: bytes.clone(),        layout,        device_key: crate::identity::DeviceKey::fixed(Some("phone".into())),        random: Arc::new(SeededRandom::new(42)),        wanted_bytes: Default::default(),    };    (dir, Arc::new(Mutex::new(replica)), sweep, bytes)}/// RULE: keeping an album fetches its missing originals newest first up to the cap, independently of keeper replication counts, and stopping keeping cancels that queue./// RULE: keep fetch is a phone rule — on a Mac neither the drain's pass nor/// the status read builds the queue, because building it scans the whole file/// and on a standby's copy of the owner's database that scan held every read/// connection until the app could not quit (standbyhang, 12 Oct 2026).#[test]fn a_mac_builds_no_keep_queue() {    let (_dir, replica, sweep, bytes) = setup();    replica.lock().unwrap().driver.run("UPDATE cotton_devices SET platform='macos' WHERE device_id='phone'", &[]).unwrap();    let clock = FixedClock::default_start();    assert!(over(&[replica.clone()], &sweep, &clock).is_empty());    assert!(bytes.asked.lock().unwrap().is_empty());    let r = replica.lock().unwrap();    let read = status(&r.driver, WORKSPACE, "phone", 0).unwrap();    assert!(read.coming.is_empty() && read.smallest_missing.is_none());}#[test]fn a_kept_album_arrives_within_the_cap_and_unkeep_stops_it() {    let (_dir, replica, sweep, bytes) = setup();    let clock = FixedClock::default_start();    let report = pass(&replica, &sweep, &clock, 0);    assert_eq!(report.pulled, 2);    assert_eq!(report.pending, 1);    let asked = bytes.asked.lock().unwrap().clone();    assert!(asked[0].contains(&"c".repeat(64)));    assert!(asked[1].contains(&"b".repeat(64)));    let r = replica.lock().unwrap();    assert_eq!(charged(&r.driver, WORKSPACE).unwrap(), 10);    let state = status(        &r.driver,        WORKSPACE,        "phone",        clock.now().timestamp_millis(),    )    .unwrap();    assert!(state.full);    assert_eq!(state.coming[0].held_count, 2);    assert_eq!(state.coming[0].total_count, 3);    r.driver        .run("DELETE FROM cotton_device_keep WHERE id='keep'", &[])        .unwrap();    assert!(wanted(        &r.driver,        WORKSPACE,        "phone",        clock.now().timestamp_millis()    )    .unwrap()    .is_empty());    drop(r);    assert_eq!(pass(&replica, &sweep, &clock, 0).pulled, 0);    assert_eq!(bytes.asked.lock().unwrap().len(), 2);}/// RULE: opening an original removes it from fetched-by-rule accounting; the owner may open more than their automatic download cap.#[test]fn opened_bytes_do_not_count_against_the_cap() {    let (_dir, replica, sweep, _bytes) = setup();    let clock = FixedClock::default_start();    assert_eq!(pass(&replica, &sweep, &clock, 0).pulled, 2);    let r = replica.lock().unwrap();    let key = r        .driver        .get("SELECT key FROM _media LIMIT 1", &[])        .unwrap()        .unwrap()        .text("key")        .unwrap()        .to_string();    cotton_store::media_ledger::mark_viewed(&r.driver, &key, "2026-09-08T09:00:00.000Z").unwrap();    assert_eq!(charged(&r.driver, WORKSPACE).unwrap(), 5);    drop(r);    assert_eq!(pass(&replica, &sweep, &clock, 0).pulled, 1);    assert_eq!(        charged(&replica.lock().unwrap().driver, WORKSPACE).unwrap(),        10    );}/// RULE: a lying original size cannot cross the cap; actual arrival bytes are checked before a file enters the phone's store.#[test]fn an_oversized_arrival_is_discarded() {    let (_dir, replica, mut sweep, _bytes) = setup();    sweep.deps = Arc::new(Bytes {        actual: 11,        ..Bytes::default()    });    assert_eq!(        pass(&replica, &sweep, &FixedClock::default_start(), 0).pulled,        0    );    assert_eq!(        charged(&replica.lock().unwrap().driver, WORKSPACE).unwrap(),        0    );}#[derive(Debug)]struct ChangeDuringFetch {    replica: Arc<Mutex<Replica>>,    cap_change: bool,}impl MediaHydrateDeps for ChangeDuringFetch {    fn fetch_object_to(        &self,        _: &str,        _: &str,        dest: &Path,    ) -> Result<(), crate::transport::ServerRefusal> {        std::fs::write(dest, b"hello").unwrap();        let r = self.replica.lock().unwrap();        if self.cap_change {            r.driver                .run(                    "UPDATE cotton_devices SET kept_space_bytes=0 WHERE device_id='phone'",                    &[],                )                .unwrap();        } else {            r.driver.run("DELETE FROM cotton_device_keep", &[]).unwrap();        }        Ok(())    }    fn free_bytes(&self, _: &Path) -> Option<u64> {        Some(super::super::hydrate::HYDRATE_DISK_FLOOR_BYTES * 2)    }}/// RULE: a cap reduction or unkeep during a download takes effect before its arrival is retained, so an in-flight queue cannot overrule a person's new choice.#[test]fn choices_changed_during_download_are_checked_before_arrival() {    for cap_change in [false, true] {        let (_dir, replica, mut sweep, _bytes) = setup();        sweep.deps = Arc::new(ChangeDuringFetch {            replica: replica.clone(),            cap_change,        });        assert_eq!(            pass(&replica, &sweep, &FixedClock::default_start(), 0).pulled,            0        );        assert_eq!(            charged(&replica.lock().unwrap().driver, WORKSPACE).unwrap(),            0        );    }}/// RULE: one phone cap covers every database and the newest owed original wins across them, rather than giving each database another full allowance.#[test]fn all_database_queues_share_the_phone_cap_and_newest_first_order() {    let (dir, replica, sweep, bytes) = setup();    let other_workspace = "synthetic-kept-project";    let other = crate::test_support::open_replica_for(&sweep.layout, dir.path(), other_workspace);    let db = &other.driver;    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-09-08','phone','2026-09-08','2026-09-08')",&[text(other_workspace)]).unwrap();    let sha = "d".repeat(64);    let key = format!("{other_workspace}/photos/{sha}.heic");    db.run("INSERT INTO cotton_photos (id,workspace_id,key,sha256,content_type,size_bytes,taken_at,created_at,updated_at) VALUES (?,?,?,?,'image/heic',5,'2026-09-04','2026-09-04','2026-09-04')",&[text(&format!("photo:{sha}")),text(other_workspace),text(&key),text(&sha)]).unwrap();    cotton_tools::test_fixtures::reconcile(db, "cotton_photos");    let other = Arc::new(Mutex::new(other));    let clock = FixedClock::default_start();    over(&[replica.clone(), other.clone()], &sweep, &clock);    let asked = bytes.asked.lock().unwrap().clone();    assert_eq!(asked.len(), 2);    assert_eq!(asked[0], key);    assert!(asked[1].contains(&"c".repeat(64)));    assert_eq!(        charged(&replica.lock().unwrap().driver, WORKSPACE).unwrap()            + charged(&other.lock().unwrap().driver, other_workspace).unwrap(),        10    );}/// RULE: a WhatsApp byte override fetches old WhatsApp media while Instagram keeps its existing horizon; source choices must never widen a neighbouring source's queue.#[test]fn whatsapp_fetches_everything_without_widening_instagram() {    let (_dir, replica, sweep, _bytes) = setup();    let r = replica.lock().unwrap();    let db = &r.driver;    db.run("INSERT INTO cotton_msg_threads (id,workspace_id,kind,title,created_at,updated_at) VALUES ('sources',?,'group','Synthetic sources','2026-01-01','2026-01-01')",&[text(WORKSPACE)]).unwrap();    for source in ["whatsapp", "instagram"] {        let key = format!("{WORKSPACE}/messages/sources/{source}.jpg");        db.run("INSERT INTO cotton_msg_messages (id,thread_id,workspace_id,direction,channel,origin,sent_at,created_at,media) VALUES (?,'sources',?,'in',?,'imported','2026-01-01','2026-01-01',?)",&[text(source),text(WORKSPACE),text(source),text(&serde_json::json!([{"key":key}]).to_string())]).unwrap();        db.run(            "INSERT INTO _media_key_names (key,tbl,row_id) VALUES (?,'cotton_msg_messages',?)",            &[text(&key), text(source)],        )        .unwrap();        db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?,?,?,'phone','original',5,'2026-01-01','2026-01-01')",&[text(source),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 ('wa',?,'phone','whatsapp','all','2026-09-08','2026-09-08')",&[text(WORKSPACE)]).unwrap();    let list = wanted(        db,        WORKSPACE,        "phone",        FixedClock::default_start().now().timestamp_millis(),    )    .unwrap();    assert!(list.iter().any(|w| w.key.ends_with("whatsapp.jpg")));    assert!(!list.iter().any(|w| w.key.ends_with("instagram.jpg")));    let rules = byte_rules(db, WORKSPACE, "phone").unwrap();    assert_eq!(        rules            .iter()            .find(|r| r.tool == "whatsapp")            .unwrap()            .keep_rule,        "all"    );    assert_eq!(        rules            .iter()            .find(|r| r.tool == "instagram")            .unwrap()            .keep_rule,        "recent_90_days"    );    drop(r);    let _ = sweep;}/// RULE: the Mac replicator's twenty-gigabyte reserve cannot block a phone that has room for its cap; rule downloads preserve a small database reserve and are bounded by the phone's actual free space.#[test]fn a_phone_with_one_gigabyte_free_fetches_within_its_cap() {    let (_dir, replica, mut sweep, _bytes) = setup();    sweep.deps = Arc::new(Bytes {        actual: 5,        free: Some(1_000_000_000),        ..Bytes::default()    });    assert_eq!(        pass(&replica, &sweep, &FixedClock::default_start(), 0).pulled,        2    );}/// RULE: no limit removes the owner's cap, never the space the phone's database needs; a rule sends no request when its original would consume that reserve.#[test]fn no_limit_does_not_consume_the_phone_database_reserve() {    let (_dir, replica, mut sweep, _bytes) = setup();    replica        .lock()        .unwrap()        .driver        .run(            "UPDATE cotton_devices SET kept_space_bytes=NULL WHERE device_id='phone'",            &[],        )        .unwrap();    let bytes = Arc::new(Bytes {        actual: 5,        free: Some(KEEP_FETCH_DISK_RESERVE_BYTES + 4),        ..Bytes::default()    });    sweep.deps = bytes.clone();    let report = pass(&replica, &sweep, &FixedClock::default_start(), 0);    assert!(report.floor);    assert_eq!(report.pulled, 0);    assert!(bytes.asked.lock().unwrap().is_empty());}/// RULE: keeping a record fetches its named originals beyond gallery tools, such as meeting audio; stopping the pin cancels that queue.#[test]fn a_kept_meeting_fetches_its_audio_and_unkeep_stops_it() {    let (_dir, replica, sweep, bytes) = setup();    let key = format!("{WORKSPACE}/meetings/meeting/full.m4a");    {        let r = replica.lock().unwrap();        let db = &r.driver;        db.run("DELETE FROM cotton_device_keep", &[]).unwrap();        db.run("INSERT INTO cotton_meetings (id,workspace_id,title,source,started_at,status_changed_at,created_at,updated_at) VALUES ('meeting',?,'Synthetic meeting','imported','2026-09-05','2026-09-05','2026-09-05','2026-09-05')",&[text(WORKSPACE)]).unwrap();        cotton_tools::test_fixtures::reconcile(db, "cotton_meetings");        db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?, ?,?,'phone','original',5,'2026-09-05','2026-09-05')",&[text(&cotton_store::media_holdings::holding_id("phone",&key,Tier::Original)),text(WORKSPACE),text(&key)]).unwrap();        db.run("INSERT INTO cotton_device_keep (id,workspace_id,device_id,kind,target,rule,created_at,updated_at) VALUES ('meeting-keep',?,'phone','record','cotton_meetings:meeting','always','2026-09-05','2026-09-05')",&[text(WORKSPACE)]).unwrap();    }    let report = pass(&replica, &sweep, &FixedClock::default_start(), 0);    assert_eq!(        report.pulled,        1,        "{report:?}; names: {:?}",        replica            .lock()            .unwrap()            .driver            .all(                "SELECT key,tbl,row_id FROM _media_key_names WHERE tbl='cotton_meetings'",                &[]            )            .unwrap()    );    assert_eq!(bytes.asked.lock().unwrap().as_slice(), &[key]);    replica        .lock()        .unwrap()        .driver        .run("DELETE FROM cotton_device_keep", &[])        .unwrap();    assert_eq!(        pass(&replica, &sweep, &FixedClock::default_start(), 0).pulled,        0    );}/// RULE: a failed local catalogue write must not leave unaccounted rule bytes on disk, or retries could exceed the phone's cap without its counter changing.#[test]fn a_catalogue_failure_keeps_no_unaccounted_original() {    let (_dir, replica, sweep, _bytes) = setup();    replica.lock().unwrap().driver.exec("CREATE TRIGGER refuse_rule_cache BEFORE INSERT ON _media BEGIN SELECT RAISE(ABORT,'synthetic catalogue refusal'); END").unwrap();    let report = pass(&replica, &sweep, &FixedClock::default_start(), 0);    assert_eq!(report.pulled, 0);    assert!(report.last_error.is_some());    assert_eq!(        charged(&replica.lock().unwrap().driver, WORKSPACE).unwrap(),        0    );    assert!(        std::fs::read_dir(sweep.layout.client_media_dir().join(WORKSPACE))            .unwrap()            .next()            .is_none()    );}/// RULE: An original the sweep streamed whole is never asked for again — it is held from the pass that landed it on, even when its ledger row was written under another database's id, and a second sweep started while one runs (a drain stopped and started again) does not walk the queue beside it (onetransport, 13 Oct 2026: whole originals were streamed again on later passes).#[test]fn an_original_streamed_whole_is_never_asked_for_again() {    let (_dir, replica, sweep, bytes) = setup();    let clock = FixedClock::default_start();    {        let r = replica.lock().unwrap();        r.driver.run("UPDATE cotton_devices SET kept_space_bytes=1000 WHERE device_id='phone'", &[]).unwrap();        // A ledger row for one key, written under another database's id        // (a row the file was handed with), and no bytes yet.        let key = format!("{WORKSPACE}/photos/{}.heic", "a".repeat(64));        r.driver.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,state,attempts,created_at,updated_at) VALUES (?,'another-database',?,'image/heic',5,'synced',0,'2026-09-08','2026-09-08')", &[text(&key), text(&"a".repeat(64))]).unwrap();    }    assert_eq!(pass(&replica, &sweep, &clock, 0).pulled, 3);    assert_eq!(bytes.asked.lock().unwrap().len(), 3);    for _ in 0..2 {        assert_eq!(pass(&replica, &sweep, &clock, 0).pulled, 0);    }    assert_eq!(bytes.asked.lock().unwrap().len(), 3, "nothing streamed whole is asked for again");}/// RULE: only the keep-fetch worker measures wanted media; its stored status follows landed originals and can be read while the catalogue is unavailable.#[test]fn the_worker_stores_status_and_remaining_bytes() {    let (_dir, replica, sweep, _bytes) = setup();    assert!(sweep.wanted_bytes.status(WORKSPACE).is_none());    over(&[replica.clone()], &sweep, &FixedClock::default_start());    let status = sweep.wanted_bytes.status(WORKSPACE).unwrap();    assert_eq!(sweep.wanted_bytes.of(WORKSPACE), Some(5));    assert_eq!(status.fetched_bytes, 10);    assert!(status.full);    assert_eq!(status.coming[0].held_count, 2);    replica.lock().unwrap().driver.exec("DROP TABLE cotton_photos").unwrap();    assert_eq!(sweep.wanted_bytes.status(WORKSPACE).unwrap().fetched_bytes, 10);}