//! A retained Storage pass. The synced rule and local ledger are the queue;//! starting again after interruption recomputes what remains. The media drain//! owns its cadence, as the ingest scheduler owns source passes.usesuper::evict::{EvictPass, EvictSweep, MediaEvictDeps};usecrate::{layout::Layout, replica::Replica, seams::Clock};use cotton_store::{driver::Driver, mint::Held, outbox::IdSource, storage_rules};use std::sync::{Arc, Mutex};#[derive(Debug, Default, serde::Serialize)]#[serde(rename_all = "camelCase")]pubstructApplied {pub removed: usize,pub freed_bytes: u64,pub errors: Vec<String>,pub rows: Vec<storage_rules::StorageRow>,}// Only this device's originals can leave. Even a bad local ledger path must// never let Storage unlink a database, a thumbnail cache or another folder.fn owned_original_path(layout: &Layout, workspace: &str, path: &std::path::Path) -> bool { path.starts_with(layout.client_media_dir().join(workspace)) && !path .components() .any(|c| matches!(c, std::path::Component::ParentDir))}/// Called under the file's writer lock. Rules cannot change between the/// confirmation evaluation and unlink; sync and a foreground open take the/// same lock. Filesystem failures retain the row and are retried next pass.#[allow(clippy::too_many_arguments)]pubfn apply_in( db: &Driver, workspace: &str, device: &str, layout: &Layout, deps: &dynMediaEvictDeps, now_ms: i64, ids: &mutdynIdSource, held: Held, limit: usize,) -> Result<Applied, String> {let _backup = cotton_store::media_backup_lock::mutating(&layout.client_media_dir()) .map_err(|e| e.to_string())?;let plan = storage_rules::evaluate(db, workspace, device, now_ms).map_err(|e| e.to_string())?;letmut result = Applied::default();for candidate in plan.candidates.into_iter().take(limit) {let path = std::path::Path::new(&candidate.local_path);if !owned_original_path(layout, workspace, path) { result.errors.push(format!("{} is outside this device's media folder", candidate.key ));continue; }let removed = match deps.remove_file(path) {Ok(()) => true,Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,Err(e) => { result .errors .push(format!("{} could not be removed: {e}", candidate.key));continue; } };let now = cotton_store::protocol::js::to_iso_string(now_ms).ok_or("Storage date out of range")?;// The row and visible holding change together. No domain record is// removed and no undo can be offered for bytes fetched from the Mac. db.transaction(|db| {for key in &candidate.aliases { cotton_store::media_evict::mark_evicted(db, key, &now)?; cotton_store::media_holdings::drop_holding( db, workspace, device, key, cotton_store::media_holdings::Tier::Original, now_ms, ids, held, )?; }Ok(()) }) .map_err(|e| e.to_string())?;if removed { result.removed += 1; result.freed_bytes = result.freed_bytes.saturating_add(candidate.bytes as u64); } } result.rows = storage_rules::evaluate(db, workspace, device, now_ms) .map_err(|e| e.to_string())? .rows; storage_rules::publish(db, workspace, &result.rows, now_ms, ids, held) .map_err(|e| e.to_string())?;Ok(result)}/// Why one original stays on this device when the person asked it to go.#[derive(Debug, Clone, PartialEq, Eq)]pubenumEvictOneError {/// The bucket does not hold its bytes yet, so this device may hold the/// last copy.NotBackedUp,/// Another key names the same file and keeps it: it is pinned, or its/// row is being deleted.SharedFileKept(String),/// The ledger names a file outside this device's media folder.OutsideMediaFolder,/// The file or the ledger could not be changed.Failed(String),}impl std::fmt::DisplayforEvictOneError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {matchself {Self::NotBackedUp => f.write_str("its bytes are not backed up yet"),Self::SharedFileKept(key) => write!(f, "{key} keeps the same file"),Self::OutsideMediaFolder => f.write_str("its file is outside this device's media folder"),Self::Failed(why) => f.write_str(why), } }}/// The person's Remove download for ONE original: unpin `key` and take its/// file off this device, with every alias of that file. The budget pass/// ([`apply_in`]) never takes a pinned file, so a kept one leaves only here.////// Called under the file's writer lock, as [`apply_in`] is. The fence is the/// bucket: only a `synced` row goes, so this device never drops the last copy./// A content-addressed file is shared by every key that names its path, so/// each of them must also be unpinned and not mid-delete. Answers the bytes/// freed: none when the key has no row or no file here, or the file was/// already gone.#[allow(clippy::too_many_arguments)]pubfn evict_one( db: &Driver, workspace: &str, device: &str, layout: &Layout, deps: &dynMediaEvictDeps, key: &str, now_ms: i64, ids: &mutdynIdSource, held: Held,) -> Result<u64, EvictOneError> {let failed = |e: &dyn std::fmt::Display| EvictOneError::Failed(e.to_string());let _backup = cotton_store::media_backup_lock::mutating(&layout.client_media_dir()) .map_err(|e| failed(&e))?;let now = cotton_store::protocol::js::to_iso_string(now_ms) .ok_or_else(|| EvictOneError::Failed("Storage date out of range".into()))?;letSome(row) = cotton_store::media_ledger::media_by_key(db, key).map_err(|e| failed(&e))? else {returnOk(0); };letSome(local_path) = row.local_path else {// Nothing here to take; the keep ends all the same. cotton_store::media_ledger::set_media_pinned(db, key, false, &now).map_err(|e| failed(&e))?;returnOk(0); };if row.state != "synced" {returnErr(EvictOneError::NotBackedUp); }let path = std::path::Path::new(&local_path);if !owned_original_path(layout, workspace, path) {returnErr(EvictOneError::OutsideMediaFolder); }let rows = db .all("SELECT key, pinned, state FROM _media WHERE local_path = ? ORDER BY key", &[rusqlite::types::Value::Text(local_path.clone())], ) .map_err(|e| failed(&e))?;letmut aliases = Vec::with_capacity(rows.len());for alias in &rows {let alias_key = alias.text("key").unwrap_or_default().to_string();if alias_key != key && (alias.int("pinned") != Some(0) || alias.text("state") == Some("delete_pending")) {returnErr(EvictOneError::SharedFileKept(alias_key)); } aliases.push(alias_key); }let removed = match deps.remove_file(path) {Ok(()) => true,Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,Err(e) => returnErr(EvictOneError::Failed(format!("{key} could not be removed: {e}"))), };// The pin, the rows and the visible holdings change together. db.transaction(|db| { cotton_store::media_ledger::set_media_pinned(db, key, false, &now)?;for alias in &aliases { cotton_store::media_evict::mark_evicted(db, alias, &now)?; cotton_store::media_holdings::drop_holding( db, workspace, device, alias, cotton_store::media_holdings::Tier::Original, now_ms, ids, held, )?; }Ok(()) }) .map_err(|e| failed(&e))?;Ok(if removed { row.size_bytes.max(0) as u64 } else { 0 })}pubfn pass(replica: &Arc<Mutex<Replica>>, sweep: &EvictSweep, clock: &dynClock) -> EvictPass {letmut result = EvictPass::default();letSome(device) = sweep.device_key.get() else {return result; };letmut replicas = vec![Arc::clone(replica)];ifletSome(others) = &sweep.others { replicas.extend(others()); }letmut ids = crate::seams::op_ids(Arc::clone(&sweep.random));letmut seen = std::collections::BTreeSet::new();for replica in replicas {let replica = replica.lock().unwrap_or_else(|p| p.into_inner());if !seen.insert(replica.workspace_id.clone()) {continue; }match apply_in( &replica.driver, &replica.workspace_id, &device, &sweep.layout, sweep.deps.as_ref(), clock.now().timestamp_millis(), &mut ids,Held::Replica,64, ) {Ok(applied) => { result.removed += applied.removed; result.bytes += applied.freed_bytes; result.media_bytes += applied .rows .iter() .map(|r| r.held_bytes.max(0) as u64) .sum::<u64>();if applied.removed > 0 { result .removed_in .insert(replica.workspace_id.clone(), applied.removed); } result.last_error = applied.errors.last().cloned().or(result.last_error); }Err(e) => result.last_error = Some(e), } } result}#[cfg(test)]mod tests {usesuper::*; #[test]fn a_storage_pass_cannot_unlink_outside_its_media_directory() {let layout = Layout::new(std::path::PathBuf::from("/synthetic/storage")); assert!(owned_original_path( &layout,"db", &layout.client_media_dir().join("db/photos/a.jpg") )); assert!(!owned_original_path( &layout,"db", &layout.client_media_dir().join("../../life.db") )); assert!(!owned_original_path( &layout,"db", std::path::Path::new("/synthetic/storage/life.db") )); assert!(!owned_original_path( &layout,"db", &layout.thumbs_cache_dir().join("photo.jpg") )); }/// A phone holding one pinned book, synced or not, with its hold; answers/// the key and the file.fn a_kept_book( db: &Driver, layout: &Layout, workspace: &str, name: &str, state: &str, ids: &mutdynIdSource, ) -> (String, std::path::PathBuf) {let text = |s: &str| rusqlite::types::Value::Text(s.into()); db.run("INSERT OR IGNORE INTO cotton_devices (id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at) VALUES ('phone',?,'phone','Phone','2026-01-01','phone','2026-01-01','2026-01-01')",&[text(workspace)]).unwrap();let key = format!("{workspace}/books/{name}.epub");let path = layout.client_media_dir().join(workspace).join(format!("{name}.epub")); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, b"invented").unwrap(); db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,pinned) VALUES (?,?,'synthetic','application/epub+zip',8,?,?,'2026-01-01','2026-01-01',1)",&[text(&key),text(workspace),text(path.to_str().unwrap()),text(state)]).unwrap(); cotton_store::media_holdings::record_holding(db, workspace, "phone", &key, cotton_store::media_holdings::Tier::Original, 8, 1_791_331_200_000, ids, Held::Replica).unwrap(); (key, path) }fn row(db: &Driver, key: &str) -> cotton_store::media_ledger::MediaRow { cotton_store::media_ledger::media_by_key(db, key).unwrap().expect("the row") }// RULE: Remove download takes one kept original off this device only when its bytes are in the bucket: the file goes, the row stays with no path and no pin, and this device's hold is dropped. #[test]fn evict_one_takes_a_synced_kept_original_and_keeps_its_row() {let (_dir, layout, replica) = crate::test_support::open_test_replica();let (db, workspace) = (&replica.driver, replica.workspace_id.as_str());letmut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::default()));let (key, path) = a_kept_book(db, &layout, workspace, "dune", "synced", &mut ids);let freed = evict_one(db, workspace, "phone", &layout, &super::super::SystemEvictDisk, &key, 1_791_331_200_001, &mut ids, Held::Replica); assert_eq!(freed, Ok(8)); assert!(!path.exists());let after = row(db, &key); assert_eq!((after.local_path, after.pinned, after.state.as_str()), (None, false, "synced")); assert!(!cotton_store::media_holdings::is_live_hold(db, "phone", &key, cotton_store::media_holdings::Tier::Original).unwrap());// Asked again, nothing is here to take. assert_eq!(evict_one(db, workspace, "phone", &layout, &super::super::SystemEvictDisk, &key, 1_791_331_200_002, &mut ids, Held::Replica), Ok(0)); }// RULE: a kept original the bucket does not hold yet is never taken: this device may hold the last copy, so the file, its path and its pin all stay. #[test]fn evict_one_refuses_bytes_that_are_not_backed_up() {let (_dir, layout, replica) = crate::test_support::open_test_replica();let (db, workspace) = (&replica.driver, replica.workspace_id.as_str());letmut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::default()));let (key, path) = a_kept_book(db, &layout, workspace, "dune", "pending", &mut ids);let refused = evict_one(db, workspace, "phone", &layout, &super::super::SystemEvictDisk, &key, 1_791_331_200_001, &mut ids, Held::Replica); assert_eq!(refused, Err(EvictOneError::NotBackedUp)); assert!(path.exists());let after = row(db, &key); assert_eq!((after.local_path.as_deref(), after.pinned), (path.to_str(), true)); }// RULE: a file another key names is taken only when every key naming it lets it go; one pinned alias keeps the file and both rows as they were. #[test]fn evict_one_refuses_a_file_a_pinned_alias_keeps() {let (_dir, layout, replica) = crate::test_support::open_test_replica();let (db, workspace) = (&replica.driver, replica.workspace_id.as_str());letmut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::default()));let (key, path) = a_kept_book(db, &layout, workspace, "dune", "synced", &mut ids);let alias = format!("{workspace}/documents/dune.epub");let text = |s: &str| rusqlite::types::Value::Text(s.into()); db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,pinned) VALUES (?,?,'synthetic','application/epub+zip',8,?,'synced','2026-01-01','2026-01-01',1)",&[text(&alias),text(workspace),text(path.to_str().unwrap())]).unwrap();let refused = evict_one(db, workspace, "phone", &layout, &super::super::SystemEvictDisk, &key, 1_791_331_200_001, &mut ids, Held::Replica); assert_eq!(refused, Err(EvictOneError::SharedFileKept(alias.clone()))); assert!(path.exists()); assert!(row(db, &key).pinned);// Unpinned, the alias lets the file go and loses its path with it. cotton_store::media_ledger::set_media_pinned(db, &alias, false, "2026-01-02T00:00:00.000Z").unwrap();let freed = evict_one(db, workspace, "phone", &layout, &super::super::SystemEvictDisk, &key, 1_791_331_200_002, &mut ids, Held::Replica); assert_eq!(freed, Ok(8)); assert!(!path.exists()); assert_eq!(row(db, &alias).local_path, None); }// The pass recomputes from the ledger: an interrupted batch resumes and a// failed unlink leaves both the file and its bookkeeping intact. #[test]fn storage_pass_resumes_and_does_not_report_failed_unlinks_as_freed() {let (_dir, layout, replica) = crate::test_support::open_test_replica();let db = &replica.driver;let workspace = &replica.workspace_id;let text = |s: &str| rusqlite::types::Value::Text(s.into()); db.run("INSERT INTO cotton_devices (id,workspace_id,device_id,name,approved_at,approved_by_device,created_at,updated_at) VALUES ('phone',?,'phone','Phone','2026-01-01','phone','2026-01-01','2026-01-01'),('mac',?,'mac','Mac','2026-01-01','mac','2026-01-01','2026-01-01')",&[text(workspace),text(workspace)]).unwrap(); db.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) VALUES ('storage-serving',?,99,'mac','device:mac','2026-01-01')",&[text(workspace)]).unwrap();letmut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::default())); storage_rules::set_rule( db, workspace,"phone","photo","only_opened",1_791_331_200_000, &mut ids,Held::Replica, ) .unwrap();for n in [1, 2] {let key = format!("{workspace}/photos/{n}.jpg");let path = layout .client_media_dir() .join(workspace) .join(format!("{n}.jpg")); std::fs::create_dir_all(layout.client_media_dir().join(workspace)).unwrap(); std::fs::write(&path, b"invented").unwrap(); db.run("INSERT INTO _media (key,workspace_id,sha256,content_type,size_bytes,local_path,state,created_at,updated_at,tier) VALUES (?,?,'synthetic','image/jpeg',8,?,'synced','2026-01-01','2026-01-01','original')",&[text(&key),text(workspace),text(path.to_str().unwrap())]).unwrap(); db.run("INSERT INTO cotton_media_holdings (id,workspace_id,object_key,device_id,tier,bytes,created_at,updated_at) VALUES (?, ?, ?, 'mac','original',8,'2026-01-01','2026-01-01')",&[text(&key),text(workspace),text(&key)]).unwrap(); } #[derive(Debug)]structRefuses;implMediaEvictDepsforRefuses {fn remove_file(&self, _: &std::path::Path) -> std::io::Result<()> {Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) } }let failed = apply_in( db, workspace,"phone", &layout, &Refuses,1_791_331_200_001, &mut ids,Held::Replica,64, ) .unwrap(); assert_eq!(failed.removed, 0); assert_eq!(failed.freed_bytes, 0); assert_eq!(failed.errors.len(), 2); assert!(layout .client_media_dir() .join(workspace) .join("1.jpg") .exists());let disk = super::super::SystemEvictDisk;let first = apply_in( db, workspace,"phone", &layout, &disk,1_791_331_200_002, &mut ids,Held::Replica,1, ) .unwrap(); assert_eq!((first.removed, first.freed_bytes), (1, 8));let second = apply_in( db, workspace,"phone", &layout, &disk,1_791_331_200_003, &mut ids,Held::Replica,1, ) .unwrap(); assert_eq!((second.removed, second.freed_bytes), (1, 8));let third = apply_in( db, workspace,"phone", &layout, &disk,1_791_331_200_004, &mut ids,Held::Replica,64, ) .unwrap(); assert_eq!((third.removed, third.freed_bytes), (0, 0));// The background copy pass must not undo the keep rule on its next tick. assert!(super::super::hydrate::work_list(db, workspace, "phone", 20, 1_791_331_200_005) .unwrap() .0 .is_empty() ); storage_rules::set_rule( db, workspace,"phone","photo","all",1_791_331_200_006, &mut ids,Held::Replica, ) .unwrap(); assert_eq!(super::super::hydrate::work_list(db, workspace, "phone", 20, 1_791_331_200_007) .unwrap() .0 .len(),2 ); assert!(!layout .client_media_dir() .join(workspace) .join("1.jpg") .exists()); assert_eq!( db.get("SELECT COUNT(*) AS n FROM _media", &[]) .unwrap() .unwrap() .int("n"),Some(2) ); }}