//! This device's cache giving up the bytes of a record that was erased //! (groundwork slice 7, the client half). //! //! The store half decides WHICH keys: an erase folded here — pulled from a //! peer or written on this device — leaves a key DEAD when an erasure names it //! and no present or dormant row does, and queues it in this replica's own //! `_media_unlinks` (`cotton_store::media_erasure`). This pass drains that //! queue for every database this device holds, each replica against its OWN //! queue and its own folder of the device's media directory. //! //! **The wall is the store's** (`cotton_store::media_unlink::may_unlink_local`): //! a file is taken only when its key is under the erasing database's prefix, //! its ledger path is under `media//`, and no other ledger row //! names the same file — the store is content-addressed, and two keys with //! the same bytes share one file. //! //! **The order is the crash-safety.** The paths are read under the replica's //! lock, after the store's guard (`may_unlink_now`) has said the key is dead //! by the index AND by the holder columns read directly — a name only the //! direct read finds is written back, the key leaves the queue, and nothing //! goes; the files go with no lock held; then, under the lock again, the rule //! is asked once more and only a key still dead loses its ledger rows (the //! upload queue's entry with them), this device's holds, and its queue entry. //! A pass that died after the files went finds no ledger path the second //! time, removes nothing, and marks the key. //! //! **The index is rebuilt first, once per replica per process** //! (`media_keys::IndexRebuilt`, which [`UnlinkSweep`] carries and the shell //! keeps for the process): a replica moved by a build older than slice 7's store half has an //! empty `_media_key_names`, so before this pass reads a replica's queue for //! the first time it rebuilds that index from the rows, and the rebuild takes //! every key a row names out of the queue. A replica whose rebuild fails is not //! drained in that pass. //! //! **A key expands into its renditions**: the queue holds base keys, and the //! thumbnail and display copies are spelled from the digest — unless another //! key of the same digest is still named ([`objects_of_dead_key`]). use std::path::PathBuf; use std::sync::{Arc, Mutex}; use cotton_core::media::keys::{derived_tier_keys, is_derived_rendition, rendition_family}; use cotton_store::driver::Driver; use cotton_store::media_erasure::{ index_says_dead, index_says_family_dead, is_dead, is_family_dead, is_family_named, mark_unlinked, may_unlink_now, pending_unlinks, MayUnlink, Unlinked, }; use cotton_store::media_holdings::{drop_holding, Tier}; use cotton_store::media_ledger::delete_media_row; use cotton_store::media_unlink::{may_unlink_key, may_unlink_local}; use cotton_store::mint::Held; use cotton_store::outbox::IdSource; use rusqlite::types::Value as SqlValue; use crate::layout::Layout; use crate::replica::Replica; use crate::seams::Clock; /// The objects a dead `key`'s unlink takes: the key itself and each rendition /// derived from its digest — unless a present or dormant row names another key /// of the same family (`{sha}.heic` beside `{sha}.jpg`), which owns the same /// renditions. pub fn objects_of_dead_key(db: &Driver, key: &str) -> cotton_store::Result> { let mut objects = vec![key.to_string()]; if let Some(family) = rendition_family(key) { if !is_family_named(db, &family)? { objects.extend(derived_tier_keys(key)); } } Ok(objects) } /// Whether the bytes at `key` are dead in this replica: the key is dead, or /// it is a rendition of a family no row names any more and an erasure does. /// What hydrate, replicate and the upload queue ask before they move bytes. pub fn bytes_are_dead(db: &Driver, key: &str) -> cotton_store::Result { if is_derived_rendition(key) { return match rendition_family(key) { Some(family) => is_family_dead(db, &family), None => Ok(false), }; } is_dead(db, key) } /// WHAT A QUEUE THAT FETCHES BYTES ASKS, once per object, every pass: the /// dead-key rule as the index answers it (`index_says_dead`, and the family's /// for a rendition) — point reads, never [`bytes_are_dead`]'s second read. /// /// That second read (`media_keys::rows_naming`) is a scan of every holder /// table and every receipt of one, and it runs exactly when a key IS dead. /// A dead key stays on a fetch queue for as long as another device still /// holds its copy, so a work list that asked `bytes_are_dead` per object /// made that scan once per dead key on every pass, inside a hold of the file /// (11 Oct 2026: 17.5 million steps, 5.9 s, each minute, on a database whose /// pruned bundles two newly joined Macs still held). /// /// The scan guards against an index that missed a row, and here the index /// being wrong costs a fetch put off, never bytes: a key the index calls dead /// and a row names is not pulled until the index is repaired — the unlink /// pass rebuilds it at its first pass over each database — and nothing is /// deleted on this answer. Where bytes GO the scan is still asked. pub fn index_says_bytes_dead(db: &Driver, key: &str) -> cotton_store::Result { if is_derived_rendition(key) { return match rendition_family(key) { Some(family) => index_says_family_dead(db, &family), None => Ok(false), }; } index_says_dead(db, key) } /// Everything the pass needs that is not the replica. pub struct UnlinkSweep { pub layout: Layout, /// This device's KEY, read when the pass runs — the id its own holds name /// it by (`super::holds`). pub device_key: crate::identity::DeviceKey, /// The op ids a dropped hold is minted with come from here. pub random: Arc, /// The replicas whose media-key index this process rebuilt, by file id — /// the start step of [`unlink_pass`]. Shared, so the shell keeps one for /// the process however many drains it starts. pub indexed: Arc, /// Whether this copy holds every row it can know of now (the shell's: caught up in this generation, key held, no /// row parked). Bytes only here go only while it says so (ABSENCE 5, item 6). pub knows_every: Arc bool + Send + Sync>, } impl std::fmt::Debug for UnlinkSweep { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("UnlinkSweep") .field("root", &self.layout.root()) .finish_non_exhaustive() } } /// What one pass did, in one database. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct UnlinkPass { /// Dead keys whose bytes are gone here and are marked so. pub unlinked: usize, /// Files taken off this device for them. pub files: usize, /// Keys named again before their bytes went: nothing taken. pub alive_again: usize, /// Keys a row named that the media-key index had missed: nothing taken, /// the index repaired. Always a defect. pub repaired: usize, /// The names the start rebuild of the media-key index added, when this /// pass was the process's first over the replica; `None` after. pub indexed: Option, pub last_error: Option, } /// What the first look under the lock found for one queued key. enum Plan { /// Still dead: these files go, then the ledger and the queue are told. Unlink { objects: Vec, files: Vec }, /// Named again: nothing goes, and the mark takes it out of the queue. Keep, /// Bytes only on this device, not yet past their hold: nothing goes and the key stays queued. Wait, /// The index missed a row that names the key: nothing goes, and the store /// repaired the index and took the key out of the queue (a defect). Repaired(usize), /// Outside this database's prefix — the store never queues one. Not /// touched, and never marked as if its bytes were gone. Foreign, } /// How long a dead key whose bytes are only on this device (never taken by the server) waits before they go: a copy /// made again can fold an erase of the key under an old record before the new record naming it arrives (ABSENCE audit /// item 5), and bytes the server never took cannot be fetched back. pub const ONLY_HERE_HOLD_MS: i64 = 7 * 86_400_000; /// Whether any row this copy pulled is still parked unopened: a row naming the key may be among them. fn rows_parked(db: &Driver) -> cotton_store::Result { if db.get("SELECT 1 AS v FROM sqlite_master WHERE type = 'table' AND name = '_seal_parked'", &[])?.is_none() { return Ok(false); } Ok(db.get("SELECT 1 AS v FROM _seal_parked LIMIT 1", &[])?.is_some()) } fn plan_for(replica: &Replica, media_dir: &std::path::Path, key: &str, queued_at: &str, now_ms: i64, knows_every: &dyn Fn() -> bool) -> cotton_store::Result { let db = &replica.driver; let file = replica.file_id(); if !may_unlink_key(file, key) { return Ok(Plan::Foreign); } match may_unlink_now(db, key)? { MayUnlink::Yes => {} MayUnlink::Repaired(names) => return Ok(Plan::Repaired(names.len())), MayUnlink::Named | MayUnlink::NotDead => return Ok(Plan::Keep), } let objects = objects_of_dead_key(db, key)?; // Bytes the server never took (pending or failed upload), or a key this copy has no ledger row for at all: a // row naming it may not be here yet, and what goes cannot be fetched back. let mut only_here = false; for object in &objects { only_here |= cotton_store::media_ledger::media_by_key(db, object)?.is_none_or(|row| row.state == "pending" || row.state == "failed"); } if only_here { let queued = chrono::DateTime::parse_from_rfc3339(queued_at).map_or(now_ms, |at| at.timestamp_millis()); if now_ms.saturating_sub(queued) < ONLY_HERE_HOLD_MS || rows_parked(db)? || !knows_every() { return Ok(Plan::Wait); } } let mut files = Vec::new(); for object in &objects { if let Some(path) = may_unlink_local(db, file, media_dir, object)? { files.push(path); } } Ok(Plan::Unlink { objects, files }) } /// Drain ONE replica's unlink queue against this device's media directory. /// /// Synchronous and blocking, like the budget pass: SQLite and the filesystem. /// The replica's lock is taken per step and never across a file removal. pub fn unlink_pass(replica: &Arc>, sweep: &UnlinkSweep, clock: &dyn Clock) -> UnlinkPass { let media_dir = sweep.layout.client_media_dir(); let mut pass = UnlinkPass::default(); let identity = { let held = crate::sync::cycle::held(replica); sweep.indexed.pending_file(&held.driver) }; let rebuild = (|| -> cotton_store::Result> { let Some(identity) = identity? else { return Ok(None) }; let mut scan = cotton_store::media_keys::NameSweep::default(); let mut added = 0; loop { let page = { let held = crate::sync::cycle::held(replica); scan.rebuild_next(&held.driver)? }; match page { Some(count) => added += count, None => break } std::thread::yield_now(); } sweep.indexed.finish(identity); Ok(Some(added)) })(); match rebuild { Ok(added) => pass.indexed = added, Err(error) => { pass.last_error = Some(format!("the media-key index could not be rebuilt, so the unlink queue waits for the next pass: {error}")); return pass; } } let pending = { let held = crate::sync::cycle::held(replica); match pending_unlinks(&held.driver) { Ok(pending) => pending, Err(error) => { pass.last_error = Some(format!("the unlink queue could not be read: {error}")); return pass; } } }; let mut ids = crate::seams::op_ids(Arc::clone(&sweep.random)); for queued in pending { let key = queued.key; let plan = { let held = crate::sync::cycle::held(replica); plan_for(&held, &media_dir, &key, &queued.queued_at, clock.now().timestamp_millis(), &*sweep.knows_every) }; let (objects, files) = match plan { Ok(Plan::Unlink { objects, files }) => (objects, files), Ok(Plan::Keep) => (Vec::new(), Vec::new()), Ok(Plan::Repaired(names)) => { pass.repaired += 1; pass.last_error = Some(format!( "{key} was queued to unlink while {names} row(s) named it and the media-key \ index did not — nothing was taken, the index is repaired" )); continue; } Ok(Plan::Foreign | Plan::Wait) => continue, Err(error) => { pass.last_error = Some(format!("{key} could not be read: {error}")); continue; } }; // THE FILES FIRST, with no lock held. A file already gone is gone. if !files.is_empty() { let _backup = match cotton_store::media_backup_lock::mutating(&media_dir) { Ok(guard) => guard, Err(error) => { pass.last_error = Some(format!("a backup holds the media directory: {error}")); return pass; } }; let mut failed = false; for path in &files { match std::fs::remove_file(path) { Ok(()) => pass.files += 1, Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => { pass.last_error = Some(format!("{} could not be removed: {error}", path.display())); failed = true; } } } if failed { // Not marked: the next pass tries the file again. continue; } } let held = crate::sync::cycle::held(replica); let now = clock.now_iso(); let now_ms = clock.now().timestamp_millis(); let outcome = settle(&held, sweep.device_key.get().as_deref(), &key, &objects, &now, now_ms, &mut ids); match outcome { Ok(Unlinked::Done) => pass.unlinked += 1, Ok(Unlinked::AliveAgain) => pass.alive_again += 1, Ok(Unlinked::NotQueued) => {} Err(error) => pass.last_error = Some(format!("{key} could not be marked: {error}")), } } pass } /// Under the lock, after the files: ask the rule once more, and only for a /// key still dead drop its ledger rows (the upload queue's entry among them) /// and this device's holds on its objects, then mark it. fn settle( replica: &Replica, device_key: Option<&str>, key: &str, objects: &[String], now: &str, now_ms: i64, ids: &mut dyn IdSource, ) -> cotton_store::Result { let db = &replica.driver; if !objects.is_empty() && is_dead(db, key)? { for object in objects { delete_media_row(db, object)?; } drop_own_holds(db, &replica.workspace_id, device_key, objects, now_ms, ids)?; } mark_unlinked(db, key, now) } /// This device's live holds on `objects`, at any tier, set `dropped_at`. /// Nothing while this device may not hold here. fn drop_own_holds( db: &Driver, workspace_id: &str, device_key: Option<&str>, objects: &[String], now_ms: i64, ids: &mut dyn IdSource, ) -> cotton_store::Result { let device_id = match super::holds::holder_in(db, workspace_id, device_key) { Ok(Ok(device_id)) => device_id, Ok(Err(_)) | Err(_) => return Ok(0), }; let mut dropped = 0usize; for object in objects { let rows = db.all( "SELECT tier FROM cotton_media_holdings \ WHERE workspace_id = ? AND device_id = ? AND object_key = ? AND dropped_at IS NULL", &[ SqlValue::Text(workspace_id.to_string()), SqlValue::Text(device_id.clone()), SqlValue::Text(object.clone()), ], )?; for tier in rows.iter().filter_map(|row| row.text("tier").and_then(Tier::parse)) { if drop_holding(db, workspace_id, &device_id, object, tier, now_ms, ids, Held::Replica)? { dropped += 1; } } } Ok(dropped) } #[cfg(test)] #[path = "unlink_tests.rs"] mod tests;