//! Media leaves when its last record goes (groundwork slice 7, store half). //! //! **An Erase writes one `cotton_media_erasures` fact per key** that the //! erased record and its owned descendants — dormant ones included — name //! ([`with_erasure_facts`], asked by `mint` in the erase's own act, so the //! facts are stamped by the writer's author under the act's actor, in the //! same transaction). A fact's id is derived from `(key, record_table, //! record_id)`, never from the key alone: an erasure is of a record, and the //! same bytes added again under a new record are a new life. //! //! **A key is DEAD in this database when an erasure fact names it and no //! present or dormant row names it** ([`is_dead`], read through //! `_media_key_names`, `crate::media_keys`). Only a dead key may lose its //! bytes. A key named again later — a new record referencing it — is alive //! again: the fact stays, and the rule answers alive. //! //! **Each device keeps its own UNLINK QUEUE**, `_media_unlinks` (local, never //! synced). The queue is a list of CANDIDATES and entering it deletes //! nothing: a key enters when THE INDEX says it is dead ([`index_says_dead`], //! two point reads), and the rows themselves are read once, by //! [`may_unlink_now`], before any bytes go. The fold never reads the rows — //! see [`index_says_dead`] for what that cost. A key enters when it turns dead here — an erasure fact taken //! (written locally or folded from a peer, [`fact_folded`], the hook in //! `fact_hooks`) or an erase dropping the last names of a key an erasure //! already holds ([`names_dropped`]) — and only when //! `media_unlink::may_unlink_key` allows it for this file: a key outside this //! database's prefix never enters. A row that names a queued key again //! takes it out ([`named_again`]): a re-reference before the unlink wins. The //! server and client halves read [`pending_unlinks`], remove the bytes, and //! call [`mark_unlinked`], which asks the rule again in its own transaction. use std::collections::BTreeSet; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value as JsonValue}; use crate::canonical::{Kind, Receipt}; use crate::driver::Driver; use crate::error::{Result, StoreError}; use crate::mint::{Act, Change}; use crate::protocol::derived_id::derived_id; /// The fact table of media erasures. pub const MEDIA_ERASURES_TABLE: &str = "cotton_media_erasures"; /// The id of the erasure of `key` as `record_table`'s `record_id` named it. pub fn erasure_id(key: &str, record_table: &str, record_id: &str) -> String { derived_id(MEDIA_ERASURES_TABLE, &[key, record_table, record_id]) } /// Whether an erasure fact names `key`. pub fn is_erased(db: &Driver, key: &str) -> Result { Ok(db .get( "SELECT 1 AS erased FROM cotton_media_erasures WHERE key = ? LIMIT 1", &[SqlValue::Text(key.to_string())], )? .is_some()) } /// THE DEAD-KEY RULE: an erasure names `key` and no present or dormant row /// does — by the index, and, when the index says none, by the holder columns /// and receipts themselves (`media_keys::rows_naming`), so a file whose index /// missed a row never calls that row's key dead. The second read costs only /// for a key an erasure names and the index does not. pub fn is_dead(db: &Driver, key: &str) -> Result { Ok(is_erased(db, key)? && !crate::media_keys::is_named(db, key)? && crate::media_keys::rows_naming(db, key)?.is_empty()) } /// THE DEAD-KEY RULE AS THE INDEX ANSWERS IT: an erasure names `key` and /// `_media_key_names` holds no name of it. Two point reads, each on an index. /// /// **THIS, AND NOT [`is_dead`], IS WHAT THE FOLD ASKS.** `is_dead`'s 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, which is every /// erasure fact of an ordinary erase. Asked per folded fact it is /// O(facts × media rows) inside the fold's transaction: on 10 Oct 2026 one /// write that erased a few hundred keys held the owner's store lock for more /// than ten minutes on a database of 28,000 media rows, and every other /// handler waited behind it. The scan is the guard against an index that /// missed a row, and that guard belongs where bytes go — [`may_unlink_now`], /// once per key, outside the fold — not where a key is merely written down /// as a candidate. pub fn index_says_dead(db: &Driver, key: &str) -> Result { Ok(is_erased(db, key)? && !crate::media_keys::is_named(db, key)?) } /// [`index_says_dead`] for a FAMILY's renditions: an erasure names a key of /// `family` and `_media_key_names` holds no name of any. Two range reads, each /// on an index; a family this crate cannot read as one is not dead. pub fn index_says_family_dead(db: &Driver, family: &str) -> Result { let Some((from, to)) = family_range(family) else { return Ok(false); }; let within = |table: &str| -> Result { Ok(db .get( &format!("SELECT 1 AS found FROM {table} WHERE key >= ? AND key < ? LIMIT 1"), &[SqlValue::Text(from.clone()), SqlValue::Text(to.clone())], )? .is_some()) }; Ok(within(MEDIA_ERASURES_TABLE)? && !within("_media_key_names")?) } /// The key range of a FAMILY — a prefix ending in `.`, spelled by /// `cotton_core::media::keys::rendition_family`, which this crate cannot /// name. `/` is the byte after `.`, so `[family, family/)` is every key that /// starts with it, and both ends ride the `key` index. fn family_range(family: &str) -> Option<(String, String)> { let stem = family.strip_suffix('.')?; Some((family.to_string(), format!("{stem}/"))) } /// Whether any present or dormant row names a key of `family` — the /// question before an unlink takes a rendition, which every key of the same /// digest shares. A family this crate cannot read as one answers `true`: /// named, so nothing is taken. Asked of the index, and, when it says none, of /// the holder columns and receipts themselves, as [`is_dead`] is. pub fn is_family_named(db: &Driver, family: &str) -> Result { is_family_named_read(db, family, None) } /// [`is_family_named`], with the rows already read for the whole pass /// (`media_keys::RowsRead`): the index is asked now, and the rows are read /// again only when the pass's read says one names the family. pub fn is_family_named_read(db: &Driver, family: &str, rows: Option<&crate::media_keys::RowsRead>) -> Result { let Some((from, to)) = family_range(family) else { return Ok(true); }; let indexed = db .get( "SELECT 1 AS named FROM _media_key_names WHERE key >= ? AND key < ? LIMIT 1", &[SqlValue::Text(from), SqlValue::Text(to)], )? .is_some(); if indexed { return Ok(true); } if rows.is_some_and(|rows| !rows.names_family(family)) { return Ok(false); } Ok(!crate::media_keys::rows_naming_family(db, family)?.is_empty()) } /// Whether a family's renditions are dead bytes: an erasure names a key of /// it and no present or dormant row names any key of it. pub fn is_family_dead(db: &Driver, family: &str) -> Result { let Some((from, to)) = family_range(family) else { return Ok(false); }; let erased = db .get( "SELECT 1 AS erased FROM cotton_media_erasures WHERE key >= ? AND key < ? LIMIT 1", &[SqlValue::Text(from), SqlValue::Text(to)], )? .is_some(); Ok(erased && !is_family_named(db, family)?) } /// `act` with one erasure fact after each Erase in it, per key the erased /// record and its owned descendants name, and after each RELEASE (a change /// setting a `MEDIA_KEY_RELEASES` column), per key the row named — or `None` /// when the act erases and releases nothing that names a key. A fact the act already carries, or this file /// already holds, is not written twice. pub(crate) fn with_erasure_facts(db: &Driver, act: &Act, workspace_id: &str, at_ms: i64) -> Result> { let erases = |change: &Change| change.kind == Kind::Retract && change.delete.as_ref().and_then(crate::mint::Delete::erase_reason).is_some(); if !act.changes.iter().any(|change| erases(change) || releases(change)) { return Ok(None); } let erased_at = crate::protocol::js::to_iso_string(at_ms) .ok_or_else(|| StoreError::encode(format!("timestamp out of range: {at_ms}")))?; let actor = act.actor.to_wire(); let mut written: BTreeSet = act .changes .iter() .filter(|change| change.table == MEDIA_ERASURES_TABLE) .map(|change| change.row_id.clone()) .collect(); // What the act's erased rows own, read once for the act: asked a row at a // time it is a pass over the receipts per erased row, inside the file. let erased: Vec<(String, String)> = act.changes.iter().filter(|change| erases(change)).map(|change| (change.table.clone(), change.row_id.clone())).collect(); let owned = crate::erase::Owned::of(db, &erased)?; let mut changes = Vec::with_capacity(act.changes.len()); let mut added = false; for change in &act.changes { changes.push(change.clone()); let rows = if erases(change) { let mut rows = owned.descendants(db, &change.table, &change.row_id)?; rows.push((change.table.clone(), change.row_id.clone())); rows } else if releases(change) { // A RELEASE: the row stays and lets its bytes go, so its own keys // — read before the change lands, and none if it is released // already — are erased as an Erase's would be. vec![(change.table.clone(), change.row_id.clone())] } else { continue; }; for (table, row_id) in &rows { let held = owned.key_names(db, table, row_id)?; for key in crate::media_keys::keys_named_with(db, table, row_id, held)? { let id = erasure_id(&key, table, row_id); if !written.insert(id.clone()) || holds_fact(db, &id)? { continue; } let fields = json!({ "id": id, "workspace_id": workspace_id, "key": key, "record_table": table, "record_id": row_id, "erased_at": erased_at, "actor": actor, }); let JsonValue::Object(patch) = fields else { unreachable!("a json! object literal is an object") }; changes.push(Change::create(MEDIA_ERASURES_TABLE, &id, patch)); added = true; } } } if !added { return Ok(None); } Ok(Some(Act { actor: act.actor.clone(), verb: act.verb.clone(), history: act.history, changes, })) } /// Whether `change` sets its table's release column /// (`media_keys::MEDIA_KEY_RELEASES`) to a value. fn releases(change: &Change) -> bool { change.kind != Kind::Retract && change.patch.as_ref().is_some_and(|patch| { crate::media_keys::is_released(&change.table, |column| patch.get(column)) }) } fn holds_fact(db: &Driver, id: &str) -> Result { Ok(db .get( "SELECT 1 AS held FROM cotton_media_erasures WHERE id = ?", &[SqlValue::Text(id.to_string())], )? .is_some()) } /// The ISO moment of an HLC stamp `::`. fn moment_of(stamp: &str) -> String { stamp .split(':') .next() .and_then(|ms| ms.parse::().ok()) .and_then(crate::protocol::js::to_iso_string) .unwrap_or_else(|| stamp.to_string()) } /// Queue `key` when the index says it is dead here ([`index_says_dead`]) and /// this file may unlink it. A key already queued stays as it is. Point reads /// only: this runs inside the fold, once per erasure fact and once per name /// an erase drops. fn queue_if_dead(db: &Driver, key: &str, at: &str) -> Result<()> { if !index_says_dead(db, key)? { return Ok(()); } let Some(identity) = crate::file_identity::read_file_identity(db)? else { return Ok(()); }; if !crate::media_unlink::may_unlink_key(identity.id(), key) { return Ok(()); } db.run( "INSERT INTO _media_unlinks (key, queued_at) VALUES (?, ?) ON CONFLICT(key) DO NOTHING", &[SqlValue::Text(key.to_string()), SqlValue::Text(at.to_string())], )?; Ok(()) } /// THE MEDIA-ERASURE HOOK (`fact_hooks`): an erasure fact was taken, written /// here or folded from a peer, so its key is queued if it is dead. pub(crate) fn fact_folded(db: &Driver, fact: &Receipt) -> Result<()> { let Some(key) = fact.fields.get("key").and_then(JsonValue::as_str) else { return Ok(()); }; queue_if_dead(db, key, &moment_of(&fact.stamp)) } /// An erase took the names of `keys` (`erase::apply`): each one an erasure /// already names, and nothing names now, is queued — whichever of the erase /// and its facts a device folds first. pub(crate) fn names_dropped(db: &Driver, keys: &BTreeSet, stamp: &str) -> Result<()> { let at = moment_of(stamp); for key in keys { queue_if_dead(db, key, &at)?; } Ok(()) } /// A row named `keys` again (`fact_hooks::row_taken`): each leaves the /// queue, so a re-reference before the unlink keeps the bytes. pub(crate) fn named_again(db: &Driver, keys: &BTreeSet) -> Result<()> { for key in keys { // not a copy: _media_unlinks, the bytes this device may free, derived from the rows. db.run("DELETE FROM _media_unlinks WHERE key = ?", &[SqlValue::Text(key.clone())])?; } Ok(()) } /// One dead key waiting for its bytes to go. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PendingUnlink { pub key: String, pub queued_at: String, } /// Every queued key whose bytes are not yet gone, oldest first. pub fn pending_unlinks(db: &Driver) -> Result> { Ok(db .all( "SELECT key, queued_at FROM _media_unlinks WHERE done_at IS NULL ORDER BY queued_at, key", &[], )? .iter() .map(|row| PendingUnlink { key: row.text("key").unwrap_or_default().to_string(), queued_at: row.text("queued_at").unwrap_or_default().to_string(), }) .collect()) } /// What [`mark_unlinked`] found. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Unlinked { /// The key is dead and is now marked done at the moment given. Done, /// A row names the key (again): it is not marked, and it is not in the /// queue. Bytes already removed must be fetched or uploaded again. AliveAgain, /// The key is not named, and the queue holds no pending entry for it. NotQueued, } /// What [`may_unlink_now`] found, before any bytes are touched. #[derive(Debug, Clone, PartialEq, Eq)] pub enum MayUnlink { /// Dead by the index and by the rows themselves: the bytes may go. Yes, /// A row names the key in the index: nothing goes, and it left the queue. Named, /// THE INDEX MISSED A ROW: `_media_key_names` holds no name of the key and /// a holder column or a held receipt names it. Nothing goes, the missing /// names are written, and the key left the queue — a defect, never a /// normal path. Carries the names written. Repaired(Vec), /// No erasure names the key, or it is not queued: nothing goes. NotDead, } /// Whether a row names `key`, asked of the index and then, independently, of /// the holder columns and receipts. A name only the second read finds is /// written into the index, the key leaves the queue, and the defect is said /// out loud — it means a path put rows in this file around `row_taken`. /// /// `rows` is the pass's one read of every row (`media_keys::RowsRead`), when /// it made one: a key that read does not name is not read for again, and one /// it does name is read again HERE, now — the row may be gone since. fn named_or_repaired(db: &Driver, key: &str, rows: Option<&crate::media_keys::RowsRead>) -> Result> { if crate::media_keys::is_named(db, key)? { // not a copy: _media_unlinks, the bytes this device may free, derived from the rows. db.run("DELETE FROM _media_unlinks WHERE key = ?", &[SqlValue::Text(key.to_string())])?; return Ok(Some(MayUnlink::Named)); } if rows.is_some_and(|rows| !rows.names(key)) { return Ok(None); } let names = crate::media_keys::rows_naming(db, key)?; if names.is_empty() { return Ok(None); } crate::media_keys::insert_names(db, &names)?; // not a copy: _media_unlinks, the bytes this device may free, derived from the rows. db.run("DELETE FROM _media_unlinks WHERE key = ?", &[SqlValue::Text(key.to_string())])?; let rows: Vec = names.iter().map(|(_, table, row_id)| format!("{table} {row_id}")).collect(); eprintln!( "cotton: DEFECT — {key} was queued to unlink while {} named it and _media_key_names did not; \ nothing was deleted, the names are written again and the key left the queue", rows.join(", ") ); Ok(Some(MayUnlink::Repaired(names.into_iter().collect()))) } /// THE LAST QUESTION BEFORE BYTES GO — a guard, asked by every pass that /// deletes (`cotton-server` and `cotton-client`'s `media/unlink.rs`) before it /// deletes anything for `key`: the key must be queued and dead by the index, /// AND no present row's holder column and no held receipt may name it, read /// directly. A name only the direct read finds is repaired and reported /// ([`MayUnlink::Repaired`]), because an index that missed a row would /// otherwise delete bytes a record still uses. pub fn may_unlink_now(db: &Driver, key: &str) -> Result { may_unlink_read(db, key, None) } /// [`may_unlink_now`] for a pass that read every row ONCE /// (`media_keys::RowsRead`) rather than once per key: the same question and /// the same answers, with the direct read taken from `rows`. pub fn may_unlink_read(db: &Driver, key: &str, rows: Option<&crate::media_keys::RowsRead>) -> Result { db.transaction(|db| { if let Some(found) = named_or_repaired(db, key, rows)? { return Ok(found); } let queued = db .get( "SELECT 1 AS queued FROM _media_unlinks WHERE key = ? AND done_at IS NULL", &[SqlValue::Text(key.to_string())], )? .is_some(); if !queued || !is_erased(db, key)? { return Ok(MayUnlink::NotDead); } Ok(MayUnlink::Yes) }) } /// Mark `key`'s bytes gone at `at` — asking the dead-key rule again in the /// same transaction, of the index and of the rows directly, and refusing /// ([`Unlinked::AliveAgain`]) when a row names the key now. pub fn mark_unlinked(db: &Driver, key: &str, at: &str) -> Result { mark_unlinked_read(db, key, at, None) } /// [`mark_unlinked`] for a pass that read every row once — see /// [`may_unlink_read`]. pub fn mark_unlinked_read( db: &Driver, key: &str, at: &str, rows: Option<&crate::media_keys::RowsRead>, ) -> Result { db.transaction(|db| { if named_or_repaired(db, key, rows)?.is_some() { return Ok(Unlinked::AliveAgain); } let queued = db .get( "SELECT 1 AS queued FROM _media_unlinks WHERE key = ? AND done_at IS NULL", &[SqlValue::Text(key.to_string())], )? .is_some(); // The index and the rows have both just been asked and neither names // it (`named_or_repaired`), so what is left of the dead-key rule is // the erasure — asked alone, never as `is_dead`, which would read the // rows a second time. if !queued || !is_erased(db, key)? { return Ok(Unlinked::NotQueued); } db.run( "UPDATE _media_unlinks SET done_at = ? WHERE key = ?", &[SqlValue::Text(at.to_string()), SqlValue::Text(key.to_string())], )?; Ok(Unlinked::Done) }) }