Cotton code
770 lines · 30.8 KB · RustRaw
//! `cotton_media_holdings` — who holds which bytes.//!//! The table answers ONE question: *who can give me these bytes.* Everything//! phase 2 wants from it is a consequence of that one question —//!//! - a Mac's replicator asks [`objects_with_fewer_than`] for the originals that//!   fewer than two live KEEPERS hold — Macs that keep everything//!   ([`crate::storage_rules::KEEPS_EVERYTHING`]); a phone's copy, a rows-only//!   Mac's and the mirror bucket's are never one of the two (sync programme,//!   lane D, 12 Oct 2026: "the bucket is the store, not a holder") — and//!   pulls them until the answer is empty;//! - a phone's eviction pass asks [`holders_of`] before it deletes a file, and//!   refuses when this device is the only holder. **A phone never drops the//!   last copy of anything**, which is the sentence the Mac's leave refusal//!   already makes one layer up;//! - the Server view asks the same query for its one line: *"3 photos are on//!   one machine only."*//!//! ## A holding names a MACHINE, by its device key//!//! **`device_id` is the machine's DEVICE KEY id** — `cotton_devices.device_id`,//! the 43 characters the server admits the machine by, and the id every reader//! here joins on ([`LIVE_HOLDINGS`]). It is never the file's AUTHOR id//! (`_meta.device_id`, the id its ops are stamped with): a founding Mac's file//! is born `device:<ulid>` and so is a phone's replica, neither has a//! `cotton_devices` row, and a hold written under one is a row no reader can//! see — which is how a serving Mac once held eleven thousand originals that no//! standby was ever sent to copy (todo 77f48a68). So each machine is counted//! once, under the one id every reader already uses.//!//! **The store refuses a hold no reader could see.** [`record_holding`] and//! [`drop_holding`] refuse a `device_id` that is not a LIVE (unrevoked)//! `cotton_devices` row of that workspace ([`device_standing`]) — loudly,//! never an invisible row. A caller that can run before its own device row has//! folded (a founding Mac before its root row is written, a phone before its//! row arrives) asks [`device_standing`] first and skips, and its next pass//! records what this one could not.//!//! **One writer per row still holds**, and it is what makes plain LWW correct//! here so [`crate::fold::COLUMN_POLICIES`] needs no entry: every writer takes//! the id it writes under from its OWN identity (the server's `SelfDevice`,//! the client's device key), so only the machine holding that key ever writes//! its rows. A row about somebody else's disk would be a claim this machine//! cannot verify. An op that arrives from a peer is that peer writing its own//! rows, and it folds without passing through here at all.//!//! **Rows written under the author id are retired, not left as clutter.**//! [`retire_author_holdings`] marks `dropped_at` on every live hold this FILE//! wrote under its author id, when that id is no device row — the file's own//! rows, so still one writer — and hands them back so the caller can restate//! each one under its key.//!//! What follows from one writer per row is that a revocation is never a write//! to somebody else's rows. A revoked phone's holdings are stale and only that//! phone may write them, and it may never come back — so both readers here JOIN//! `cotton_devices` and exclude a device carrying a `revoked_at`. A revoke is//! therefore correct on every device the instant the device row folds, and the//! join is spelled ONCE ([`LIVE_HOLDINGS`]) so there cannot be a second answer//! to "who is a holder".//!//! The one exception is housekeeping, not a claim about a disk://! [`drop_revoked_holdings`] marks `dropped_at` on the live rows of a REVOKED//! device, which no reader counts already. Without it they sit live for ever —//! ten thousand on the owner's Personal under two Mac credentials revoked in//! October — and every count of "live rows" has to remember the join. It//! never touches a row of a device that is live.//!//! ## What the table cannot tell you//!//! It knows only what a device has RECORDED. An object nobody has ever recorded//! a hold for has no row here at all, so it is not "held by zero devices" — it//! is unknown, and [`objects_with_fewer_than`] cannot return it. The caller//! that wants "every original, and how many hold it" drives the walk from the//! records themselves and asks this module per object.//!//! No clock and no filesystem: every function takes `now_ms` from its caller,//! the way the rest of this crate does.use rusqlite::types::Value as SqlValue;use serde_json::json;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::actor::{Actor, JobName};use crate::mint::{changes_of, mint, Act, Held, History};use crate::outbox::{IdSource, LocalChange};use crate::protocol::js;use crate::protocol::types::OpKind;use crate::storage_rules::KEEPS_EVERYTHING;/// The table, spelled once.pub const TABLE: &str = "cotton_media_holdings";/// Which rendition of an object a hold is about.////// The `original` is the bytes as captured; `display` is the ~1600px rendition/// a detail view opens; `thumb` is the ~256px grid tile. All three are in the/// column's `CHECK` because the SHAPE is right, and phase 2 writes only/// `original`: the table's question is "who can give me these bytes", and it is/// only ever asked about originals and display renditions. A thumb is/// "everybody, eventually", answered locally off `_media`, and writing a row/// per thumb would triple the table for an answer nobody reads.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum Tier {    Thumb,    Display,    Original,}impl Tier {    /// Every tier, in the order the `CHECK` names them.    pub const ALL: [Tier; 3] = [Tier::Thumb, Tier::Display, Tier::Original];    /// What the column stores.    pub const fn as_str(self) -> &'static str {        match self {            Tier::Thumb => "thumb",            Tier::Display => "display",            Tier::Original => "original",        }    }    /// A tier read back off a row, or `None` for a word this build does not    /// know. `None` rather than a default: a row whose tier this build cannot    /// name is a row it must not act on.    pub fn parse(word: &str) -> Option<Tier> {        Tier::ALL.into_iter().find(|tier| tier.as_str() == word)    }}impl std::fmt::Display for Tier {    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        formatter.write_str(self.as_str())    }}/// One device that holds an object's bytes, live.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Holder {    /// `cotton_devices.device_id` — the key that may open this database.    pub device_id: String,    /// The device's own name, for the sentence a screen prints.    pub name: String,    /// What the holder says the file weighs.    pub bytes: i64,    /// The last time that device confirmed the file is really there.    pub verified_at: Option<String>,    /// Is the holder a KEEPER — a Mac that keeps everything    /// ([`crate::storage_rules::KEEPS_EVERYTHING`])? Only a keeper's copy lets    /// another device let its own go: a phone or a rows-only Mac may itself    /// let the bytes go tomorrow, so two of them could each be the other's    /// fence and both go.    pub keeps_everything: bool,}/// A hold's id, derived from its natural key.////// `hold:<tier>:<device_id>:<object_key>` — so a second record of the same hold/// is a restatement of ONE row rather than a second row, on any device, with no/// lookup first. The order puts the two short, bounded parts in front of the/// key, which is the only part that carries slashes.pub fn holding_id(device_id: &str, object_key: &str, tier: Tier) -> String {    format!("hold:{}:{device_id}:{object_key}", tier.as_str())}/// The live-holder join, spelled ONCE.////// Two exclusions, and both are load-bearing: `dropped_at IS NOT NULL` is a/// device that evicted the bytes, and `revoked_at IS NOT NULL` is a device that/// may never come back to say so itself. A second spelling of this anywhere/// would be a second answer to "who is a holder", and the one that forgot the/// revocation would be the one a phone trusted before deleting a file.const LIVE_HOLDINGS: &str = "FROM cotton_media_holdings h \     JOIN cotton_devices d \       ON d.workspace_id = h.workspace_id AND d.device_id = h.device_id \     WHERE h.dropped_at IS NULL AND d.revoked_at IS NULL";/// The ONE order for "what to copy" over a `GROUP BY h.object_key` of/// [`LIVE_HOLDINGS`]: NEWEST first by the object's first hold time, the key as/// a tie-break so the order is total.const WHAT_TO_COPY_FIRST: &str = "ORDER BY MIN(h.created_at) DESC, h.object_key";/// `EXISTS (…)`: a LIVE KEEPER (a Mac that keeps everything) OTHER than this/// device holds the object an outer `_media` row named `m` is about. Never the/// last copy: a phone's or a rows-only Mac's copy may go tomorrow too.////// The eviction pass's fence, as a correlated sub-select, so a screen asking/// "how much could go" is ONE statement rather than a lookup per candidate./// Built FROM [`LIVE_HOLDINGS`] rather than beside it: the module's whole rule/// is that there is one answer to "who is a holder", and a second spelling that/// forgot the revocation join would be the one a phone trusted before deleting/// a file.////// Two placeholders, in order: the tier, then the device to exclude. The outer/// query MUST alias `_media` as `m`.pub fn held_elsewhere_exists() -> String {    format!(        "EXISTS (SELECT 1 {LIVE_HOLDINGS} \           AND h.workspace_id = m.workspace_id AND h.object_key = m.key \           AND h.tier = ? AND h.device_id <> ? AND {KEEPS_EVERYTHING})"    )}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// Every holdings write, through `mint`, as this device's own job.////// The op ids used to be derived from the row (`op:<row>`) so a re-run could/// not queue a second copy. `cotton_media_holdings` travels like any handed-over/// table (it is not server-only; an adopt leaves its changes behind by name,/// `ADOPT_BOOKKEEPING`, QUEUE BAD OP 7): the derived row id carries the/// idempotence, so a second record of the same hold restates one row, and a/// fresh ulid per op is the right id.fn write(    db: &Driver,    verb: &str,    changes: &[LocalChange],    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<()> {    if changes.is_empty() {        return Ok(());    }    // Judged on the serving Mac's file, the wall clock on any other handle.    let clock = crate::mint::clock::writer_clock(db, now_ms, &mut *ids)?;    mint(        db,        &Act {            actor: Actor::DeviceJob(JobName::named("media-holdings")?),            verb: verb.to_string(),            history: History::None,            changes: changes_of(db, changes),        },        &clock,        ids,        held,    )?;    Ok(())}fn iso(now_ms: i64) -> Result<String> {    js::to_iso_string(now_ms)        .ok_or_else(|| StoreError::encode(format!("timestamp out of range: {now_ms}")))}/// Where a device stands in this workspace's `cotton_devices` — the question a/// hold is refused on.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum DeviceStanding {    /// An approved row with no `revoked_at`: every reader can see its holds.    Live,    /// A row that carries a `revoked_at`: nobody counts its holds.    Revoked,    /// No row at all — an author id, or a device whose row has not folded    /// here yet.    Absent,}/// Where `device_id` stands in `workspace_id`'s `cotton_devices`.pub fn device_standing(db: &Driver, workspace_id: &str, device_id: &str) -> Result<DeviceStanding> {    // `revoked_at IS NULL` — [`LIVE_HOLDINGS`]' own test, so a writer and    // every reader give ONE answer to "is this device revoked": any value at    // all, the empty string included, is a revocation.    let row = db.get(        "SELECT revoked_at IS NULL AS live FROM cotton_devices \         WHERE workspace_id = ? AND device_id = ?",        &[text(workspace_id), text(device_id)],    )?;    Ok(match row {        None => DeviceStanding::Absent,        Some(row) if row.int("live") == Some(1) => DeviceStanding::Live,        Some(_) => DeviceStanding::Revoked,    })}/// Refuse a hold no reader could see. See the module header.fn only_a_live_device(db: &Driver, workspace_id: &str, device_id: &str) -> Result<()> {    match device_standing(db, workspace_id, device_id)? {        DeviceStanding::Live => Ok(()),        DeviceStanding::Revoked => Err(StoreError::refused(format!(            "{device_id} is revoked in this database, so a holding it wrote is one nobody counts"        ))),        DeviceStanding::Absent => Err(StoreError::refused(format!(            "a holding names a machine by its device key, and {device_id} is no device of this \             database, so no reader could see the row"        ))),    }}/// What the row already says, if anything.struct Existing {    created_at: String,}fn existing(db: &Driver, id: &str) -> Result<Option<Existing>> {    Ok(db        .get(            "SELECT created_at FROM cotton_media_holdings WHERE id = ?",            &[text(id)],        )?        .map(|row| Existing {            created_at: row.text("created_at").unwrap_or_default().to_string(),        }))}/// Record that THIS device — named by its device key — holds these bytes, at/// this tier. Refused unless `device_id` is a live device of the workspace.////// A restatement, not an insert: the id is derived from the natural key, so/// recording the same hold twice folds onto one row and moves `verified_at`./// `created_at` is kept from the row that was already there, because the fact/// being restated is the same fact.////// It also clears `dropped_at`. A device that evicted these bytes and has them/// again is a holder again, and leaving the column set would make it invisible/// to every reader here for ever.////// The write goes through [`crate::mint::mint`], so the row carries an `_hlc` and/// travels: a holding nobody else can see answers nobody else's question./// Returns the row's id.#[allow(clippy::too_many_arguments)]pub fn record_holding(    db: &Driver,    workspace_id: &str,    device_id: &str,    object_key: &str,    tier: Tier,    bytes: i64,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<String> {    record(db, workspace_id, device_id, object_key, tier, bytes, None, now_ms, ids, held)}/// [`record_holding`] for a hold this machine has had since `first_held` — a/// hold [`retire_author_holdings`] handed back, restated under the device/// key. The row keeps the instant its object was FIRST held, because that is/// what the copy pass orders by ([`WHAT_TO_COPY_FIRST`]): eleven thousand/// restated originals stamped with one instant would be copied in key order.#[allow(clippy::too_many_arguments)]pub fn restate_holding(    db: &Driver,    workspace_id: &str,    device_id: &str,    object_key: &str,    tier: Tier,    bytes: i64,    first_held: &str,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<String> {    record(db, workspace_id, device_id, object_key, tier, bytes, Some(first_held), now_ms, ids, held)}#[allow(clippy::too_many_arguments)]fn record(    db: &Driver,    workspace_id: &str,    device_id: &str,    object_key: &str,    tier: Tier,    bytes: i64,    first_held: Option<&str>,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<String> {    only_a_live_device(db, workspace_id, device_id)?;    let id = holding_id(device_id, object_key, tier);    let stamp = iso(now_ms)?;    let created_at = existing(db, &id)?.map_or_else(        || first_held.filter(|at| !at.is_empty()).map_or_else(|| stamp.clone(), str::to_string),        |row| row.created_at,    );    let change = LocalChange {        delete: Default::default(),        kind: OpKind::Upsert,        table: TABLE.to_string(),        row_id: id.clone(),        patch: Some(            json!({                "id": id,                "workspace_id": workspace_id,                "object_key": object_key,                "device_id": device_id,                "tier": tier.as_str(),                "bytes": bytes,                "verified_at": stamp,                "dropped_at": serde_json::Value::Null,                "created_at": created_at,                "updated_at": stamp,            })            .as_object()            .expect("an object")            .clone(),        ),    };    write(db, "record_holding", &[change], now_ms, ids, held)?;    Ok(id)}/// This device — named by its device key — no longer holds these bytes./// Refused, like [`record_holding`], unless `device_id` is a live device.////// **A column, never a row delete.** "I had these bytes and I no longer do" is/// a fact the other devices need — it is what moves an object from two holders/// to one — and a delete would travel as a tombstone that says nothing about/// which object or which tier it was about once it has been pruned.////// Returns `false` when there was no hold to drop, which is not an error: a/// device evicting a file it never recorded is a device with nothing to say.#[allow(clippy::too_many_arguments)]pub fn drop_holding(    db: &Driver,    workspace_id: &str,    device_id: &str,    object_key: &str,    tier: Tier,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<bool> {    only_a_live_device(db, workspace_id, device_id)?;    let id = holding_id(device_id, object_key, tier);    if existing(db, &id)?.is_none() {        return Ok(false);    }    let stamp = iso(now_ms)?;    write(db, "drop_holding", &[dropped(&id, workspace_id, &stamp)], now_ms, ids, held)?;    Ok(true)}/// The one shape of "this hold is dropped": a column, never a row delete.fn dropped(id: &str, workspace_id: &str, stamp: &str) -> LocalChange {    LocalChange {        delete: Default::default(),        kind: OpKind::Upsert,        table: TABLE.to_string(),        row_id: id.to_string(),        patch: Some(            json!({                "id": id,                "workspace_id": workspace_id,                "dropped_at": stamp,                "updated_at": stamp,            })            .as_object()            .expect("an object")            .clone(),        ),    }}/// A hold [`retire_author_holdings`] dropped, handed back so the caller can/// restate it under the machine's device key when the bytes are still there.#[derive(Debug, Clone, PartialEq, Eq)]pub struct RetiredHold {    pub object_key: String,    pub tier: Tier,    pub bytes: i64,    /// When the object was first held — [`restate_holding`] keeps it.    pub created_at: String,}/// Retire every live hold THIS FILE wrote under its own AUTHOR id/// (`_meta.device_id`) — when that id is no `cotton_devices` row.////// Those rows are the ones written before a holding named a machine by its/// device key: no reader's join can see them, so they are clutter that says/// nothing — and they are this file's own rows, so dropping them keeps one/// writer per row. A file whose author id IS a device row (a joined Mac's is/// its key) has nothing to retire: its rows were always visible.////// `dropped_at`, never a delete, for [`drop_holding`]'s reason. Returns what/// was retired, so the caller restates each one under its key.////// AT MOST `limit` rows per call, so a first retirement of eleven thousand/// rows is many short writes rather than one long one; the caller calls again/// until it answers fewer than `limit`. A call on a level file still walks the/// author id's DROPPED rows (`idx_cotton_media_holdings_device` has no/// `dropped_at`), so a caller that runs every pass remembers, per open file,/// that it came back level and stops asking — nothing writes a hold under the/// author id any more ([`record_holding`] refuses it), so level stays level.pub fn retire_author_holdings(    db: &Driver,    workspace_id: &str,    limit: usize,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<Vec<RetiredHold>> {    let author = db        .get("SELECT device_id FROM _meta", &[])?        .and_then(|row| row.text("device_id").map(str::to_string))        .unwrap_or_default();    if author.is_empty() || device_standing(db, workspace_id, &author)? != DeviceStanding::Absent    {        return Ok(Vec::new());    }    let rows = db.all(        "SELECT id, object_key, tier, bytes, created_at FROM cotton_media_holdings \         WHERE workspace_id = ? AND device_id = ? AND dropped_at IS NULL \         ORDER BY object_key, tier LIMIT ?",        &[            text(workspace_id),            text(&author),            SqlValue::Integer(i64::try_from(limit).unwrap_or(i64::MAX)),        ],    )?;    if rows.is_empty() {        return Ok(Vec::new());    }    let stamp = iso(now_ms)?;    let mut changes = Vec::with_capacity(rows.len());    let mut retired = Vec::with_capacity(rows.len());    for row in &rows {        let (Some(id), Some(key)) = (row.text("id"), row.text("object_key")) else {            continue;        };        changes.push(dropped(id, workspace_id, &stamp));        // A tier this build cannot name is retired all the same — nobody could        // see the row — and simply not handed back to be restated.        if let Some(tier) = row.text("tier").and_then(Tier::parse) {            retired.push(RetiredHold {                object_key: key.to_string(),                tier,                bytes: row.int("bytes").unwrap_or(0),                created_at: row.text("created_at").unwrap_or_default().to_string(),            });        }    }    write(db, "retire_author_holdings", &changes, now_ms, ids, held)?;    Ok(retired)}/// Drop the live holds of every REVOKED device of this workspace — at most/// `limit` per call, so the caller calls again until it answers fewer.////// No live machine can hold what a revoked one recorded, and the revoked one/// may never come back to say so, so its rows are marked `dropped_at` (a/// column, never a delete). A device key that also has a live row is never/// touched: [`device_standing`] would call it live. Answers how many it dropped.pub fn drop_revoked_holdings(    db: &Driver,    workspace_id: &str,    limit: usize,    now_ms: i64,    ids: &mut dyn IdSource,    held: Held,) -> Result<usize> {    let rows = db.all(        "SELECT h.id FROM cotton_media_holdings h \         WHERE h.workspace_id = ? AND h.dropped_at IS NULL \           AND EXISTS (SELECT 1 FROM cotton_devices d WHERE d.workspace_id = h.workspace_id \                       AND d.device_id = h.device_id AND d.revoked_at IS NOT NULL) \           AND NOT EXISTS (SELECT 1 FROM cotton_devices d WHERE d.workspace_id = h.workspace_id \                           AND d.device_id = h.device_id AND d.revoked_at IS NULL) \         ORDER BY h.id LIMIT ?",        &[            text(workspace_id),            SqlValue::Integer(i64::try_from(limit).unwrap_or(i64::MAX)),        ],    )?;    if rows.is_empty() {        return Ok(0);    }    let stamp = iso(now_ms)?;    let changes: Vec<LocalChange> = rows        .iter()        .filter_map(|row| row.text("id"))        .map(|id| dropped(id, workspace_id, &stamp))        .collect();    write(db, "drop_revoked_holdings", &changes, now_ms, ids, held)?;    Ok(changes.len())}/// Every LIVE device that holds this object at this tier.////// Live means two things at once, and the query says both: the hold is not/// dropped, and the device is not revoked. Ordered by device id so a caller/// comparing two answers is comparing the same list.pub fn holders_of(    db: &Driver,    workspace_id: &str,    object_key: &str,    tier: Tier,) -> Result<Vec<Holder>> {    let sql = format!(        "SELECT h.device_id AS device_id, d.name AS name, h.bytes AS bytes, \                h.verified_at AS verified_at, {KEEPS_EVERYTHING} AS keeper \         {LIVE_HOLDINGS} AND h.workspace_id = ? AND h.object_key = ? AND h.tier = ? \         ORDER BY h.device_id"    );    Ok(db        .all(            &sql,            &[text(workspace_id), text(object_key), text(tier.as_str())],        )?        .iter()        .map(|row| Holder {            device_id: row.text("device_id").unwrap_or_default().to_string(),            name: row.text("name").unwrap_or_default().to_string(),            bytes: row.int("bytes").unwrap_or(0),            verified_at: row.text("verified_at").map(str::to_string),            keeps_everything: row.int("keeper") == Some(1),        })        .collect())}/// The objects at this tier that fewer than `holders` live KEEPERS hold — the/// replicator's work list, and the Server view's one line. A keeper is a Mac/// that keeps everything ([`KEEPS_EVERYTHING`]): an object a phone and a/// rows-only Mac both hold is still short of two, because neither promises to/// keep it.////// `objects_with_fewer_than(db, ws, 2, Tier::Original)` is "the originals that/// are on one machine only". It reads only what a device has RECORDED (see the/// module header): an object with no holdings row at all is unknown here rather/// than unheld, and cannot come back from this query.////// **NEWEST FIRST** — by the object's FIRST hold time (the earliest/// `created_at` among its holds), latest first, with the key as a tie-break so/// the order is total. The copy pass takes this order ([`WHAT_TO_COPY_FIRST`],/// one order for "what to copy"): a picture taken this week is the one a person/// opens next and the one with no second copy anywhere yet, while a library's/// old pictures have usually been on a disk somewhere for years. A media key is/// content-addressed, so key order alone would be effectively random.pub fn objects_with_fewer_than(    db: &Driver,    workspace_id: &str,    holders: i64,    tier: Tier,) -> Result<Vec<String>> {    let sql = format!(        "SELECT h.object_key AS object_key \         {LIVE_HOLDINGS} AND h.workspace_id = ? AND h.tier = ? \         GROUP BY h.object_key \         HAVING COUNT(DISTINCT CASE WHEN {KEEPS_EVERYTHING} THEN h.device_id END) < ? \         {WHAT_TO_COPY_FIRST}"    );    Ok(db        .all(            &sql,            &[                text(workspace_id),                text(tier.as_str()),                SqlValue::Integer(holders),            ],        )?        .iter()        .filter_map(|row| row.text("object_key").map(str::to_string))        .collect())}/// Whether `device_id` already has a live (not dropped) hold on this object/// at this tier — a point read on the row's derived id.////// The question a writer asks BEFORE restating a hold it may already have:/// [`record_holding`] is a restatement and would move `verified_at` and mint/// an op for a fact nobody's copy lacks. A sweep that walks a whole store/// every hour asks this first so that a level ledger costs reads, not writes./// A DROPPED row answers `false`: a device that evicted these bytes and has/// them again is a holder again, and saying so is the restatement.pub fn is_live_hold(db: &Driver, device_id: &str, object_key: &str, tier: Tier) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS held FROM cotton_media_holdings WHERE id = ? AND dropped_at IS NULL",            &[text(&holding_id(device_id, object_key, tier))],        )?        .is_some())}/// Every live (not dropped) hold `device_id` has in this workspace, at every/// tier, ordered by key then tier. `device_id` is the machine's device key.////// The question a device asks of its OWN rows when it reconciles them with/// its disk: a hold on bytes that are gone is a claim the ledger must stop/// making. Deliberately not joined to `cotton_devices` — these are the rows/// this device wrote, whatever the file now says about it.pub fn live_holds_of(    db: &Driver,    workspace_id: &str,    device_id: &str,) -> Result<Vec<(String, Tier)>> {    Ok(db        .all(            "SELECT object_key, tier FROM cotton_media_holdings \             WHERE workspace_id = ? AND device_id = ? AND dropped_at IS NULL \             ORDER BY object_key, tier",            &[text(workspace_id), text(device_id)],        )?        .iter()        .filter_map(|row| {            let key = row.text("object_key")?.to_string();            let tier = Tier::parse(row.text("tier")?)?;            Some((key, tier))        })        .collect())}/// Every object at this tier that a LIVE device OTHER than `device_id` holds —/// a standby Mac's work list, newest first — with what it weighs.////// [`objects_with_fewer_than`] asks "which originals are short of a second/// copy", which is the question for a household that wants two. A standby Mac/// asks a different one: it is a FULL copy, so it wants every object somebody/// else can give it, however many machines already hold it. The same join/// ([`LIVE_HOLDINGS`]) and the same order ([`WHAT_TO_COPY_FIRST`]), so a/// dropped hold and a revoked device are no source here for the reason they are/// no holder there — and an object only THIS device holds is not on the list,/// because there is nobody to ask for it.////// `device_id` is this machine's DEVICE KEY — the id its own holds name it by/// (module header). The weight is the largest any live holder recorded, so a/// pass can bound itself by bytes as well as by count.////// Like every reader here it sees only what a device has RECORDED; an object/// nobody ever recorded a hold for cannot come back from it.pub fn objects_held_elsewhere(    db: &Driver,    workspace_id: &str,    device_id: &str,    tier: Tier,) -> Result<Vec<(String, i64)>> {    let sql = format!(        "SELECT h.object_key AS object_key, MAX(h.bytes) AS bytes \         {LIVE_HOLDINGS} AND h.workspace_id = ? AND h.tier = ? AND h.device_id <> ? \         GROUP BY h.object_key \         {WHAT_TO_COPY_FIRST}"    );    Ok(db        .all(            &sql,            &[text(workspace_id), text(tier.as_str()), text(device_id)],        )?        .iter()        .filter_map(|row| {            let key = row.text("object_key")?.to_string();            Some((key, row.int("bytes").unwrap_or(0)))        })        .collect())}/// How many originals `device_id` holds that no OTHER live keeper holds — the/// count a Mac's copy may not be dropped over (`runner_change`).pub fn only_holder_of(db: &Driver, workspace_id: &str, device_id: &str) -> Result<i64> {    let sql = format!(        "SELECT COUNT(*) AS n FROM (SELECT DISTINCT h.workspace_id AS workspace_id, h.object_key AS key \           {LIVE_HOLDINGS} AND h.workspace_id = ? AND h.device_id = ? AND h.tier = 'original') m \         WHERE NOT {}",        held_elsewhere_exists()    );    Ok(db        .get(            &sql,            &[text(workspace_id), text(device_id), text(Tier::Original.as_str()), text(device_id)],        )?        .and_then(|row| row.int("n"))        .unwrap_or(0))}#[cfg(test)]#[path = "media_holdings_tests.rs"]mod tests;