Cotton code
656 lines · 27.3 KB · RustRaw
//! WHO MAY HOLD A RECORD: the only-you audience, and the one judge that reads it.//!//! Architect's ruling, 14 Oct 2026 (the databases ruling's "only-you audience//! held at admit"): a record of a shared database marked only-you is held by//! NOBODY BUT THE OWNER, ON ANY DEVICE, EVER — the serving Mac never admits it//! into another device's exchange, a device that is not the owner's never//! holds it, and only the owner releases it; from the release on it travels//! like any other record.//!//! The value lives in `cotton_audiences` (`crate::schema::ddl::AUDIENCES_TABLE`)://! one row per record, `only_you` or `everyone`. A record with no row is//! everyone's, as every record always was.//!//! ONE JUDGE ([`Holds`]), read wherever a row could leave the owner's devices.//! It is asked through the keep judge (`crate::keep::Keep`), so every path that//! already asks what a device keeps obeys it without a second list: an//! exchange answer ([`crate::keep::Keep::leave_out`]), a record opened by name//! ([`crate::keep::open`]), a table fetched for a widened rule//! ([`crate::keep::open_table`]) and a device's first copy//! ([`crate::keep::cut_copy`]). A device that is the owner's holds everything;//! any other device — a member's phone or Mac, or a device this file cannot//! place — is judged, and a held row is NEVER on it.//!//! What a hold covers: the record's own row; every row it owns//! (`OWNING_REFS`, transitively — a checklist's items, a comment's replies);//! every row that NAMES it ([`NAMED_BY`] — a link, a comment, its history, an//! album item); and the audience row itself, whose very existence names the//! record. A delete of a held row is held too: a member never had the row, and//! even its id is the owner's.//!//! THE SAME RULE AT THE FOLD ([`refusal`]), for a write minted here or handed//! over by a device: a device that is not the owner's never writes a held row//! and never writes an audience; only-you is chosen before anyone else can hold//! the record — a record already in a file that admits another person's//! device is refused the mark; and only the owner, at one of their own//! devices, RELEASES — an assistant, a job or an automation never does.//! The phone runs this same fold on its own mints, so a held record never//! leaves an owner's phone for a peer that is not the owner's.use std::collections::BTreeSet;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value as JsonValue};use crate::actor::Actor;use crate::driver::Driver;use crate::error::Result;use crate::mint::Change;use crate::protocol::derived_id::audience_id;use crate::protocol::types::{CottonOp, OpKind};use crate::schema::table_specs::OWNING_REFS;/// The audiences' own table.pub const TABLE: &str = "cotton_audiences";/// Held on the database owner's devices alone.pub const ONLY_YOU: &str = "only_you";/// Released: the record travels to every member.pub const EVERYONE: &str = "everyone";/// Every audience a row may carry. A CODE rule, not a CHECK: a new audience/// never widens a synced CHECK.pub const AUDIENCES: &[&str] = &[ONLY_YOU, EVERYONE];/// What a write of a held row from another device is refused with.pub const HELD_REFUSAL: &str =    "is only-you: the database owner's devices hold it, and no other device writes it";/// What an audience written from a device that is not the owner's is refused with.pub const ONLY_THE_OWNER_SETS: &str = "only the database owner's own devices set a record's audience";/// What a release by anybody but the owner is refused with.pub const ONLY_THE_OWNER_RELEASES: &str =    "only the owner releases an only-you record, at one of their own devices — an assistant, a job or an automation never does";/// What a late mark is refused with.pub const ALREADY_SHARED: &str =    "is already in a database another person's device holds; only-you is chosen when a record is made, before anyone else can hold it";/// What an audience row's delete is refused with.pub const NEVER_DELETED: &str = "an audience is never deleted: an only-you record is released, and a released one stays released";/// The rows that NAME a record without being owned through `OWNING_REFS`:/// `(table, the column naming the record)`. With [`crate::erase::OWNED_BY`]/// (links, project links, album items, faces, sightings, attachments) these/// are every row that would carry a held record's id or words to a member: a/// comment on it, its history, its place in a group, an assistant run on it.pub static NAMED_BY: &[(&str, &str)] = &[    ("cotton_comments", "record_id"),    ("cotton_changes", "record_id"),    ("cotton_group_members", "record_id"),    ("cotton_assistant_runs", "record_id"),];/// No chain of owners is this deep; a row that claims one is held.const MAX_DEPTH: usize = 16;fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// Is `device_key` one of the database owner's own devices, as this file says?////// A live approval in `cotton_devices` naming no person key, and no device/// statement making it a member's. Anything else — a member's device, a/// revoked one, a device this file holds no row for — is NOT: the judge fails/// closed, because a held row sent to a device that turns out to be the/// owner's costs a fetch, and one sent to a device that is not costs the owner.pub fn owners_device(db: &Driver, device_key: &str) -> Result<bool> {    let row = db.get(        "SELECT person_key, revoked_at FROM cotton_devices WHERE device_id = ? \         ORDER BY (revoked_at IS NULL) DESC, approved_at DESC, id ASC LIMIT 1",        &[text(device_key)],    )?;    let Some(row) = row else {        return Ok(false);    };    if row.text("revoked_at").is_some_and(|at| !at.is_empty()) {        return Ok(false);    }    if row.text("person_key").is_some_and(|key| !key.trim().is_empty()) {        return Ok(false);    }    Ok(db        .get("SELECT 1 AS x FROM cotton_device_statements WHERE device_key = ? LIMIT 1", &[text(device_key)])?        .is_none())}/// The device that wrote a receipt stamped `hlc`: its author's device/// (`cotton_authors`). `None` when this file cannot say.pub fn writer_device(db: &Driver, hlc: &str) -> Result<Option<String>> {    let Some(author) = crate::fold::author_of(hlc) else {        return Ok(None);    };    Ok(db        .get("SELECT device_id FROM cotton_authors WHERE id = ? LIMIT 1", &[text(author)])?        .and_then(|row| row.text("device_id").map(str::to_string)))}/// The owner-id prefix of an assistant SEAT: a token another person holds in/// a database they were admitted to (`cotton_server::mcp::reach`).pub const SEAT_PREFIX: &str = "person:";/// Does `actor` (wire form) act for a person who is not the owner — a member/// at their device, or an assistant seat a member holds (its token's owner is/// `person:<key>`), directly or through an automation it set off? A write/// the serving Mac mints for a seat is stamped by the Mac itself, so the/// writer's device alone cannot say.pub fn acts_for_another_person(db: &Driver, actor: &str) -> Result<bool> {    let Ok(actor) = Actor::from_wire(actor) else {        return Ok(false);    };    Ok(match actor.principal() {        Actor::Member(_) => true,        Actor::Token(token) => db            .get("SELECT owner_user_id FROM cotton_mcp_tokens WHERE id = ?", &[text(token.as_str())])?            .and_then(|row| row.text("owner_user_id").map(str::to_string))            .is_some_and(|owner| owner.starts_with(SEAT_PREFIX)),        _ => false,    })}/// Does this file hold any record only-you? One indexed read; every judge/// asks it first, so a file nobody marked pays nothing more. A file of a/// shape from before the audience (a peer of an older build across an/// additive rise) holds none.pub fn any_held(db: &Driver) -> Result<bool> {    db.batch_fact("audience any_held", || read_any_held(db))}fn read_any_held(db: &Driver) -> Result<bool> {    if !table_exists(db, TABLE)? {        return Ok(false);    }    Ok(db        .get(&format!("SELECT 1 AS x FROM {TABLE} WHERE audience = ? LIMIT 1"), &[text(ONLY_YOU)])?        .is_some())}/// The audience `table`'s `record_id` carries here, when it carries one.pub fn of_record(db: &Driver, table: &str, record_id: &str) -> Result<Option<String>> {    Ok(db        .get(            &format!("SELECT audience FROM {TABLE} WHERE record_table = ? AND record_id = ?"),            &[text(table), text(record_id)],        )?        .and_then(|row| row.text("audience").map(str::to_string)))}/// WHAT ONE DEVICE MAY NOT HOLD OF ONE FILE: the only-you records, read once./// Empty for the owner's own devices and for a file nobody marked.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Holds {    /// The held records, `(physical table, id)`.    records: BTreeSet<(String, String)>,    /// The held records' ids alone: what a naming row is matched by (ids are    /// uuids, unique across tables and databases).    ids: BTreeSet<String>,    /// The ids of the audience rows that hold them.    audience_rows: BTreeSet<String>,}impl Holds {    /// Nothing held: what the owner's devices are judged by.    pub fn none() -> Holds {        Holds::default()    }    /// Every only-you record of this file.    pub fn of_file(db: &Driver) -> Result<Holds> {        let mut holds = Holds::default();        for row in db.all(            &format!("SELECT id, record_table, record_id FROM {TABLE} WHERE audience = ? ORDER BY id"),            &[text(ONLY_YOU)],        )? {            let (Some(id), Some(table), Some(record)) = (row.text("id"), row.text("record_table"), row.text("record_id"))            else {                continue;            };            holds.records.insert((table.to_string(), record.to_string()));            holds.ids.insert(record.to_string());            holds.audience_rows.insert(id.to_string());        }        Ok(holds)    }    /// What an assistant seat — another person's token — may not see of this    /// file: every only-you record, when there is one.    pub fn for_seat(db: &Driver) -> Result<Holds> {        if !any_held(db)? {            return Ok(Holds::none());        }        Holds::of_file(db)    }    /// What `device_key` may not hold of this file: nothing when it is one of    /// the owner's devices ([`owners_device`]), every only-you record otherwise.    pub fn for_device(db: &Driver, device_key: &str) -> Result<Holds> {        if !any_held(db)? || owners_device(db, device_key)? {            return Ok(Holds::none());        }        Holds::of_file(db)    }    /// Is nothing held?    pub fn is_empty(&self) -> bool {        self.audience_rows.is_empty()    }    /// The held records, `(physical table, id)`.    pub fn records(&self) -> impl Iterator<Item = &(String, String)> {        self.records.iter()    }    /// What these holds keep back, as text a copy's fingerprint folds in: two    /// devices with the same keep rules and different holds are cut apart.    pub fn fingerprint(&self) -> String {        self.audience_rows.iter().map(|id| format!("h\u{1f}{id}\u{1e}")).collect()    }    /// Is `table`'s `row_id` held — the record, an audience row holding one, a    /// row a held record owns, or a row naming one? `said` is what an op in    /// hand says of the row, read where the file holds no row of it yet.    pub fn holds(&self, db: &Driver, table: &str, row_id: &str, said: Option<&Map<String, JsonValue>>) -> Result<bool> {        if self.is_empty() {            return Ok(false);        }        self.holds_at(db, table, row_id, said, 0)    }    fn holds_at(        &self,        db: &Driver,        table: &str,        row_id: &str,        said: Option<&Map<String, JsonValue>>,        depth: usize,    ) -> Result<bool> {        if depth > MAX_DEPTH {            return Ok(true);        }        if table == TABLE {            return Ok(self.audience_rows.contains(row_id));        }        if self.records.contains(&(table.to_string(), row_id.to_string())) {            return Ok(true);        }        for (child, column, parent) in OWNING_REFS {            if *child != table {                continue;            }            if let Some(parent_id) = column_text(db, table, row_id, column, said)? {                if self.holds_at(db, parent, &parent_id, None, depth + 1)? {                    return Ok(true);                }            }        }        for (naming, column) in naming_columns() {            if naming != table {                continue;            }            if let Some(named) = column_text(db, table, row_id, column, said)? {                if self.ids.contains(&named) {                    return Ok(true);                }            }        }        Ok(false)    }    /// Does `value` name a held record anywhere — its id, or its audience    /// row's — as any string inside it?    pub fn names(&self, value: &JsonValue) -> bool {        match value {            JsonValue::String(text) => self.ids.contains(text) || self.audience_rows.contains(text),            JsonValue::Array(items) => items.iter().any(|item| self.names(item)),            JsonValue::Object(fields) => fields.values().any(|field| self.names(field)),            _ => false,        }    }    /// AN ANSWER FOR ANOTHER PERSON, LESS WHAT IT MAY NOT SEE: every element    /// of every list inside `value` that names a held record leaves — a hit,    /// a row, a comment on it. What is left can still name one only where the    /// answer IS that record; the caller refuses it whole then ([`Self::names`]).    pub fn redact(&self, value: JsonValue) -> JsonValue {        match value {            JsonValue::Array(items) => {                JsonValue::Array(items.into_iter().filter(|item| !self.names(item)).map(|item| self.redact(item)).collect())            }            JsonValue::Object(fields) => {                JsonValue::Object(fields.into_iter().map(|(key, field)| (key, self.redact(field))).collect())            }            other => other,        }    }    /// Are a media object's bytes held — named by held rows and by nothing    /// else (`crate::media_keys::rows_naming`)? A picture an ordinary record    /// also shows is that record's to show.    pub fn holds_key(&self, db: &Driver, key: &str) -> Result<bool> {        if self.is_empty() {            return Ok(false);        }        let names = crate::media_keys::rows_naming(db, key)?;        if names.is_empty() {            return Ok(false);        }        for (_, table, row_id) in &names {            if !self.holds(db, table, row_id, None)? {                return Ok(false);            }        }        Ok(true)    }    /// AN ANSWER'S OPS, LESS WHAT THIS DEVICE MAY NOT HOLD — upserts and    /// deletes alike. Handed back as they came when nothing is held.    pub fn leave_out(&self, db: &Driver, ops: Vec<CottonOp>) -> Result<Vec<CottonOp>> {        if self.is_empty() {            return Ok(ops);        }        let mut kept = Vec::with_capacity(ops.len());        for op in ops {            let said = match op.kind {                OpKind::Upsert => op.patch.as_ref(),                OpKind::Delete => None,            };            if !self.holds(db, &op.table, &op.row_id, said)? {                kept.push(op);            }        }        Ok(kept)    }    /// Every row these holds keep off a device, present or known only by a    /// receipt, deepest first: each held record with what it owns, what names    /// it, and the audience row that holds it.    pub fn rows(&self, db: &Driver) -> Result<Vec<(String, String)>> {        let mut rows: Vec<(String, String)> = Vec::new();        let push = |rows: &mut Vec<(String, String)>, row: (String, String)| {            if !rows.contains(&row) {                rows.push(row);            }        };        for (table, record) in &self.records {            for (naming, column) in naming_columns() {                for id in naming_ids(db, naming, column, record)? {                    for owned in crate::erase::owned_descendants(db, naming, &id)? {                        push(&mut rows, owned);                    }                    push(&mut rows, (naming.to_string(), id));                }            }            for owned in crate::erase::owned_descendants(db, table, record)? {                push(&mut rows, owned);            }            push(&mut rows, (table.clone(), record.clone()));        }        for id in &self.audience_rows {            push(&mut rows, (TABLE.to_string(), id.clone()));        }        Ok(rows)    }}/// Every `(table, column)` that names a record: [`NAMED_BY`] and the/// `OWNED_BY` rows of the erase.fn naming_columns() -> impl Iterator<Item = (&'static str, &'static str)> {    NAMED_BY        .iter()        .copied()        .chain(crate::erase::OWNED_BY.iter().map(|(table, column, _)| (*table, *column)))}/// The ids of `table`'s rows whose `column` names `record`: in the table, and/// in the receipts of rows it does not hold.fn naming_ids(db: &Driver, table: &str, column: &str, record: &str) -> Result<BTreeSet<String>> {    let mut ids = BTreeSet::new();    let Some(spec) = crate::schema::specs::spec_for(table) else {        return Ok(ids);    };    if !spec.columns.iter().any(|(name, _)| *name == column) {        return Ok(ids);    }    if table_exists(db, table)? {        for row in db.all(&format!("SELECT \"{}\" AS id FROM {table} WHERE \"{column}\" = ?", spec.pk), &[text(record)])? {            if let Some(id) = row.text("id") {                ids.insert(id.to_string());            }        }    }    for row in db.all(        &format!(            "SELECT DISTINCT w.row_id FROM _writes w WHERE w.tbl = ? \             AND ({}) = ?",            crate::receipts::implied::field_sql("w", table, column)        ),        &[text(table), text(record)],    )? {        if let Some(id) = row.text("row_id") {            ids.insert(id.to_string());        }    }    Ok(ids)}fn table_exists(db: &Driver, table: &str) -> Result<bool> {    db.table_exists(table)}/// One column of `table`'s `row_id` as text: the file's own row first, then/// what the op in hand says.fn column_text(    db: &Driver,    table: &str,    row_id: &str,    column: &str,    said: Option<&Map<String, JsonValue>>,) -> Result<Option<String>> {    let Some(spec) = crate::schema::package_shape::spec_on(db, table)? else {        return Ok(None);    };    if !spec.columns.iter().any(|(name, _)| *name == column) {        return Ok(None);    }    let here = db        .get(&format!("SELECT \"{column}\" AS v FROM {table} WHERE \"{pk}\" = ?", pk = spec.pk), &[text(row_id)])?        .and_then(|row| row.text("v").map(str::to_string));    Ok(here.or_else(|| said.and_then(|patch| patch.get(column)).and_then(|v| v.as_str()).map(str::to_string)))}fn encoded_text<'a>(encoded: Option<&'a [(String, SqlValue)]>, column: &str) -> Option<&'a str> {    encoded?.iter().find(|(name, _)| name == column).and_then(|(_, value)| match value {        SqlValue::Text(text) => Some(text.as_str()),        _ => None,    })}/// Does this file admit a device that is not the owner's — a member's device/// that is live? Read from the same rows [`owners_device`] reads.fn admits_another_persons_device(db: &Driver) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS x FROM cotton_devices WHERE revoked_at IS NULL \             AND person_key IS NOT NULL AND length(trim(person_key)) > 0 LIMIT 1",            &[],        )?        .is_some())}/// Is `table`'s `row_id` present in this file (its row, or any receipt of it)?fn record_here(db: &Driver, table: &str, row_id: &str) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS x FROM _writes WHERE tbl = ?1 AND row_id = ?2 \             UNION ALL SELECT 1 FROM _tombstones WHERE tbl = ?1 AND row_id = ?2 LIMIT 1",            &[text(table), text(row_id)],        )?        .is_some())}/// THE RULE AT THE FOLD, asked of one write minted here or handed over by a/// device (never of a pulled answer: the serving Mac's own fold already asked/// it). `None` is "nothing to say"; `Some(reason)` the refusal. `encoded` is/// an upsert's patch as the fold encoded it.pub fn refusal(    db: &Driver,    op: &CottonOp,    encoded: Option<&[(String, SqlValue)]>,) -> Result<Option<String>> {    let audience_op = op.table == TABLE;    if !audience_op && !any_held(db)? {        return Ok(None);    }    // The writer is the owner's unless this file says otherwise. A write    // reaches a file only from a device approved in it, so where no other    // person's device is admitted every writer is the owner's; where one is,    // a writer the file cannot place as the owner's is judged as theirs.    let owners = match writer_device(db, &op.hlc)? {        Some(device) if owners_device(db, &device)? => true,        _ => !admits_another_persons_device(db)?,    } && !acts_for_another_person(db, &op.actor)?;    if !audience_op {        let said = op.patch.as_ref().filter(|_| op.kind == OpKind::Upsert);        if !owners && Holds::of_file(db)?.holds(db, &op.table, &op.row_id, said)? {            return Ok(Some(format!("{} {} {HELD_REFUSAL}", op.table, op.row_id)));        }        return Ok(None);    }    if !owners {        return Ok(Some(format!("{TABLE} {}: {ONLY_THE_OWNER_SETS}", op.row_id)));    }    if op.kind == OpKind::Delete {        return Ok(Some(format!("{TABLE} {}: {NEVER_DELETED}", op.row_id)));    }    let here = db.get(        &format!("SELECT record_table, record_id, audience FROM {TABLE} WHERE id = ?"),        &[text(&op.row_id)],    )?;    let current = here.as_ref().and_then(|row| row.text("audience").map(str::to_string));    let record_table = encoded_text(encoded, "record_table")        .map(str::to_string)        .or_else(|| here.as_ref().and_then(|row| row.text("record_table").map(str::to_string)));    let record_id = encoded_text(encoded, "record_id")        .map(str::to_string)        .or_else(|| here.as_ref().and_then(|row| row.text("record_id").map(str::to_string)));    let (Some(record_table), Some(record_id)) = (record_table, record_id) else {        return Ok(Some(format!("{TABLE} {}: an audience names the record it holds", op.row_id)));    };    if audience_id(&record_table, &record_id) != op.row_id {        return Ok(Some(format!(            "{TABLE} {}: an audience's id is derived from the record it holds (derived_id::audience_id)",            op.row_id        )));    }    let Some(audience) = encoded_text(encoded, "audience").map(str::to_string) else {        return Ok(None);    };    if !AUDIENCES.contains(&audience.as_str()) {        return Ok(Some(format!("{TABLE} {}: {audience:?} is no audience ({})", op.row_id, AUDIENCES.join(", "))));    }    let releasing = current.as_deref() == Some(ONLY_YOU) && audience != ONLY_YOU;    if releasing {        let by_the_owner = Actor::from_wire(&op.actor).is_ok_and(|actor| actor.is_owner());        if !by_the_owner {            return Ok(Some(format!("{record_table} {record_id}: {ONLY_THE_OWNER_RELEASES}")));        }    }    let marking = audience == ONLY_YOU && current.as_deref() != Some(ONLY_YOU);    if marking && record_here(db, &record_table, &record_id)? && admits_another_persons_device(db)? {        return Ok(Some(format!("{record_table} {record_id} {ALREADY_SHARED}")));    }    Ok(None)}/// THE MARK, as the changes a writer mints: `table`'s `record_id` held for/// the owner alone. Minted BEFORE the record's own create when a record is/// made only-you, so the serving Mac holds the audience before the record can/// reach it.pub fn mark(db: &Driver, workspace_id: &str, table: &str, record_id: &str, at: &str) -> Result<Change> {    write(db, workspace_id, table, record_id, ONLY_YOU, at)}/// THE RELEASE, as the change a writer mints: every column of the audience/// row restated, so a member who never held the row receives it whole and/// asks for the record it names ([`released_missing`]).pub fn release(db: &Driver, workspace_id: &str, table: &str, record_id: &str, at: &str) -> Result<Change> {    write(db, workspace_id, table, record_id, EVERYONE, at)}fn write(db: &Driver, workspace_id: &str, table: &str, record_id: &str, audience: &str, at: &str) -> Result<Change> {    let id = audience_id(table, record_id);    let created = db        .get(&format!("SELECT created_at FROM {TABLE} WHERE id = ?"), &[text(&id)])?        .and_then(|row| row.text("created_at").map(str::to_string));    let mut patch = Map::new();    patch.insert("id".into(), JsonValue::String(id.clone()));    patch.insert("workspace_id".into(), JsonValue::String(workspace_id.to_string()));    patch.insert("record_table".into(), JsonValue::String(table.to_string()));    patch.insert("record_id".into(), JsonValue::String(record_id.to_string()));    patch.insert("audience".into(), JsonValue::String(audience.to_string()));    patch.insert("created_at".into(), JsonValue::String(created.clone().unwrap_or_else(|| at.to_string())));    patch.insert("updated_at".into(), JsonValue::String(at.to_string()));    Ok(match created {        Some(_) => Change::update(TABLE, &id, patch),        None => Change::create(TABLE, &id, patch),    })}/// WHAT A RELEASE LEFT THIS DEVICE TO ASK FOR, each to be opened by name/// ([`crate::keep::open`]) like any record, at most `limit`:////// - the AUDIENCE ROW, when this file holds its release and not its create:///   the owner released it after this device's cursors passed the hold, so///   the row is dormant here (a row is live only with its create) and its///   opening brings the create;/// - the RECORD a released audience names, when this file holds no row of it///   and no retract — no page will carry it, for the same reason.////// The release restates every column of its row, so the record is named/// from the release's own receipt.pub fn released_missing(db: &Driver, limit: usize) -> Result<Vec<(String, String)>> {    let mut missing: Vec<(String, String)> = Vec::new();    if limit == 0 {        return Ok(missing);    }    let ids = db.all("SELECT DISTINCT row_id FROM _writes WHERE tbl = ? ORDER BY row_id", &[text(TABLE)])?;    for id in ids.iter().filter_map(|row| row.text("row_id")) {        if missing.len() >= limit {            break;        }        let receipts = crate::receipts::of_row(db, TABLE, id)?;        let life = crate::receipts::assemble_under(TABLE, &receipts, None, false);        let field = |name: &str| life.fields.get(name).and_then(|current| current.value.as_str().map(str::to_string));        if field("audience").as_deref() != Some(EVERYONE) {            continue;        }        let (Some(table), Some(record)) = (field("record_table"), field("record_id")) else {            continue;        };        let live_here = db.get(&format!("SELECT 1 AS x FROM {TABLE} WHERE id = ?"), &[text(id)])?.is_some();        if !live_here {            missing.push((TABLE.to_string(), id.to_string()));        }        let Some(spec) = crate::schema::package_shape::spec_on(db, &table)? else {            continue;        };        let present = db            .get(&format!("SELECT 1 AS x FROM {} WHERE \"{}\" = ?", spec.name, spec.pk), &[text(&record)])?            .is_some();        if !present && crate::receipts::retract_stamp(db, spec.name, &record)?.is_none() && missing.len() < limit {            missing.push((spec.name.to_string(), record));        }    }    Ok(missing)}#[cfg(test)]#[path = "audience_tests.rs"]mod tests;