//! The replicator's pass, against a real replica and a fake link.//!//! Every fixture is synthetic and the clock is fixed//! ([nothing-real-ever-goes-in-cotton-s-public-tree]): the bytes are a few//! invented characters, the digests fall out of them, and no test here reaches//! a network or reads a real disk's free space.use std::sync::{Arc, Mutex};use cotton_store::media_holdings::{holders_of, holding_id, Tier};use rusqlite::types::ValueasSqlValue;usesuper::*;usecrate::seams::FixedClock;usecrate::test_support::{open_test_replica, WORKSPACE};/// The Mac under test, by its DEVICE KEY — 43 synthetic characters.const THIS_MACS_KEY: &str = "MacKey_____________________________________";const THE_OTHER_MAC: &str = "device:01J00000000000000000000MAC";const A_PHONE: &str = "device:01J000000000000000000PHONE";fn key(letter: char) -> String { format!("{WORKSPACE}/photos/{}.heic", letter.to_string().repeat(64))}/// A device row, so the holdings join has somebody to join to.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 (?,?,?,?,?,?,?,?)", &[SqlValue::Text(format!("dev:{device_id}")),SqlValue::Text(workspace.to_string()),SqlValue::Text(device_id.to_string()),SqlValue::Text("An invented device".to_string()),SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()),SqlValue::Text(device_id.to_string()),SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()),SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()), ], ) .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, at: &str) { a_peers_hold_in(db, WORKSPACE, device_id, object_key, at);}fn a_peers_hold_in( db: &cotton_store::driver::Driver, workspace: &str, device_id: &str, object_key: &str, at: &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',?,?,?,?,?)", &[SqlValue::Text(holding_id(device_id, object_key, Tier::Original)),SqlValue::Text(workspace.to_string()),SqlValue::Text(object_key.to_string()),SqlValue::Text(device_id.to_string()),SqlValue::Integer(9),SqlValue::Text(at.to_string()),SqlValue::Text(at.to_string()),SqlValue::Text(at.to_string()),SqlValue::Text(format!("1789549200000:0001:{device_id}")), ], ) .expect("the peer's hold"); cotton_tools::test_fixtures::reconcile(&db, "cotton_media_holdings");}/// A link that answers a fixed body for every key it is asked, and remembers/// what it was asked, in order.#[derive(Debug)]structFakeLink { asked: Mutex<Vec<String>>,/// The database each fetch named, in the same order. named: Mutex<Vec<String>>, free: Mutex<Option<u64>>, refuse: Mutex<bool>, policy_room: Mutex<Option<DiskRoom>>,}implFakeLink {fn with_room() -> FakeLink {FakeLink { asked: Mutex::new(Vec::new()), named: Mutex::new(Vec::new()), free: Mutex::new(Some(HYDRATE_DISK_FLOOR_BYTES * 4)), refuse: Mutex::new(false), policy_room: Mutex::new(None), } }fn asked(&self) -> Vec<String> {self.asked.lock().expect("the log").clone() }fn named(&self) -> Vec<String> {self.named.lock().expect("the log").clone() }}implMediaHydrateDepsforFakeLink {fn disk_room(&self, path: &std::path::Path) -> DiskRoom {self.policy_room.lock().expect("the device policy").unwrap_or_else(|| room_left(self.free_bytes(path))) }fn fetch_object_to( &self, database: &str, key: &str, dest: &std::path::Path, ) -> Result<(), ServerRefusal> {self.asked.lock().expect("the log").push(key.to_string());self.named .lock() .expect("the log") .push(database.to_string());if *self.refuse.lock().expect("the switch") {returnErr(ServerRefusal::new("this server signs nothing today", 403)); }// The bytes differ per key, so two objects cannot land on one digest. std::fs::write(dest, format!("the invented bytes of {key}")) .map_err(|error| ServerRefusal::new(error.to_string(), 0)) }fn free_bytes(&self, _path: &std::path::Path) -> Option<u64> { *self.free.lock().expect("the reading") }}structBench { 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 MAC'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_MACS_KEY.to_string(); approve(&replica.driver, &device_id);Bench { dir, layout, replica: Arc::new(Mutex::new(replica)), device_id, clock: FixedClock::default_start(), }}implBench {fn with_file<T>(&self, f: implFnOnce(&cotton_store::driver::Driver) -> T) -> T {let held = self.replica.lock().expect("the replica"); f(&held.driver) }/// This Mac's own copy of `object_key`: a real file, the ledger row/// naming it, and the hold — what a pulled original looks like. A hold/// with no ledger row is one the pass rightly drops.fn its_own_copy(&self, object_key: &str) {let path = self.dir.path().join(object_key.replace('/', "_")); std::fs::write(&path, b"invented").expect("the file");self.with_file(|db| { db.run("INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, \ local_path, state, attempts, created_at, updated_at) \ VALUES (?,?,?,?,?,?,'synced',0,?,?)", &[SqlValue::Text(object_key.to_string()),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text("f".repeat(64)),SqlValue::Text("image/heic".to_string()),SqlValue::Integer(9),SqlValue::Text(path.display().to_string()),SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()),SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()), ], ) .expect("the ledger row"); cotton_store::media_holdings::record_holding( db, WORKSPACE, &self.device_id, object_key,Tier::Original,9,1_789_200_000_000, &mutcrate::test_support::fresh_ids(), cotton_store::mint::Held::Replica, ) .expect("this Mac's own hold"); }); }fn run_with(&self, link: &dynMediaHydrateDeps) -> HydratePass { hydrate_pass( &self.replica, link, &self.layout,Policy::Everything, &self.clock,Some(&self.device_id), &mutcrate::test_support::fresh_ids(), ) }fn run(&self, link: &FakeLink, policy: Policy) -> HydratePass { hydrate_pass( &self.replica, link, &self.layout, policy, &self.clock,Some(&self.device_id), &mutcrate::test_support::fresh_ids(), ) }}#[test]fn a_mac_pulls_only_what_it_lacks() {let bench = bench();let lacking = key('a');let already_here = key('b'); bench.with_file(|db| { a_peers_hold(db, THE_OTHER_MAC, &lacking, "2026-09-08T09:00:00.000Z"); a_peers_hold(db, THE_OTHER_MAC, &already_here, "2026-09-08T09:10:00.000Z"); }); bench.its_own_copy(&already_here);let link = FakeLink::with_room();let pass = bench.run(&link, Policy::Everything); assert_eq!( link.asked(), vec![lacking.clone()],"the object this Mac already holds is not asked for" ); assert_eq!(pass.pulled, 1); assert_eq!(pass.failed, 0); assert!(!pass.floor);// And the hold it recorded is the second one — which is what makes the// other machine's leave stop refusing.let holders = bench.with_file(|db| { holders_of(db, WORKSPACE, &lacking, Tier::Original).expect("the holders") }); assert_eq!(holders.len(), 2); assert!(holders.iter().any(|h| h.device_id == bench.device_id));}/// RULE: A reader can cache an ordinary original without publishing a holding/// or queueing a receipt, because cached bytes must never make a read-only/// device part of the household's redundancy state.#[test]fn a_reader_caches_media_without_announcing_a_holding() {let bench = bench();let object = key('r'); bench.with_file(|db| { db.set_device_scope(cotton_store::device_scope::DeviceScope::Reader); a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"); });let outbox_before = bench.with_file(cotton_store::outbox::pending_count).expect("the outbox");let link = FakeLink::with_room();let pass = bench.run_with(&link); assert_eq!(pass.pulled, 1); assert_eq!(link.asked(), vec![object.clone()]); bench.with_file(|db| { assert!(cotton_store::media_ledger::media_by_key(db, &object).unwrap().is_some()); assert_eq!(holders_of(db, WORKSPACE, &object, Tier::Original).unwrap().len(), 1); assert_eq!(cotton_store::outbox::pending_count(db).unwrap(), outbox_before); });}/// `device_id` is a phone: its row says so.fn a_phone(db: &cotton_store::driver::Driver, device_id: &str) { approve(db, device_id); db.run("UPDATE cotton_devices SET platform = 'ios' WHERE device_id = ?", &[SqlValue::Text(device_id.to_string())]) .expect("the platform"); cotton_tools::test_fixtures::reconcile(db, "cotton_devices");}/// `device_id` is a Mac whose device row says "rows only": every byte tool/// `only_opened`, the rows `storage_rules::mac_keeps_patches` writes.fn keeps_rows_only(db: &cotton_store::driver::Driver, device_id: &str) { approve(db, device_id);for tool in cotton_store::storage_rules::BYTE_TOOLS { db.run("INSERT INTO cotton_storage_rules (id, workspace_id, device_id, tool, keep_rule, created_at, updated_at) \ VALUES (?,?,?,?,'only_opened','2026-09-08T09:00:00.000Z','2026-09-08T09:00:00.000Z')", &[SqlValue::Text(cotton_store::storage_rules::row_id(device_id, tool)),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(device_id.to_string()),SqlValue::Text(tool.to_string()), ], ) .expect("the rule"); } cotton_tools::test_fixtures::reconcile(db, "cotton_storage_rules");}/// RULE: the two-holder target counts only Macs that keep everything — an original a keeper and a phone hold, or a keeper and a rows-only Mac, is still short of its second copy and is pulled; one two keepers hold is done (sync programme, lane D, 12 Oct 2026: a phone's or a rows-only Mac's copy may go tomorrow, so it is never one of the household's two).#[test]fn the_replicator_stops_at_two_macs_that_keep_everything() {const A_ROWS_ONLY_MAC: &str = "device:01J000000000000000ROWSMAC";const A_SECOND_KEEPER: &str = "device:01J00000000000000KEEPER2";let bench = bench();let with_a_phone = key('c');let with_a_rows_only_mac = key('g');let with_two_keepers = key('h'); bench.with_file(|db| { a_phone(db, A_PHONE); keeps_rows_only(db, A_ROWS_ONLY_MAC); a_peers_hold(db, THE_OTHER_MAC, &with_a_phone, "2026-09-08T09:00:00.000Z"); a_peers_hold(db, A_PHONE, &with_a_phone, "2026-09-08T09:01:00.000Z"); a_peers_hold(db, THE_OTHER_MAC, &with_a_rows_only_mac, "2026-09-08T09:02:00.000Z"); a_peers_hold(db, A_ROWS_ONLY_MAC, &with_a_rows_only_mac, "2026-09-08T09:03:00.000Z"); a_peers_hold(db, THE_OTHER_MAC, &with_two_keepers, "2026-09-08T09:04:00.000Z"); a_peers_hold(db, A_SECOND_KEEPER, &with_two_keepers, "2026-09-08T09:05:00.000Z"); });let link = FakeLink::with_room();let pass = bench.run(&link, Policy::Everything);letmut asked = link.asked(); asked.sort(); assert_eq!( asked, vec![with_a_phone, with_a_rows_only_mac],"a phone's copy and a rows-only Mac's copy are not the second copy; two keepers' are" ); assert_eq!(pass.pulled, 2);}/// RULE: A Rows-only Mac never automatically rehydrates even a recently opened original, because the old thirty-day warm window would refill the disk after the Files choice; foreground opens fetch on demand.#[test]fn a_rows_only_mac_never_automatically_rehydrates_recently_opened_originals() {let bench = bench();let unopened = key('i');let opened = key('j'); bench.with_file(|db| { keeps_rows_only(db, THIS_MACS_KEY); a_peers_hold(db, THE_OTHER_MAC, &unopened, "2026-09-08T09:00:00.000Z"); a_peers_hold(db, THE_OTHER_MAC, &opened, "2026-09-08T09:01:00.000Z");// Opened here this week, the bytes since gone from this disk. db.run("INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, state, attempts, \ created_at, updated_at, last_viewed_at) VALUES (?,?,?,?,9,'synced',0,?,?,?)", &[SqlValue::Text(opened.clone()),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text("e".repeat(64)),SqlValue::Text("image/heic".to_string()),SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()),SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()),SqlValue::Text(bench.clock.now_iso()), ], ) .expect("the ledger row"); });let link = FakeLink::with_room(); bench.run(&link, Policy::Everything); assert!(link.asked().is_empty(), "Rows only must not refill the disk in the background");}#[test]fn a_revoked_holder_puts_an_object_back_on_the_list() {// The other half of "two holders": a device that may never come back is not// one of them, and the pass has to see that the moment its row folds.let bench = bench();let object = key('d'); bench.with_file(|db| { a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"); a_peers_hold(db, A_PHONE, &object, "2026-09-08T09:01:00.000Z"); db.run("UPDATE cotton_devices SET revoked_at = ? WHERE device_id = ?", &[SqlValue::Text("2026-09-08T09:30:00.000Z".to_string()),SqlValue::Text(A_PHONE.to_string()), ], ) .expect("the revocation"); cotton_tools::test_fixtures::reconcile(&db, "cotton_devices"); });let link = FakeLink::with_room();let pass = bench.run(&link, Policy::Everything); assert_eq!(link.asked(), vec![object]); assert_eq!(pass.pulled, 1);}#[test]fn the_disk_guard_stops_the_pass() {let bench = bench();let object = key('e'); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"));let link = FakeLink::with_room(); *link.free.lock().expect("the reading") = Some(HYDRATE_DISK_FLOOR_BYTES - 1);let pass = bench.run(&link, Policy::Everything); assert!(link.asked().is_empty(), "nothing is asked for below the floor"); assert!(pass.floor); assert_eq!(pass.pulled, 0); assert_eq!( pass.pending, 1,"the object is still short of a second holder, and says so" ); assert!(!pass.catch_up(), "a pass held back by the disk never chains");}#[test]fn an_unknown_free_space_reading_stops_the_pass_and_says_why() {// Unknown is not permission. A replicator that filled a disk because nobody// could tell it how full the disk was is the masked fallback this repo does// not allow.let bench = bench(); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &key('f'), "2026-09-08T09:00:00.000Z"));let link = FakeLink::with_room(); *link.free.lock().expect("the reading") = None;let pass = bench.run(&link, Policy::Everything); assert!(link.asked().is_empty()); assert!(pass.floor); assert!(pass .last_error .as_deref() .expect("a reason") .contains("how much room is left"));}#[test]fn a_phone_pulls_nothing_here() {let bench = bench(); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &key('g'), "2026-09-08T09:00:00.000Z"));let link = FakeLink::with_room();let pass = bench.run(&link, Policy::Viewed); assert!(link.asked().is_empty()); assert!(pass.off, "the phone's downloads are `media.ensure`, on a finger");}#[test]fn a_pulled_object_is_findable_and_is_not_queued_for_upload() {let bench = bench();let object = key('h'); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"));let link = FakeLink::with_room(); assert_eq!(bench.run(&link, Policy::Everything).pulled, 1);let row = bench .with_file(|db| cotton_store::media_ledger::media_by_key(db, &object).expect("the row")) .expect("a ledger row"); assert_eq!( row.state, "synced","these bytes came OUT of the bucket; queueing them would send back what is already there" );let path = std::path::PathBuf::from(row.local_path.expect("a path")); assert!(path.exists(), "and `read.mediaPath` can find them");}#[test]fn a_refused_object_leaves_no_half_file_and_comes_back_next_pass() {let bench = bench();let object = key('i'); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"));let link = FakeLink::with_room(); *link.refuse.lock().expect("the switch") = true;let pass = bench.run(&link, Policy::Everything); assert_eq!(pass.failed, 1); assert_eq!(pass.pulled, 0); assert_eq!(pass.pending, 1);let scratch: Vec<_> = std::fs::read_dir(bench.layout.client_media_dir().join(WORKSPACE)) .expect("the folder") .flatten() .filter(|entry| entry.file_name().to_string_lossy().ends_with(".part")) .collect(); assert!(scratch.is_empty(), "a failed fetch cleans up after itself"); *link.refuse.lock().expect("the switch") = false; assert_eq!(bench.run(&link, Policy::Everything).pulled, 1);}#[test]fn the_work_list_is_capped_and_says_how_much_is_left() {let bench = bench();let objects: Vec<String> = ('a'..='z') .take(HYDRATE_BATCH + 4) .map(key) .collect(); bench.with_file(|db| {for (index, object) in objects.iter().enumerate() { a_peers_hold( db, THE_OTHER_MAC, object, &format!("2026-09-08T09:{index:02}:00.000Z"), ); } });let link = FakeLink::with_room();let pass = bench.run(&link, Policy::Everything); assert_eq!(pass.pulled, HYDRATE_BATCH); assert_eq!(pass.pending, 4, "the rest is the next pass's work"); assert!(pass.catch_up(), "and the next pass follows at once");letmut newest_first = objects.clone(); newest_first.reverse(); assert_eq!( link.asked(), newest_first[..HYDRATE_BATCH].to_vec(),"newest first" );}#[test]fn an_object_this_mac_alone_holds_is_not_something_to_ask_a_server_for() {// The ledger says it is short of a second holder — and this machine IS the// one holder, so there is nowhere to pull it from. Somebody else's pass is// what fixes it.let bench = bench();let object = key('j'); bench.its_own_copy(&object);let link = FakeLink::with_room();let pass = bench.run(&link, Policy::Everything); assert!(link.asked().is_empty()); assert_eq!(pass.pending, 0, "nothing on this machine's list");}#[test]fn the_floor_is_read_one_way_for_every_pull_on_this_machine() {// Exhaustive over the three answers and the boundary. The floor itself is// "at least this much must stay free", so a volume with EXACTLY the floor// left takes nothing more — and the standby's pull, which asks this same// function through `cotton-ffi`, has no second comparison to disagree. assert_eq!(room_left(Some(HYDRATE_DISK_FLOOR_BYTES + 1)), DiskRoom::Enough); assert_eq!(room_left(Some(u64::MAX)), DiskRoom::Enough); assert_eq!(room_left(Some(HYDRATE_DISK_FLOOR_BYTES)), DiskRoom::Floor); assert_eq!(room_left(Some(0)), DiskRoom::Floor); assert_eq!(room_left(None), DiskRoom::Unread, "unknown is never permission");}/// A second database this Mac holds beside its own — a project's.const A_PROJECT: &str = "66666666-6666-4666-8666-666666666666";/// RULE: The replica pull runs over every database a device holds at its household's server, and each fetch names the database its key belongs to.#[test]fn replica_pull_covers_every_database() {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 mine = key('a');let theirs = format!("{A_PROJECT}/photos/{}.heic", "b".repeat(64)); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &mine, "2026-09-08T09:00:00.000Z")); a_peers_hold_in( &project.lock().expect("the project").driver, A_PROJECT, THE_OTHER_MAC, &theirs,"2026-09-08T09:00:00.000Z", );let link = FakeLink::with_room();let databases = vec![ WORKSPACE.to_string(),"77777777-7777-4777-8777-777777777777".to_string(), A_PROJECT.to_string(), ];let pass = hydrate_every( &databases, &mut |id| match id { WORKSPACE => Ok(Arc::clone(&bench.replica)), A_PROJECT => Ok(Arc::clone(&project)), other => Err(format!("{other} would not open")), }, &link, &bench.layout,Policy::Everything, &bench.clock,Some(&bench.device_id), &mutcrate::test_support::fresh_ids(), ); assert_eq!(pass.pulled, 2, "one object in each database"); assert_eq!(link.asked(), vec![mine.clone(), theirs.clone()]); assert_eq!( link.named(), vec![WORKSPACE.to_string(), A_PROJECT.to_string()],"each fetch names the file its key is in" ); assert!(!pass.off); assert_eq!( pass.last_error.as_deref(),Some("77777777-7777-4777-8777-777777777777 would not open"),"a database that will not open is said, and the others are still pulled" );// The project's hold is recorded in the PROJECT's file, and its bytes// under the project's folder.let held = project.lock().expect("the project");let holders = holders_of(&held.driver, A_PROJECT, &theirs, Tier::Original).expect("holders"); assert!(holders.iter().any(|holder| holder.device_id == bench.device_id)); assert!(bench .layout .client_media_dir() .join(A_PROJECT) .read_dir() .expect("the project's folder") .next() .is_some());}/// A link whose first fetch of every key is cut half way (status 0, the line/// dropped) and whose next sends only what the partial lacks — the way the/// real transport answers `Range: bytes=N-` with a 206.#[derive(Debug, Default)]structCutLink {/// The bytes already on disk when each fetch began, in order. had: Mutex<Vec<u64>>,}implMediaHydrateDepsforCutLink {fn fetch_object_to(&self, _database: &str, key: &str, dest: &std::path::Path) -> Result<(), ServerRefusal> {use std::io::Write;let whole = format!("the invented bytes of {key}, long enough to cut in two").into_bytes();let have = std::fs::metadata(dest).map(|m| m.len()).unwrap_or(0);let first = { letmut had = self.had.lock().expect("the log"); had.push(have); had.len() == 1 };let half = whole.len() / 2;letmut file = std::fs::OpenOptions::new().create(true).append(true).open(dest).expect("the partial");if first { file.write_all(&whole[..half]).expect("half");returnErr(ServerRefusal::new("the bytes stopped arriving", 0)); } file.write_all(&whole[usize::try_from(have).expect("small")..]).expect("the rest");Ok(()) }fn free_bytes(&self, _path: &std::path::Path) -> Option<u64> {Some(HYDRATE_DISK_FLOOR_BYTES * 4) }}/// RULE: A standby's replica fetch cut part way keeps what arrived and the next pass asks only for the rest — on 13 Oct 2026 a standby's quit threw away 195 MB of a 196.4 MB bundle, and every cut meant the whole object over the relay again.#[test]fn a_cut_hydrate_fetch_resumes_from_its_last_byte() {let bench = bench();let object = key('r'); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"));let link = CutLink::default();let cut = bench.run_with(&link); assert_eq!((cut.pulled, cut.failed), (0, 1));let whole = format!("the invented bytes of {object}, long enough to cut in two");let half = u64::try_from(whole.len() / 2).expect("small");let resumed = bench.run_with(&link); assert_eq!(resumed.pulled, 1); assert_eq!(*link.had.lock().expect("the log"), vec![0, half], "the second fetch began at the cut");let landed = bench.with_file(|db| { db.get("SELECT local_path FROM _media WHERE key = ?", &[SqlValue::Text(object.clone())]) .expect("the read") .expect("the row") .text("local_path") .expect("a path") .to_string() }); assert_eq!(std::fs::read_to_string(landed).expect("the file"), whole, "the object is whole");}/// RULE: One replica walk per media store in a process — a walk that finds another going over the same store does not start, because a stopped server cannot cancel its blocking walk and a restarted one walked the same work list beside it.#[test]fn a_second_walk_over_a_store_is_not_started() {let bench = bench();let object = key('w'); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"));let link = FakeLink::with_room();let every = |bench: &Bench, link: &FakeLink| { hydrate_every( &[WORKSPACE.to_string()], &mut |_| Ok(Arc::clone(&bench.replica)), link, &bench.layout,Policy::Everything, &bench.clock,Some(&bench.device_id), &mutcrate::test_support::fresh_ids(), ) };let running = Walking::take(bench.layout.client_media_dir()).expect("the first walk");let beside = every(&bench, &link); assert!(link.asked().is_empty(), "the second walk asked for nothing"); assert_eq!(beside.pulled, 0); drop(running); assert_eq!(every(&bench, &link).pulled, 1, "once the first is done, a walk goes");}/// RULE: A Mac hydration pass obeys the device port's disk policy instead of reapplying a hard-coded reserve, because media and jobs must protect the same keep-free setting.#[test]fn a_hydration_pass_uses_its_device_policy() {let bench = bench();let object = key('p'); bench.with_file(|db| a_peers_hold(db, THE_OTHER_MAC, &object, "2026-09-08T09:00:00.000Z"));let link = FakeLink::with_room(); *link.policy_room.lock().unwrap() = Some(DiskRoom::Floor); assert!(bench.run(&link, Policy::Everything).floor); assert!(link.asked().is_empty()); *link.free.lock().unwrap() = Some(1); *link.policy_room.lock().unwrap() = Some(DiskRoom::Enough); assert_eq!(bench.run(&link, Policy::Everything).pulled, 1);}