//! This device's own holds, named by its device key, against a real replica. //! //! Every id, key and byte is synthetic and every instant explicit //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). use cotton_store::media_holdings::{holders_of, holding_id, is_live_hold, Tier}; use rusqlite::types::Value as SqlValue; use super::*; use crate::test_support::{open_test_replica, WORKSPACE}; /// This phone, by its DEVICE KEY — 43 synthetic characters. const THIS_PHONES_KEY: &str = "PhoneKey___________________________________"; /// 2026-09-16T09:00:00.000Z. const T0: i64 = 1_789_549_200_000; fn text(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } fn key(letter: char) -> String { format!("{WORKSPACE}/photos/{}.heic", letter.to_string().repeat(64)) } fn approve(db: &Driver, device_id: &str) { db.run( "INSERT 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 phone"), 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"); cotton_tools::test_fixtures::reconcile(&db, "cotton_devices"); } /// Op ids for a pass's writes, never one twice. fn ids() -> impl cotton_store::outbox::IdSource { crate::test_support::fresh_ids() } fn author(db: &Driver) -> String { cotton_store::meta::read_meta(db) .expect("meta") .expect("a row") .device_id } /// A hold this replica wrote under its AUTHOR id, the way every writer did /// before holdings named a machine by its key. fn an_author_hold(db: &Driver, object_key: &str) { let author = author(db); db.run( "INSERT INTO cotton_media_holdings (id, workspace_id, object_key, device_id, tier, \ bytes, verified_at, created_at, updated_at, _hlc) \ VALUES (?,?,?,?,'original',9,?,?,?,?)", &[ text(&holding_id(&author, object_key, Tier::Original)), text(WORKSPACE), text(object_key), text(&author), text("2026-09-08T09:00:00.000Z"), text("2026-09-08T09:00:00.000Z"), text("2026-09-08T09:00:00.000Z"), // Stamped before the retirement below, as an old write is. text(&format!("1788800000000:0001:{author}")), ], ) .expect("the author's hold"); cotton_tools::test_fixtures::reconcile(&db, "cotton_media_holdings"); } /// A `_media` row naming `path` as this device's copy of `object_key`. fn on_this_device(db: &Driver, object_key: &str, path: &std::path::Path) { db.run( "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \ state, attempts, created_at, updated_at) VALUES (?,?,?,?,?,?,'synced',0,?,?)", &[ text(object_key), text(WORKSPACE), text(&"f".repeat(64)), text("image/heic"), SqlValue::Integer(9), text(&path.display().to_string()), text("2026-09-08T09:00:00.000Z"), text("2026-09-08T09:00:00.000Z"), ], ) .expect("the ledger row"); } #[test] fn a_device_with_no_key_or_no_row_here_may_hold_nothing_yet() { let (_dir, _layout, replica) = open_test_replica(); let db = &replica.driver; assert!(holder_in(db, WORKSPACE, None).expect("reads").is_err()); let absent = holder_in(db, WORKSPACE, Some(THIS_PHONES_KEY)).expect("reads"); assert!( absent.as_ref().is_err_and(|why| why.contains("not reached")), "{absent:?}" ); approve(db, THIS_PHONES_KEY); assert_eq!( holder_in(db, WORKSPACE, Some(THIS_PHONES_KEY)).expect("reads"), Ok(THIS_PHONES_KEY.to_string()) ); } /// RULE: A reader may cache media but never publishes a holding, because a /// holding changes the shared redundancy state and is therefore a write. #[test] fn a_reader_never_becomes_a_media_holder() { let (_dir, _layout, replica) = open_test_replica(); let db = &replica.driver; approve(db, THIS_PHONES_KEY); db.set_device_scope(cotton_store::device_scope::DeviceScope::Reader); let holder = holder_in(db, WORKSPACE, Some(THIS_PHONES_KEY)).expect("reads"); assert!(holder.is_err_and(|reason| reason.contains("only read"))); assert!(!may_announce_holds(db, Some(THIS_PHONES_KEY))); } /// RULE: A device's holds written under its replica's author id are retired and the ones whose bytes it still has are recorded again under its device key. #[test] fn author_id_holds_are_retired_and_restated_under_the_device_key() { let (dir, _layout, replica) = open_test_replica(); let db = &replica.driver; approve(db, THIS_PHONES_KEY); let kept = key('a'); let gone = key('b'); let file = dir.path().join("kept.heic"); std::fs::write(&file, b"invented bytes").expect("the file"); an_author_hold(db, &kept); an_author_hold(db, &gone); on_this_device(db, &kept, &file); on_this_device(db, &gone, &dir.path().join("not-there.heic")); let restated = restate_author_holds(db, WORKSPACE, Some(THIS_PHONES_KEY), T0, &mut ids()).expect("the restatement"); assert_eq!( restated, Restated { retired: 2, restated: 1 }, "only the object whose bytes are still here" ); let author = author(db); assert!(!is_live_hold(db, &author, &kept, Tier::Original).expect("reads")); assert!(!is_live_hold(db, &author, &gone, Tier::Original).expect("reads")); assert!(is_live_hold(db, THIS_PHONES_KEY, &kept, Tier::Original).expect("reads")); assert!(!is_live_hold(db, THIS_PHONES_KEY, &gone, Tier::Original).expect("reads")); assert_eq!( holders_of(db, WORKSPACE, &kept, Tier::Original) .expect("reads") .into_iter() .map(|holder| holder.device_id) .collect::>(), vec![THIS_PHONES_KEY.to_string()], "and a reader now sees it" ); // Level: a second pass has nothing left to retire. assert_eq!( restate_author_holds(db, WORKSPACE, Some(THIS_PHONES_KEY), T0, &mut ids()).expect("again"), Restated::default() ); } #[test] fn nothing_is_retired_while_the_key_may_not_hold_here() { let (_dir, _layout, replica) = open_test_replica(); let db = &replica.driver; let object = key('c'); an_author_hold(db, &object); assert_eq!( restate_author_holds(db, WORKSPACE, Some(THIS_PHONES_KEY), T0, &mut ids()).expect("a state"), Restated::default() ); assert!( is_live_hold(db, &author(db), &object, Tier::Original).expect("reads"), "retired only once it can be restated" ); } /// RULE: Once an open replica's author-id holds are all retired, the passes stop asking for the rest of that open, so a level file costs no scan per pass. #[test] fn a_level_replica_is_not_asked_again_until_it_is_opened_again() { let (_dir, _layout, mut replica) = open_test_replica(); approve(&replica.driver, THIS_PHONES_KEY); assert_eq!(keep_holds_level(&mut replica, Some(THIS_PHONES_KEY), T0, &mut ids()), None); assert!(replica.author_holds_level, "nothing to retire: level"); // An author-id row appearing now is one nothing writes any more; the // memo is what this proves — the pass does not look. let object = key('d'); an_author_hold(&replica.driver, &object); assert_eq!(keep_holds_level(&mut replica, Some(THIS_PHONES_KEY), T0, &mut ids()), None); let author = author(&replica.driver); assert!(is_live_hold(&replica.driver, &author, &object, Tier::Original).expect("reads")); // A new open asks again. replica.author_holds_level = false; assert_eq!(keep_holds_level(&mut replica, Some(THIS_PHONES_KEY), T0, &mut ids()), None); assert!(!is_live_hold(&replica.driver, &author, &object, Tier::Original).expect("reads")); } /// RULE: A replica is never marked level while its device key may not hold there, so the retirement still happens once the key's row arrives. #[test] fn a_replica_is_not_level_before_its_key_may_hold() { let (_dir, _layout, mut replica) = open_test_replica(); an_author_hold(&replica.driver, &key('e')); assert_eq!(keep_holds_level(&mut replica, Some(THIS_PHONES_KEY), T0, &mut ids()), None); assert!(!replica.author_holds_level); approve(&replica.driver, THIS_PHONES_KEY); keep_holds_level(&mut replica, Some(THIS_PHONES_KEY), T0, &mut ids()); assert!(replica.author_holds_level); let author = author(&replica.driver); assert!(!is_live_hold(&replica.driver, &author, &key('e'), Tier::Original).expect("reads")); } /// RULE: A device's own hold on an object its ledger names no file for is dropped, and a hold whose file is named stays. #[test] fn a_hold_with_no_file_in_the_ledger_is_dropped_and_one_with_a_file_stays() { let (dir, _layout, replica) = open_test_replica(); let db = &replica.driver; approve(db, THIS_PHONES_KEY); let kept = key('f'); let gone = key('g'); let file = dir.path().join("kept.heic"); std::fs::write(&file, b"invented bytes").expect("the file"); on_this_device(db, &kept, &file); for object in [&kept, &gone] { cotton_store::media_holdings::record_holding( db, WORKSPACE, THIS_PHONES_KEY, object, Tier::Original, 9, T0, &mut ids(), cotton_store::mint::Held::Replica, ) .expect("a hold"); } assert_eq!(drop_missing_holds(db, WORKSPACE, Some(THIS_PHONES_KEY), T0 + 1, &mut ids()), Ok(1)); assert!(is_live_hold(db, THIS_PHONES_KEY, &kept, Tier::Original).expect("reads")); assert!(!is_live_hold(db, THIS_PHONES_KEY, &gone, Tier::Original).expect("reads")); } /// The relay's word on the time, fixed at the pass's instant. struct FixedJudge; impl cotton_store::judge::JudgeSource for FixedJudge { fn now(&self) -> Option { Some(T0) } fn mint_clock(&self, wall_ms: i64) -> Result { Ok(cotton_store::mint::Clock::judged(Some(T0), wall_ms, 0, "6f1c1f55-0000-4000-8000-000000000003".to_string())) } fn confirm(&self, _device_ts_ms: i64) -> Result { Ok(false) } fn offer(&self, _server_time: &str, _wall_ms: i64) -> Result { Err("a fixed judge takes no reading".to_string()) } } /// The steps one drop pass asks of the file for `missing` holds whose files /// are gone, in a replica that also carries `besides` holds of other Macs, /// each with its write. The pass runs on a FRESH judged handle — the file /// just opened, its release pass not yet run — as one Mac's did on 11 Oct /// 2026, right after its copy was replaced. fn steps_to_drop(missing: usize, besides: usize) -> u64 { let (_dir, _layout, replica) = open_test_replica(); let db = replica.driver; approve(&db, THIS_PHONES_KEY); db.run( "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?) \ INSERT INTO cotton_media_holdings (id, workspace_id, object_key, device_id, tier, bytes, \ verified_at, created_at, updated_at, _hlc) \ SELECT 'other-' || i, ?, ? || '/photos/' || printf('%064d', i) || '.heic', 'OtherMac' || (i % 7), \ 'original', 9, '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z', \ '2026-09-08T09:00:00.000Z', '1788800000000:0001:device:other' FROM n", &[SqlValue::Integer(besides as i64), text(WORKSPACE), text(WORKSPACE)], ) .expect("other Macs' holds"); db.run( "INSERT INTO _writes (tbl, row_id, hlc, author, op_id, kind, held) \ SELECT 'cotton_media_holdings', id, _hlc, 'device:other', 'op-' || id, 'create', 0 \ FROM cotton_media_holdings WHERE id LIKE 'other-%'", &[], ) .expect("their writes"); for i in 0..missing { cotton_store::media_holdings::record_holding( &db, WORKSPACE, THIS_PHONES_KEY, &format!("{WORKSPACE}/photos/gone-{i}.heic"), Tier::Original, 9, T0, &mut ids(), cotton_store::mint::Held::Replica, ) .expect("a hold"); } let db = db.replica_judged_by(std::sync::Arc::new(FixedJudge), Box::new(ids())); let before = db.steps(); assert_eq!(drop_missing_holds(&db, WORKSPACE, Some(THIS_PHONES_KEY), T0 + 1, &mut ids()), Ok(missing)); db.steps() - before } /// RULE: Each hold a drop pass drops costs the same steps among 1,000 holds as among 100,000 — no drop re-reads the file's writes. /// /// Measured 11 Oct 2026 on a Mac: 26,368 missing holds dropped in one /// transaction, each drop re-scanning 916k `_writes` rows for held receipts /// (the release pass ran again at every depth > 0), with the replica locked /// for over an hour and sync, ingest and the server's restart behind it. A /// fresh handle may scan once per pass; the 40 drops beyond the first 20 may /// not scan at all. #[test] fn dropping_holds_costs_the_same_steps_among_1_000_and_100_000_holds() { let further = |besides: usize| steps_to_drop(60, besides).saturating_sub(steps_to_drop(20, besides)); let among_few = further(1_000); let among_many = further(100_000); assert!( among_many <= among_few + among_few / 10, "40 more drops took {among_few} steps among 1,000 holds and {among_many} among 100,000" ); }