//! Groundwork slice 7, the client half: this device's cache giving up the //! bytes of a record that was erased, and the queues that move bytes skipping //! dead keys. //! //! A real replica in a temporary data dir, invented bytes, a fixed clock. //! Every row is synthetic, and nothing is dialled. use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use cotton_core::media::keys::derived_tier_keys; use cotton_store::media_erasure::pending_unlinks; use cotton_store::media_ledger::{ claim_due_media, enqueue_media, media_by_key, MediaEnqueueInput, AFTER_NEXT_EXCHANGE, }; use cotton_store::mint::Change; use serde_json::json; use super::*; use crate::media::{finish_upload, is_dead_key_refusal, plan_upload, work_list, Uploaded}; use crate::seams::{FixedClock, SeededRandom}; use crate::test_support::{open_replica_for, open_test_replica, WORKSPACE}; use crate::transport::ServerRefusal; const T0: i64 = 1_760_000_000_000; const PHOTOS: &str = "cotton_photos"; const AT: &str = "2026-09-08T10:00:00.000Z"; fn sha(n: u8) -> String { format!("{n:064x}") } fn key_in(workspace: &str, n: u8, ext: &str) -> String { format!("{workspace}/photos/{}.{ext}", sha(n)) } fn photo_id(n: u8) -> String { format!("photo:{}", sha(n)) } fn photo(workspace: &str, n: u8, key: &str) -> Change { let id = photo_id(n); let patch = json!({ "id": id, "workspace_id": workspace, "key": key, "sha256": sha(n), "content_type": "image/heic", "size_bytes": 10, "taken_at": AT, "created_at": AT, "updated_at": AT, }) .as_object() .expect("an object") .clone(); Change::create(PHOTOS, &id, patch) } /// Mint `changes` in the replica as this device's own write. fn act(replica: &Replica, at_ms: i64, changes: Vec) { let mut ids = crate::test_support::fresh_ids(); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::device_job( cotton_store::actor::JobName::named("test").expect("a job name"), ), verb: "test".to_string(), history: cotton_store::mint::History::Kept, changes, }, &cotton_store::mint::clock::writer_clock(&replica.driver, at_ms, &mut ids).expect("the clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("mints"); } fn erase(replica: &Replica, at_ms: i64, n: u8) { act(replica, at_ms, vec![Change::erase(PHOTOS, &photo_id(n), "bin")]); } /// Put invented bytes at `path` and a ledger row for `key` pointing at it. fn cached_at(replica: &Replica, key: &str, path: &Path, state: &str) { std::fs::create_dir_all(path.parent().expect("a folder")).expect("the folder"); std::fs::write(path, format!("the invented bytes of {key}")).expect("the file"); enqueue_media( &replica.driver, &MediaEnqueueInput { key: key.to_string(), workspace_id: replica.workspace_id.clone(), sha256: sha(0), content_type: "image/heic".to_string(), size_bytes: 10, local_path: Some(path.display().to_string()), state: Some(state.to_string()), after: None, after_row_id: None, tier: None, captured_here: false, now: AT.to_string(), }, ) .expect("the ledger row"); } /// The cache path this device files `key`'s bytes under. fn cache_path(layout: &crate::Layout, workspace: &str, key: &str) -> PathBuf { let name = key.rsplit('/').next().expect("a name"); layout.client_media_dir().join(workspace).join(&name[..2]).join(name) } fn sweep(layout: &crate::Layout) -> UnlinkSweep { UnlinkSweep { layout: layout.clone(), device_key: crate::identity::DeviceKey::fixed(None), random: Arc::new(SeededRandom::default()), indexed: Arc::default(), knows_every: Arc::new(|| true), } } fn queued(replica: &Arc>) -> Vec { let held = replica.lock().expect("the replica"); pending_unlinks(&held.driver).expect("reads").into_iter().map(|p| p.key).collect() } fn clock() -> FixedClock { FixedClock::default_start() } /// RULE: An erase folded on a device takes the erased key's cached file and its renditions' files off it and drops their ledger rows, and no later pass fetches them back. #[test] fn erased_photo_leaves_no_bytes_on_the_replica_and_no_pass_refetches() { let (_dir, layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k)]); let mut files = Vec::new(); for object in std::iter::once(k.clone()).chain(derived_tier_keys(&k)) { let path = cache_path(&layout, WORKSPACE, &object); cached_at(&replica, &object, &path, "synced"); files.push(path); } erase(&replica, T0 + 1_000, 1); let replica = Arc::new(Mutex::new(replica)); assert_eq!(queued(&replica), vec![k.clone()], "the premise: the dead key is queued"); let pass = unlink_pass(&replica, &sweep(&layout), &clock()); assert_eq!((pass.unlinked, pass.files, pass.last_error.clone()), (1, 3, None), "{pass:?}"); for path in &files { assert!(!path.exists(), "{} is still on the device", path.display()); } let held = replica.lock().expect("the replica"); for object in std::iter::once(k.clone()).chain(derived_tier_keys(&k)) { assert!(media_by_key(&held.driver, &object).expect("reads").is_none(), "{object} is still in the ledger"); } assert!(pending_unlinks(&held.driver).expect("reads").is_empty()); let (wanted, _) = work_list(&held.driver, WORKSPACE, "another-device", 10, 1_791_331_200_000).expect("reads"); assert!(wanted.is_empty(), "a pass would fetch the erased key back: {wanted:?}"); } /// RULE: A dead key whose bytes the server never took keeps its file for a week after it was queued, and while any /// pulled row is still parked: a record naming it may not have arrived yet. Then it goes as any other. #[test] fn bytes_only_on_this_device_wait_before_an_unlink_takes_them() { let (_dir, layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k)]); let path = cache_path(&layout, WORKSPACE, &k); cached_at(&replica, &k, &path, "pending"); erase(&replica, T0 + 1_000, 1); let replica = Arc::new(Mutex::new(replica)); let queued_at = { let held = replica.lock().expect("the replica"); pending_unlinks(&held.driver).expect("reads").into_iter().next().expect("queued").queued_at }; let at = chrono::DateTime::parse_from_rfc3339(&queued_at).expect("an instant").with_timezone(&chrono::Utc); let clock = clock(); clock.set(at + chrono::Duration::minutes(1)); let pass = unlink_pass(&replica, &sweep(&layout), &clock); assert_eq!((pass.unlinked, pass.files), (0, 0), "{pass:?}"); assert!(path.exists(), "bytes only here went at once"); assert_eq!(queued(&replica), vec![k.clone()], "still queued"); // A week on, with a pulled row still parked: kept. clock.set(at + chrono::Duration::days(8)); { let held = replica.lock().expect("the replica"); held.driver.run("CREATE TABLE IF NOT EXISTS _seal_parked (tbl TEXT NOT NULL, row_id TEXT NOT NULL, code TEXT NOT NULL, reason TEXT NOT NULL, row TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID", &[]).expect("parked"); held.driver.run("INSERT INTO _seal_parked (tbl, row_id, code, reason, row, at) VALUES ('photo', 'p-later', 'no_key', 'invented', '{}', '2026-09-08T10:00:00Z')", &[]).expect("parked"); } let pass = unlink_pass(&replica, &sweep(&layout), &clock); assert_eq!(pass.files, 0, "{pass:?}"); assert!(path.exists(), "a parked row may name it"); { let held = replica.lock().expect("the replica"); held.driver.run("DELETE FROM _seal_parked", &[]).expect("opened"); } // A week on, nothing parked, but the copy not caught up: kept (ABSENCE 5, item 6). let mut behind = sweep(&layout); behind.knows_every = Arc::new(|| false); let pass = unlink_pass(&replica, &behind, &clock); assert_eq!(pass.files, 0, "{pass:?}"); assert!(path.exists(), "a copy not caught up keeps bytes only here"); let pass = unlink_pass(&replica, &sweep(&layout), &clock); assert_eq!((pass.unlinked, pass.files), (1, 1), "{pass:?}"); assert!(!path.exists()); } /// RULE: A dead key this copy has no ledger row for waits like bytes only here: it stays queued. #[test] fn a_key_with_no_ledger_row_waits_like_bytes_only_here() { let (_dir, layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k)]); erase(&replica, T0 + 1_000, 1); let replica = Arc::new(Mutex::new(replica)); assert_eq!(queued(&replica), vec![k.clone()]); let queued_at = { let held = replica.lock().expect("the replica"); pending_unlinks(&held.driver).expect("reads").into_iter().next().expect("queued").queued_at }; let clock = clock(); clock.set(chrono::DateTime::parse_from_rfc3339(&queued_at).expect("an instant").with_timezone(&chrono::Utc) + chrono::Duration::minutes(1)); let pass = unlink_pass(&replica, &sweep(&layout), &clock); assert_eq!(pass.unlinked, 0, "{pass:?}"); assert_eq!(queued(&replica), vec![k], "still queued"); } /// RULE: An unlink never takes a file under another database's folder whatever the ledger path says, nor a file another key's row still names, and each replica drains its own queue alone. #[test] fn an_unlink_stays_inside_its_own_database_and_leaves_a_shared_file() { let (dir, layout, mine) = open_test_replica(); const OTHER: &str = "66666666-6666-4666-8666-666666666666"; let other = open_replica_for(&layout, dir.path(), OTHER); // A ledger row of MY dead key whose path is under the other database. let stray = key_in(WORKSPACE, 1, "heic"); act(&mine, T0, vec![photo(WORKSPACE, 1, &stray)]); let elsewhere = cache_path(&layout, OTHER, &stray); cached_at(&mine, &stray, &elsewhere, "synced"); // My dead key whose file a live key of mine shares (content-addressed). let shared = key_in(WORKSPACE, 2, "heic"); let alive = key_in(WORKSPACE, 3, "jpg"); act(&mine, T0 + 1, vec![photo(WORKSPACE, 2, &shared), photo(WORKSPACE, 3, &alive)]); let one_file = cache_path(&layout, WORKSPACE, &shared); cached_at(&mine, &shared, &one_file, "synced"); cached_at(&mine, &alive, &one_file, "synced"); // The other database's own dead key. let theirs = key_in(OTHER, 4, "heic"); act(&other, T0 + 2, vec![photo(OTHER, 4, &theirs)]); let their_file = cache_path(&layout, OTHER, &theirs); cached_at(&other, &theirs, &their_file, "synced"); erase(&mine, T0 + 1_000, 1); erase(&mine, T0 + 1_001, 2); erase(&other, T0 + 1_002, 4); let mine = Arc::new(Mutex::new(mine)); let other = Arc::new(Mutex::new(other)); let pass = unlink_pass(&mine, &sweep(&layout), &clock()); assert_eq!((pass.unlinked, pass.files), (2, 0), "{pass:?}"); assert!(elsewhere.exists(), "a file under another database's folder went"); assert!(one_file.exists(), "a file a live key shares went"); assert!(their_file.exists(), "the other database's file went with my queue"); assert_eq!(queued(&other), vec![theirs.clone()], "my pass drained the other database's queue"); let pass = unlink_pass(&other, &sweep(&layout), &clock()); assert_eq!((pass.unlinked, pass.files), (1, 1), "{pass:?}"); assert!(!their_file.exists()); assert!(elsewhere.exists(), "the other database's pass took my ledger's file"); } /// RULE: A key named again before the pass keeps its cached file and leaves the queue, and a pass that died after taking the files resumes and marks the key. #[test] fn a_named_again_key_keeps_its_file_and_a_crashed_pass_resumes() { let (_dir, layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k)]); let path = cache_path(&layout, WORKSPACE, &k); cached_at(&replica, &k, &path, "synced"); erase(&replica, T0 + 1_000, 1); act(&replica, T0 + 2_000, vec![photo(WORKSPACE, 2, &k)]); let replica = Arc::new(Mutex::new(replica)); let pass = unlink_pass(&replica, &sweep(&layout), &clock()); assert_eq!(pass.unlinked, 0, "{pass:?}"); assert!(path.exists(), "a re-named key lost its file"); assert!(queued(&replica).is_empty()); let k2 = key_in(WORKSPACE, 5, "heic"); { let held = replica.lock().expect("the replica"); act(&held, T0 + 3_000, vec![photo(WORKSPACE, 5, &k2)]); cached_at(&held, &k2, &cache_path(&layout, WORKSPACE, &k2), "synced"); erase(&held, T0 + 4_000, 5); // The first pass's removal and ledger drop happened; its mark did not. std::fs::remove_file(cache_path(&layout, WORKSPACE, &k2)).expect("removed"); cotton_store::media_ledger::delete_media_row(&held.driver, &k2).expect("dropped"); } assert_eq!(queued(&replica), vec![k2.clone()]); let pass = unlink_pass(&replica, &sweep(&layout), &clock()); assert_eq!((pass.unlinked, pass.files), (1, 0), "{pass:?}"); assert!(queued(&replica).is_empty()); } /// RULE: A queued key a present row names while _media_key_names is empty is never taken by the pass: the guard reads the holder columns, writes the names back and takes the key out of the queue. #[test] fn a_key_the_index_missed_keeps_its_file() { let (_dir, layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k), photo(WORKSPACE, 2, &k)]); let path = cache_path(&layout, WORKSPACE, &k); cached_at(&replica, &k, &path, "synced"); erase(&replica, T0 + 1_000, 1); let replica = Arc::new(Mutex::new(replica)); // The start rebuild runs first, so the defect lands after it. let sweep = sweep(&layout); assert!(unlink_pass(&replica, &sweep, &clock()).indexed.is_some(), "the first pass did not rebuild"); { // The defect: an index that lost every name, and the key queued anyway. let held = replica.lock().expect("the replica"); held.driver.exec("DELETE FROM _media_key_names").expect("runs"); held.driver .run("INSERT INTO _media_unlinks (key, queued_at) VALUES (?, ?)", &[text(&k), text(AT)]) .expect("runs"); } assert_eq!(queued(&replica), vec![k.clone()], "the premise: the key is queued"); let pass = unlink_pass(&replica, &sweep, &clock()); assert_eq!((pass.unlinked, pass.files, pass.repaired), (0, 0, 1), "{pass:?}"); assert!(path.exists(), "a key a present row names lost its file"); assert!(queued(&replica).is_empty(), "the repaired key is still queued"); let held = replica.lock().expect("the replica"); assert!(cotton_store::media_keys::is_named(&held.driver, &k).expect("reads"), "the name was not written back"); assert!(!bytes_are_dead(&held.driver, &k).expect("reads")); } /// RULE: An erased record's pending upload is never sent: the drain leaves it untouched for the unlink pass, which drops it from the queue with its file. #[test] fn erased_record_is_dropped_from_the_upload_queue_and_never_sent() { let (_dir, layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k)]); let path = cache_path(&layout, WORKSPACE, &k); cached_at(&replica, &k, &path, "pending"); erase(&replica, T0 + 1_000, 1); let row = media_by_key(&replica.driver, &k).expect("reads").expect("the row"); assert!(matches!(plan_upload(&replica, &row, &clock()), Err(Uploaded::Retry)), "a dead key was planned for upload"); let after = media_by_key(&replica.driver, &k).expect("reads").expect("the row"); assert_eq!(after, row, "the drain wrote to a dead key's row"); let replica = Arc::new(Mutex::new(replica)); unlink_pass(&replica, &sweep(&layout), &clock()); let held = replica.lock().expect("the replica"); assert!(media_by_key(&held.driver, &k).expect("reads").is_none(), "the erased record is still in the upload queue"); assert!(claim_due_media(&held.driver, 10, "2030-01-01T00:00:00.000Z").expect("reads").is_empty()); assert!(!path.exists()); } /// RULE: An upload the server refused as dead bytes stays pending, waits for the next exchange instead of a backoff, and is due again once an exchange lands. #[test] fn dead_key_upload_refusal_is_retried_not_dropped() { let (_dir, layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k)]); cached_at(&replica, &k, &cache_path(&layout, WORKSPACE, &k), "pending"); let row = media_by_key(&replica.driver, &k).expect("reads").expect("the row"); let refusal = ServerRefusal { code: Some(cotton_core::media::keys::DEAD_KEY_REFUSAL_CODE.to_string()), ..ServerRefusal::new("erased", 410) }; assert!(is_dead_key_refusal(&refusal)); assert_eq!(finish_upload(&replica, &row, Err(refusal), &clock()), Uploaded::Retry); let parked = media_by_key(&replica.driver, &k).expect("reads").expect("the row is kept"); assert_eq!(parked.state, "pending", "a dead-key refusal dropped the entry"); assert_eq!(parked.next_attempt_at.as_deref(), Some(AFTER_NEXT_EXCHANGE)); assert!(claim_due_media(&replica.driver, 10, "2030-01-01T00:00:00.000Z").expect("reads").is_empty(), "a parked row is due before an exchange"); let transport = crate::test_support::FakeTransport::default(); crate::sync::cycle::run_cycle(&replica.driver, &mut &transport, WORKSPACE, AT).expect("an exchange"); let due = claim_due_media(&replica.driver, 10, AT).expect("reads"); assert_eq!(due.iter().map(|row| row.key.clone()).collect::>(), vec![k], "the entry is not due after the exchange"); } /// RULE: Hydrate's work list skips a dead key another device still holds, and takes it again once a new record names it. #[test] fn hydrate_skips_a_dead_key() { let (_dir, _layout, replica) = open_test_replica(); let k = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &k)]); a_peers_hold(&replica, "ServingMacKey", &k); let wanted = |replica: &Replica| work_list(&replica.driver, WORKSPACE, "ThisPhone", 10, 1_791_331_200_000).expect("reads").0; assert_eq!(wanted(&replica), vec![k.clone()], "the premise: a live key another device holds is wanted"); erase(&replica, T0 + 1_000, 1); assert!(wanted(&replica).is_empty(), "hydrate wants a dead key"); act(&replica, T0 + 2_000, vec![photo(WORKSPACE, 2, &k)]); assert_eq!(wanted(&replica), vec![k], "re-added content after an erase is not hydrated"); } fn text(value: &str) -> rusqlite::types::Value { rusqlite::types::Value::Text(value.to_string()) } /// A live device row for `device` and its hold on `key`, written past the /// receipts and reconciled, as `holds_tests` seeds them. fn a_peers_hold(replica: &Replica, device: &str, key: &str) { let db = &replica.driver; 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}")), text(WORKSPACE), text(device), text("An invented Mac"), text(AT), text(device), text(AT), text(AT)], ) .expect("the device row"); cotton_tools::test_fixtures::reconcile(db, "cotton_devices"); 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',10,?,?,?,?)", &[ text(&cotton_store::media_holdings::holding_id(device, key, Tier::Original)), text(WORKSPACE), text(key), text(device), text(AT), text(AT), text(AT), text(&format!("1757325600000:0001:{device}")), ], ) .expect("the peer's hold"); cotton_tools::test_fixtures::reconcile(db, "cotton_media_holdings"); } /// RULE: A replica moved with an empty _media_key_names is reindexed before its queue drains, once per process: a queued key a present row names leaves the queue with its cached file kept, and a dead key in it still goes. #[test] fn a_moved_replica_is_reindexed_once_before_its_queue_drains() { let (_dir, layout, replica) = open_test_replica(); let kept = key_in(WORKSPACE, 1, "heic"); let dead = key_in(WORKSPACE, 3, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &kept), photo(WORKSPACE, 2, &kept), photo(WORKSPACE, 3, &dead)]); let kept_file = cache_path(&layout, WORKSPACE, &kept); let dead_file = cache_path(&layout, WORKSPACE, &dead); cached_at(&replica, &kept, &kept_file, "synced"); cached_at(&replica, &dead, &dead_file, "synced"); erase(&replica, T0 + 1_000, 1); erase(&replica, T0 + 1_001, 3); // What the early mover left: no names at all, and the named key queued. replica.driver.exec("DELETE FROM _media_key_names").expect("runs"); replica .driver .run("INSERT INTO _media_unlinks (key, queued_at) VALUES (?, ?)", &[text(&kept), text(AT)]) .expect("runs"); let replica = Arc::new(Mutex::new(replica)); let mut premise = queued(&replica); premise.sort(); let mut both = vec![kept.clone(), dead.clone()]; both.sort(); assert_eq!(premise, both, "the premise: both keys are queued"); let sweep = sweep(&layout); let pass = unlink_pass(&replica, &sweep, &clock()); assert!(pass.indexed.is_some_and(|added| added > 0), "the first pass did not rebuild the index: {pass:?}"); assert_eq!((pass.unlinked, pass.files, pass.repaired, pass.last_error.clone()), (1, 1, 0, None), "{pass:?}"); assert!(kept_file.exists(), "a key a present row names lost its file"); assert!(!dead_file.exists(), "the dead key's file stayed"); assert!(queued(&replica).is_empty(), "the queue still holds {:?}", queued(&replica)); { let held = replica.lock().expect("the replica"); assert!(cotton_store::media_keys::is_named(&held.driver, &kept).expect("reads"), "the rebuild did not name the key"); } for _ in 0..2 { let later = unlink_pass(&replica, &sweep, &clock()); assert_eq!(later, UnlinkPass::default(), "a later pass rebuilt again or did something"); } } /// RULE: A replica whose media-key index rebuild fails is not drained in that pass and is not remembered as rebuilt: its queue and its cached files stay until a later pass rebuilds it. #[test] fn a_failed_reindex_drains_nothing() { let (_dir, layout, replica) = open_test_replica(); let dead = key_in(WORKSPACE, 1, "heic"); act(&replica, T0, vec![photo(WORKSPACE, 1, &dead)]); let file = cache_path(&layout, WORKSPACE, &dead); cached_at(&replica, &dead, &file, "synced"); erase(&replica, T0 + 1_000, 1); // A receipt the rebuild cannot decode. replica .driver .exec("INSERT INTO _writes (tbl, row_id, hlc, bytes) VALUES ('cotton_photos', 'photo:broken', '0:0:x', X'00')") .expect("runs"); let replica = Arc::new(Mutex::new(replica)); assert_eq!(queued(&replica), vec![dead.clone()], "the premise: the dead key is queued"); let sweep = sweep(&layout); for _ in 0..2 { let pass = unlink_pass(&replica, &sweep, &clock()); assert!(pass.last_error.as_deref().is_some_and(|error| error.contains("could not be rebuilt")), "{pass:?}"); assert_eq!((pass.unlinked, pass.files, pass.indexed), (0, 0, None), "{pass:?}"); assert!(file.exists(), "a failed rebuild took a file"); assert_eq!(queued(&replica), vec![dead.clone()], "a failed rebuild touched the queue"); } replica.lock().expect("the replica").driver.exec("DELETE FROM _writes WHERE row_id = 'photo:broken'").expect("runs"); let pass = unlink_pass(&replica, &sweep, &clock()); assert!(pass.indexed.is_some(), "the rebuild was remembered after it failed: {pass:?}"); assert_eq!((pass.unlinked, pass.files), (1, 1), "{pass:?}"); assert!(!file.exists()); }