//! Synced device × tool keep rules and the device's last storage reading.//! Reads and the retained pass share one evaluation, so the confirmation counts//! only bytes that can actually leave. No filesystem or wall clock lives here.//!//! WHAT A DEVICE KEEPS OF ITS BYTES (architect's brief and rulings, 12 Oct//! 2026). This module decides retention; cotton-client's keep-fetch queue also//! fetches originals selected by these rules within the phone's cap. A byte its//! rule keeps stays; a byte outside the rule was fetched ON DEMAND and goes//! [`ON_DEMAND_DAYS`] after it was last opened; and nothing goes unless a//! KEEPER other than this device — a live Mac that keeps everything//! ([`KEEPS_EVERYTHING`]) — holds that exact original, so the last copy never//! leaves. The serving Mac never lets anything go, whatever it keeps.//! A phone nobody gave a rule keeps three months of chat media//! ([`default_rule`]), holds what no record of its own names (a mail//! attachment it opened) on demand, and never keeps a status's bytes//! (`keep::status_bytes_never`). A record or a group kept always pins its//! bytes (`Keep::pins_key`). A Mac keeps everything unless a person says//! otherwise: "rows only" ([`MacKeeps`]) holds a Mac's bytes as a phone holds//! one it opened.usecrate::actor::{Actor, JobName};usecrate::mint::{changes_of, mint, Act, Held, History};usecrate::outbox::{IdSource, LocalChange};usecrate::protocol::{js, types::OpKind};usecrate::{ driver::Driver, error::{Result, StoreError},};use rusqlite::types::ValueasSqlValue;use serde::{Deserialize, Serialize};use serde_json::json;use std::collections::BTreeMap;pubconst TABLE: &str = "cotton_storage_rules";/// Every tool a stored file can be classified under, so a file of any tool/// has an answer. Storage lists and frees only `BYTE_TOOLS`; the rest are/// records that are small and counted, and their files are skipped.pubconst TOOLS: [(&str, &str); 7] = [ ("photo", "Photos"), ("video", "Videos"), ("document", "Documents"), ("meeting", "Meetings"), ("thread", "Messages"), ("person", "People"), ("other", "Other files"),];/// The tools whose records carry bytes: the only rows Storage shows and the/// only originals a keep rule may release. Messages is one: a chat's pictures,/// films, voice notes and files are most of what a household's phone would/// otherwise carry.pubconst MESSAGE_SOURCES: [&str; 2] = ["whatsapp", "instagram"];pubconst BYTE_TOOLS: [&str; 4] = ["photo", "video", "document", "thread"];/// How long a byte its rule does not keep stays after it was last opened: the/// same thirty days a row opened from outside the rules stays.pubconst ON_DEMAND_DAYS: i64 = crate::keep::ON_DEMAND_DAYS;const DAY_MS: i64 = 86_400_000;/// What a device keeps of a tool nobody gave it a rule for. A stored rule/// replaces it.////// A PHONE keeps the last three months of chat media and holds older on/// demand (the brief: "WhatsApp media from people — last 3 months kept, older/// on demand"); every other tool, and every tool on a Mac, is `all`.pubfn default_rule(phone: bool, tool: &str) -> KeepRule {if phone && (tool == "thread" || MESSAGE_SOURCES.contains(&tool)) {KeepRule::Recent90Days } else {KeepRule::All }}/// WHAT A MAC KEEPS of its bytes — the choice on a Mac's device row (sync/// programme, lane D, 12 Oct 2026). It is not a second store: it is read off,/// and written as, the Mac's own rules for every byte tool, so Storage and the/// device row can never disagree.////// - **Everything**: every byte tool `all` (no rule row is `all`). A Mac that/// keeps everything is a KEEPER — the only kind of device the household's/// two-copy target counts, and the only kind whose copy lets another device/// let its own go ([`KEEPS_EVERYTHING`])./// - **Rows only**: every byte tool `only_opened` — bytes come when somebody/// opens them and go thirty days after the last opening, as on a phone./// A SERVING Mac keeps everything whatever this says (coordinator, 12 Oct/// 2026): the server serves from its own disk, so its rows-only binds only/// while another Mac serves./// - **Per tool**: anything else a person set tool by tool in Storage. Not a/// keeper.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumMacKeeps {Everything,RowsOnly,PerTool,}implMacKeeps {pubfn as_str(self) -> &'static str {matchself {Self::Everything => "everything",Self::RowsOnly => "rows_only",Self::PerTool => "per_tool", } }/// A choice a person can make: `everything` or `rows_only`.pubfn parse(s: &str) -> Result<Self> {match s {"everything" => Ok(Self::Everything),"rows_only" => Ok(Self::RowsOnly), _ => Err(StoreError::refused("what a Mac keeps is everything or rows_only")), } }/// The rule every byte tool takes under this choice.pubfn rule(self) -> Option<KeepRule> {matchself {Self::Everything => Some(KeepRule::All),Self::RowsOnly => Some(KeepRule::OnlyOpened),Self::PerTool => None, } }}/// The ONE reading of "a Mac that keeps everything", as SQL over a/// `cotton_devices` row aliased `d`: not a phone, and no byte tool of it with/// a rule other than `all`. The holder counts join it, so a phone's copy, a/// rows-only Mac's copy and the mirror bucket (which records no holding at/// all) are never what lets a copy go. Its tool list is [`BYTE_TOOLS`]/// (guard: `storage_rules_tests::the_keeper_sql_names_every_byte_tool`).pubconst KEEPS_EVERYTHING: &str = "(COALESCE(d.platform, '') NOT IN ('ios', 'android') AND NOT EXISTS (\ SELECT 1 FROM cotton_storage_rules kr WHERE kr.workspace_id = d.workspace_id AND kr.device_id = d.device_id \ AND kr.tool IN ('photo', 'video', 'document', 'thread', 'whatsapp', 'instagram') AND kr.keep_rule <> 'all'))";/// What `device` keeps of its bytes, read off its byte tools' rules. A phone/// is never asked: its answer would be its defaults, which are not a Mac's.pubfn mac_keeps(db: &Driver, workspace: &str, device: &str) -> Result<MacKeeps> {letmut rules = Vec::with_capacity(BYTE_TOOLS.len());for tool in BYTE_TOOLS {let stored = db .get("SELECT keep_rule FROM cotton_storage_rules WHERE workspace_id=? AND device_id=? AND tool=?", &[text(workspace), text(device), text(tool)], )? .and_then(|r| r.text("keep_rule").map(str::to_string)); rules.push(match stored {Some(rule) => KeepRule::parse(&rule)?,None => KeepRule::All, }); }for source in MESSAGE_SOURCES {ifletSome(rule)=db.get("SELECT keep_rule FROM cotton_storage_rules WHERE workspace_id=? AND device_id=? AND tool=?",&[text(workspace),text(device),text(source)])?.and_then(|r|r.text("keep_rule").map(str::to_string)) { rules.push(KeepRule::parse(&rule)?); } }Ok(if rules.iter().all(|r| *r == KeepRule::All) {MacKeeps::Everything } elseif rules.iter().all(|r| *r == KeepRule::OnlyOpened) {MacKeeps::RowsOnly } else {MacKeeps::PerTool })}/// Is `device` a keeper — a live Mac that keeps everything? The Rust twin of/// [`KEEPS_EVERYTHING`], asked of the device's own row.pubfn keeps_everything(db: &Driver, workspace: &str, device: &str) -> Result<bool> {Ok(db .get( &format!("SELECT 1 AS keeper FROM cotton_devices d WHERE d.workspace_id = ? AND d.device_id = ? \ AND d.revoked_at IS NULL AND {KEEPS_EVERYTHING} LIMIT 1" ), &[text(workspace), text(device)], )? .is_some())}/// Does a Mac's server pull every original another device holds into its own/// store — the standby pull? Only a KEEPER does, and the SERVING Mac whatever/// it keeps (it serves from its own disk). A rows-only Mac pulls none: its/// originals come when somebody opens them, from whichever Mac serves.pubfn pulls_every_original(db: &Driver, workspace: &str, device: &str) -> Result<bool> {ifcrate::serving::serving_fact(db, workspace)?.is_some_and(|s| s.device_credential_id == device) {returnOk(true); } keeps_everything(db, workspace, device)}/// The patches that make `device`'s byte tools say `choice`: one per byte/// tool, keyed by its rule row's id, the new row's own columns included when/// it has none yet. A caller writes them through its own writer, so the ops/// land where it needs them (the keep verbs' answer). The device's last/// reading is cleared with the rule, as [`set_rule`] clears it.pubfn mac_keeps_patches( db: &Driver, workspace: &str, device: &str, choice: MacKeeps, at: &str,) -> Result<Vec<(String, serde_json::Map<String, serde_json::Value>)>> { live(db, workspace, device)?;ifcrate::keep::is_phone(db, device)? {returnErr(StoreError::refused("a phone keeps what its keep rules say; everything or rows only is a Mac's choice", )); }letSome(rule) = choice.rule() else {returnErr(StoreError::refused("what a Mac keeps is everything or rows_only")); };letmut patches = Vec::with_capacity(BYTE_TOOLS.len());letmut tools=BYTE_TOOLS.to_vec();for source in MESSAGE_SOURCES {if db.get("SELECT 1 FROM cotton_storage_rules WHERE workspace_id=? AND device_id=? AND tool=?",&[text(workspace),text(device),text(source)])?.is_some() {tools.push(source);} }for tool in tools {let id = row_id(device, tool);let held = db .get("SELECT keep_rule FROM cotton_storage_rules WHERE id=?", &[text(&id)])? .map(|r| r.text("keep_rule").unwrap_or("all").to_string());// A tool already saying it changes nothing and writes nothing; a tool// with no row says `all`.if held.as_deref().unwrap_or("all") == rule.as_str() {continue; }letmut patch = serde_json::Map::new();if held.is_none() { patch.insert("id".into(), json!(id)); patch.insert("workspace_id".into(), json!(workspace)); patch.insert("device_id".into(), json!(device)); patch.insert("tool".into(), json!(tool)); patch.insert("created_at".into(), json!(at)); } patch.insert("keep_rule".into(), json!(rule.as_str())); patch.insert("freeable_bytes".into(), serde_json::Value::Null); patch.insert("measured_at".into(), serde_json::Value::Null); patch.insert("updated_at".into(), json!(at)); patches.push((id, patch)); }Ok(patches)}pubfn holds_bytes(tool: &str) -> bool { BYTE_TOOLS.contains(&tool) || MESSAGE_SOURCES.contains(&tool)}/// Source choices inherit the broad Messages choice until explicitly set./// This single reading is shared by fetching, retention and the device face.pubfn byte_rule(db:&Driver,workspace:&str,device:&str,tool:&str)->Result<KeepRule> {let source=MESSAGE_SOURCES.contains(&tool);let sql=if source {"SELECT keep_rule FROM cotton_storage_rules WHERE workspace_id=?1 AND device_id=?2 AND tool IN (?3,'thread') ORDER BY tool=?3 DESC LIMIT 1"}else {"SELECT keep_rule FROM cotton_storage_rules WHERE workspace_id=?1 AND device_id=?2 AND tool=?3"};match db.get(sql,&[text(workspace),text(device),text(tool)])?.and_then(|r|r.text("keep_rule").map(str::to_string)) {Some(rule)=>KeepRule::parse(&rule),None=>Ok(default_rule(crate::keep::is_phone(db,device)?,if source {"thread"} else {tool})), }}/// A byte tool's name. Every one of `BYTE_TOOLS` is in `TOOLS`.fn label(tool: &str) -> &'static str { TOOLS .iter() .find(|(t, _)| *t == tool) .map(|(_, label)| *label) .expect("every byte tool is a classified tool")}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pubenumKeepRule {All, #[serde(rename = "recent_90_days")]Recent90Days,OnlyOpened,}implKeepRule {pubfn parse(s: &str) -> Result<Self> {match s {"all" => Ok(Self::All),"recent_90_days" => Ok(Self::Recent90Days),"only_opened" => Ok(Self::OnlyOpened), _ => Err(StoreError::refused("keep rule must be all, recent_90_days or only_opened", )), } }pubfn as_str(self) -> &'static str {matchself {Self::All => "all",Self::Recent90Days => "recent_90_days",Self::OnlyOpened => "only_opened", } }/// Does the rule itself keep bytes dated `at`, whether or not anybody/// opens them? A date that cannot be read is never old: a malformed date/// must not make a person's original something to discard.pubfn keeps(self, at: Option<&str>, now_ms: i64) -> bool {matchself {Self::All => true,Self::OnlyOpened => false,Self::Recent90Days => {let cutoff = now_ms.saturating_sub(90 * DAY_MS); !at.is_some_and(|s| js::parse_date_ms(s).is_some_and(|d| d < cutoff)) } } }/// May bytes dated `at` and last opened at `opened` go? Only when the rule/// does not keep them AND nobody opened them in the last/// [`ON_DEMAND_DAYS`]: what is outside a rule is held on demand, and on/// demand lasts thirty days from the last opening.pubfn releases(self, at: Option<&str>, opened: Option<&str>, now_ms: i64) -> bool { !self.keeps(at, now_ms) && !opened_lately(opened, now_ms) }}/// Opened within [`ON_DEMAND_DAYS`]. An opening whose date cannot be read/// counts as lately: the doubt keeps the bytes.fn opened_lately(opened: Option<&str>, now_ms: i64) -> bool {let fresh_from = now_ms.saturating_sub(ON_DEMAND_DAYS * DAY_MS); opened.is_some_and(|s| js::parse_date_ms(s).is_none_or(|d| d >= fresh_from))}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]pubstructStorageRow {pub id: String,pub device_id: String,pub device_name: String,pub tool: String,pub name: String,pub keep_rule: String,pub held_bytes: i64,pub freeable_bytes: i64,pub held_count: i64,pub total_count: i64,pub measured_at: Option<String>,pub is_this_device: bool,/// Of `held_bytes`, the originals this device holds ON DEMAND: outside its/// rule, here because somebody opened them, and gone thirty days after/// the last opening. The rest of `held_bytes` is kept. Measured by the/// device itself only — another device's is unknown, never 0.pub on_demand_bytes: Option<i64>,}#[derive(Debug, Clone)]pubstructCandidate {pub aliases: Vec<String>,pub tool: String,pub key: String,pub local_path: String,pub bytes: i64,}#[derive(Debug)]pubstructEvaluation {pub rows: Vec<StorageRow>,pub candidates: Vec<Candidate>,}fn text(s: &str) -> SqlValue {SqlValue::Text(s.to_string())}pubfn row_id(device: &str, tool: &str) -> String { format!("storage:{}:{device}:{tool}", device.len())}fn live(db: &Driver, workspace: &str, device: &str) -> Result<()> {ifcrate::media_holdings::device_standing(db, workspace, device)? != crate::media_holdings::DeviceStanding::Live {returnErr(StoreError::refused("Storage needs a live device of this database", )); }Ok(())}/// The catalogue includes originals not downloaded here; the ledger contributes/// prints, renditions and orphaned files too. A key is counted once even when/// several records refer to the same bytes. Documents outrank image MIME types./// The last arm dates a chat's file by its message (`?4`): only the files this/// device holds, and only for a device whose rule could let one go — a Mac/// that keeps everything never pays for the join.const INVENTORY: &str = r#"WITH refs AS ( SELECT storage_path AS key, 'document' AS tool, created_at AS at FROM cotton_documents WHERE workspace_id=?1 AND trashed_at IS NULL UNION ALL SELECT key,'photo',COALESCE(taken_at,created_at) FROM cotton_photos WHERE workspace_id=?1 AND trashed_at IS NULL UNION ALL SELECT key,'video',COALESCE(taken_at,created_at) FROM cotton_videos WHERE workspace_id=?1 AND trashed_at IS NULL UNION ALL SELECT avatar_key,'person',updated_at FROM cotton_people WHERE workspace_id=?1 AND archived_at IS NULL UNION ALL SELECT photo_key,'thread',updated_at FROM cotton_msg_threads WHERE workspace_id=?1 AND trashed_at IS NULL UNION ALL SELECT m.key,'thread',x.sent_at FROM _media m JOIN _media_key_names n ON n.key=m.key AND n.tbl='cotton_msg_messages' JOIN cotton_msg_messages x ON x.id=n.row_id WHERE ?4 AND m.workspace_id=?1 AND m.local_path IS NOT NULL AND instr(m.key,'/messages/')>0), catalogue AS (SELECT key, MIN(tool) AS tool, MAX(at) AS at FROM refs WHERE key IS NOT NULL GROUP BY key),holdings AS (SELECT object_key AS key, MAX(bytes) AS bytes, MIN(tier) AS tier FROM cotton_media_holdings WHERE workspace_id=?1 AND device_id=?2 AND dropped_at IS NULL AND ?3 GROUP BY object_key),prints AS (SELECT avatar_key AS key FROM cotton_people WHERE workspace_id=?1 AND avatar_key IS NOT NULL UNION SELECT photo_key FROM cotton_msg_threads WHERE workspace_id=?1 AND photo_key IS NOT NULL UNION SELECT poster_key FROM cotton_videos WHERE workspace_id=?1 AND poster_key IS NOT NULL),keys AS (SELECT key FROM catalogue UNION SELECT key FROM _media WHERE workspace_id=?1 AND state<>'delete_pending' UNION SELECT key FROM holdings)SELECT k.key, c.tool AS record_tool, COALESCE(c.at,m.created_at) AS at, m.local_path,COALESCE(m.size_bytes,h.bytes) AS size_bytes,COALESCE(m.tier,h.tier) AS tier,m.state,m.pinned,m.captured_here,m.last_viewed_at,m.fetched_by_rule,CASE WHEN m.fetched_by_rule=1 THEN m.updated_at END AS fetched_at,h.key IS NOT NULL AS server_held,p.key IS NOT NULL AS print,CASE WHEN ?4 THEN (SELECT x.channel FROM _media_key_names n JOIN cotton_msg_messages x ON x.id=n.row_id WHERE n.key=k.key AND n.tbl='cotton_msg_messages' AND x.deleted_at IS NULL LIMIT 1) END AS sourceFROM keys k LEFT JOIN catalogue c ON c.key=k.key LEFT JOIN _media m ON m.key=k.key AND m.workspace_id=?1 LEFT JOIN holdings h ON h.key=k.key LEFT JOIN prints p ON p.key=k.keyORDER BY k.key"#;fn tool_for<'a>(record: Option<&'a str>, key: &str) -> &'a str {let folder = key .split_once('/') .map(|(_, tail)| tail) .and_then(|s| s.split('/').next());// A chat's file is Messages' whatever else names it: the library row the// media index derives for a chat picture does not make it a Photos// original, or the Photos rule would decide what a chat keeps.if folder == Some("messages") {return"thread"; }ifletSome(tool) = record {return tool; }match folder {Some("photos") => "photo",Some("videos") => "video",Some("documents" | "statements") => "document",Some("meetings") => "meeting",Some("messages") => "thread",Some("people") => "person", _ => "other", }}/// A local reading is evaluated from this file's ledger, never another device's/// holdings. The serving fact must be known and current before any byte can go.pubfn evaluate(db: &Driver, workspace: &str, device: &str, now_ms: i64) -> Result<Evaluation> { live(db, workspace, device)?;let name = db .get("SELECT name FROM cotton_devices WHERE workspace_id=? AND device_id=?", &[text(workspace), text(device)], )? .and_then(|r| r.text("name").map(str::to_string)) .unwrap_or_default();let at = js::to_iso_string(now_ms).ok_or_else(|| StoreError::encode("storage date out of range"))?;// What this device keeps always and never, from the one judge. A Mac's is// everything: no status rule is read for it, and its pins are everyone's.let keep = crate::keep::Keep::of_device(db, device)?;let phone = crate::keep::is_phone(db, device)?;let statuses_never = keep.table_rule("cotton_stories") == crate::keep::TableRule::None;// What pins a file here: a phone's own group and record rules; on a Mac,// which holds none, every live device's (`Keep::pinned_by_anyone`) — a// rows-only Mac never lets a pinned record's or a kept album's original go.let pins = if phone { keep } else {crate::keep::Keep::pinned_by_anyone(db)? };letmut rows: BTreeMap<String, StorageRow> = BYTE_TOOLS .iter() .map(|tool| { ( tool.to_string(),StorageRow { id: row_id(device, tool), device_id: device.into(), device_name: name.clone(), tool: tool.to_string(), name: label(tool).to_string(), keep_rule: default_rule(phone, tool).as_str().into(), held_bytes: 0, freeable_bytes: 0, held_count: 0, total_count: 0, measured_at: Some(at.clone()), is_this_device: true, on_demand_bytes: Some(0), }, ) }) .collect();letmut source_rules=BTreeMap::new();for r in db.all("SELECT tool,keep_rule FROM cotton_storage_rules WHERE workspace_id=? AND device_id=?", &[text(workspace), text(device)], )? {ifletSome(row) = r.text("tool").and_then(|t| rows.get_mut(t)) { row.keep_rule = r.text("keep_rule").unwrap_or("all").into(); }iflet (Some(tool),Some(rule))=(r.text("tool"),r.text("keep_rule")) {if MESSAGE_SOURCES.contains(&tool) {source_rules.insert(tool.to_string(),KeepRule::parse(rule)?);} } }let serving = crate::serving::serving_fact(db, workspace)?;let heard_epoch = crate::serving::heard_epoch(db, workspace)?;// A SERVING MAC KEEPS EVERYTHING whatever its rules say (coordinator, 12// Oct 2026): it serves from its own disk, so its rows only binds while// another Mac serves. And nothing goes before this device has heard who// serves now.let may_release = serving .as_ref() .is_some_and(|s| s.device_credential_id != device && heard_epoch == Some(s.epoch));// NEVER THE LAST COPY: what a KEEPER other than this device holds — a// live Mac that keeps everything — read once rather than per candidate.// The serving Mac's copy alone is no longer the fence: a serving Mac may// be rows only (it keeps everything only while it serves), and the mirror// bucket records no holding at all.letmut kept_elsewhere = std::collections::BTreeSet::new();if may_release {for r in db.all( &format!("SELECT DISTINCT h.object_key AS key 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 AND h.workspace_id = ? \ AND h.tier = 'original' AND h.device_id <> ? AND {KEEPS_EVERYTHING}" ), &[text(workspace), text(device)], )? {ifletSome(key) = r.text("key") { kept_elsewhere.insert(key.to_string()); } } }letmut candidates = Vec::new();letmut counted_paths = std::collections::BTreeSet::new();letmut on_demand_paths = std::collections::BTreeSet::new();// A chat's file needs its message's date wherever one could go: on every// phone (what no message names is held on demand there), and on a device// whose Messages rule is not `all`.let dates_chats = phone || !source_rules.is_empty() || rows.get("thread").is_some_and(|row| row.keep_rule != "all");for r in db.all( INVENTORY, &[ text(workspace), text(device),// Every Mac measures its own served-store holdings, including a// standby releasing originals after a Files choice change.SqlValue::Integer(i64::from(!phone)),SqlValue::Integer(i64::from(dates_chats)), ], )? {let key = r.text("key").unwrap_or_default();let record = r.text("record_tool");let classified=tool_for(record,key);// A fetched pin outside the ordinary byte tools (meeting audio, for// example) is a file too. Keep its origin after opening so unkeep// can release it after thirty days, with the same last-copy fence.let tool=if !BYTE_TOOLS.contains(&classified) && classified!="person" && r.int("fetched_by_rule")==Some(1) {"document"} else {classified};// A file of a tool without bytes is neither listed nor freed, whatever// rule an older build synced for it; it claims no shared path either.letSome(row) = rows.get_mut(tool) else {continue; };let tier = r.text("tier");// Prints never belong to the original tier, even if an old producer// mislabelled one. A display rendition stays too: only originals go.// A chat's file has no renditions under its own key, so one with no// tier is the original, as a document's is.let original = r.int("print") != Some(1) && tool != "person" && (tier == Some("original") || (tier.is_none() && (record == Some("document") || tool == "thread")));let countable = record.is_some() || original;if countable { row.total_count += 1; }let path = r.text("local_path");if path.is_none() && r.int("server_held") != Some(1) {continue; }if r.text("state") == Some("delete_pending") {continue; }let bytes = r.int("size_bytes").unwrap_or(0).max(0);if path.is_none_or(|p| counted_paths.insert(p.to_string())) { row.held_bytes = row.held_bytes.saturating_add(bytes); }if countable { row.held_count += 1; }letSome(path) = path else {continue; };if !original || r.int("pinned") != Some(0) || r.text("state") != Some("synced") {continue; }// A STATUS'S BYTES ARE NEVER KEPT ON A PHONE: not by a rule, not by a// pin, and not for having been opened. Otherwise the tool's rule// decides — except on a phone for an original no record here names// (a mail attachment somebody opened, a file whose record has since// left this phone): nothing keeps it, so it is held on demand.let status = statuses_never && crate::keep::is_status_media(key);let rule = if phone && record.is_none() {KeepRule::OnlyOpened } elseif tool=="thread" && r.text("source").is_some_and(|source|source_rules.contains_key(source)) { source_rules[r.text("source").unwrap()] } else {KeepRule::parse(&row.keep_rule)? };if !status && (rule.keeps(r.text("at"), now_ms) || pins.pins_key(db, key)?) {continue; }// Outside the rule: held on demand, whether or not it may go yet.if on_demand_paths.insert(path.to_string()) { row.on_demand_bytes = row.on_demand_bytes.map(|held| held.saturating_add(bytes)); }if !may_release || (!status && (opened_lately(r.text("last_viewed_at"), now_ms) || opened_lately(r.text("fetched_at"), now_ms))) {continue; }// NEVER THE LAST COPY: a keeper other than this device must hold this// exact original, not merely a smaller rendition, a phone's or a// rows-only Mac's copy, or a stale/revoked peer's promise.if !kept_elsewhere.contains(key) {continue; } candidates.push(Candidate { aliases: vec![key.to_string()], tool: tool.to_string(), key: key.into(), local_path: path.into(), bytes, }); }// The media store is content-addressed: all aliases must agree to let// one physical file go. A kept print or pinned alias wins over eviction.let keys: std::collections::BTreeSet<_> = candidates.iter().map(|c| c.key.clone()).collect();letmut aliases: BTreeMap<String, Vec<String>> = BTreeMap::new();for r in db.all("SELECT key,local_path FROM _media WHERE local_path IS NOT NULL AND state<>'delete_pending'",&[])? { aliases.entry(r.text("local_path").unwrap_or_default().into()).or_default().push(r.text("key").unwrap_or_default().into()); }letmut by_path: BTreeMap<String, Candidate> = BTreeMap::new();for c in candidates {if aliases .get(&c.local_path) .is_some_and(|aliases| aliases.iter().any(|key| !keys.contains(key))) {continue; }ifletSome(first) = by_path.get_mut(&c.local_path) { first.aliases.push(c.key); } else { by_path.insert(c.local_path.clone(), c); } }let candidates: Vec<_> = by_path.into_values().collect();for c in &candidates {ifletSome(row) = rows.get_mut(&c.tool) { row.freeable_bytes = row.freeable_bytes.saturating_add(c.bytes); } }Ok(Evaluation { rows: BYTE_TOOLS.iter().filter_map(|t| rows.remove(*t)).collect(), candidates, })}#[allow(clippy::too_many_arguments)]fn write( db: &Driver, workspace: &str, device: &str, tool: &str, patch: serde_json::Value, now_ms: i64, ids: &mutdynIdSource, held: Held,) -> Result<()> {let id = row_id(device, tool);let at = js::to_iso_string(now_ms).ok_or_else(|| StoreError::encode("storage date out of range"))?;letmut patch = patch.as_object().expect("storage patch").clone();if db .get("SELECT id FROM cotton_storage_rules WHERE id=?", &[text(&id)], )? .is_none() { patch.insert("id".into(), json!(id)); patch.insert("workspace_id".into(), json!(workspace)); patch.insert("device_id".into(), json!(device)); patch.insert("tool".into(), json!(tool)); patch.insert("created_at".into(), json!(at)); } patch.insert("updated_at".into(), json!(at));let change = LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: TABLE.into(), row_id: id, patch: Some(patch), };let clock = crate::mint::clock::writer_clock(db, now_ms, &mut *ids)?; mint( db, &Act { actor: Actor::DeviceJob(JobName::named("storage")?), verb: "storage".into(), history: History::None, changes: changes_of(db, &[change]), }, &clock, ids, held, )?;Ok(())}/// Any admitted device may edit another's rule. Measurements never rewrite it.#[allow(clippy::too_many_arguments)]pubfn set_rule( db: &Driver, workspace: &str, device: &str, tool: &str, rule: &str, now_ms: i64, ids: &mutdynIdSource, held: Held,) -> Result<()> { live(db, workspace, device)?;if !holds_bytes(tool) {returnErr(StoreError::refused(format!("Storage keeps rules only for photos, videos, documents and messages, not {tool}" ))); }let rule = KeepRule::parse(rule)?; write( db, workspace, device, tool, json!({"keep_rule":rule.as_str(),"freeable_bytes":null,"measured_at":null}), now_ms, ids, held, )}/// Only the device measuring its own ledger publishes these readings. A quiet/// pass writes nothing; peers see when the last changed reading was measured.pubfn publish( db: &Driver, workspace: &str, rows: &[StorageRow], now_ms: i64, ids: &mutdynIdSource, held: Held,) -> Result<()> {for r in rows {let existing=db.get("SELECT held_bytes,freeable_bytes,held_count,total_count,measured_at FROM cotton_storage_rules WHERE id=?",&[text(&r.id)])?;if existing.is_some_and(|e| { e.text("measured_at").is_some() && e.int("held_bytes") == Some(r.held_bytes) && e.int("freeable_bytes") == Some(r.freeable_bytes) && e.int("held_count") == Some(r.held_count) && e.int("total_count") == Some(r.total_count) }) {continue; } write( db, workspace, &r.device_id, &r.tool, json!({"held_bytes":r.held_bytes,"freeable_bytes":r.freeable_bytes,"held_count":r.held_count,"total_count":r.total_count,"measured_at":r.measured_at}), now_ms, ids, held, )?; }Ok(())}pubfn remote_rows(db: &Driver, workspace: &str, device: &str) -> Result<Vec<StorageRow>> { live(db, workspace, device)?;let device_name = db .get("SELECT name FROM cotton_devices WHERE workspace_id=? AND device_id=?", &[text(workspace), text(device)], )? .and_then(|r| r.text("name").map(str::to_string)) .unwrap_or_default();let saved = db.all("SELECT * FROM cotton_storage_rules WHERE workspace_id=? AND device_id=?", &[text(workspace), text(device)], )?;let phone = crate::keep::is_phone(db, device)?;Ok(BYTE_TOOLS .iter() .map(|tool| {let r = saved.iter().find(|r| r.text("tool") == Some(*tool));StorageRow { id: row_id(device, tool), device_id: device.into(), device_name: device_name.clone(), tool: tool.to_string(), name: label(tool).to_string(), keep_rule: r .and_then(|r| r.text("keep_rule")) .unwrap_or(default_rule(phone, tool).as_str()) .into(), held_bytes: r.and_then(|r| r.int("held_bytes")).unwrap_or(0), freeable_bytes: r.and_then(|r| r.int("freeable_bytes")).unwrap_or(0), held_count: r.and_then(|r| r.int("held_count")).unwrap_or(0), total_count: r.and_then(|r| r.int("total_count")).unwrap_or(0), measured_at: r.and_then(|r| r.text("measured_at")).map(str::to_string), is_this_device: false, on_demand_bytes: None, } }) .collect())}/// A replica's background hydrator must not immediately fetch bytes its keep/// rule just released. Opening an original still fetches it through media.ensure.pubfn wants_original( db: &Driver, workspace: &str, device: &str, key: &str, now_ms: i64,) -> Result<bool> {if !crate::keep::is_phone(db, device)? {if pulls_every_original(db, workspace, device)? { returnOk(true); }if mac_keeps(db, workspace, device)? == MacKeeps::RowsOnly { returnOk(false); } }let row=db.get("SELECT COALESCE((SELECT 'document' FROM cotton_documents WHERE workspace_id=?1 AND storage_path=?2 LIMIT 1),(SELECT 'photo' FROM cotton_photos WHERE workspace_id=?1 AND key=?2 LIMIT 1),(SELECT 'video' FROM cotton_videos WHERE workspace_id=?1 AND key=?2 LIMIT 1)) AS tool, COALESCE((SELECT created_at FROM cotton_documents WHERE workspace_id=?1 AND storage_path=?2 LIMIT 1),(SELECT COALESCE(taken_at,created_at) FROM cotton_photos WHERE workspace_id=?1 AND key=?2 LIMIT 1),(SELECT COALESCE(taken_at,created_at) FROM cotton_videos WHERE workspace_id=?1 AND key=?2 LIMIT 1),(SELECT x.sent_at FROM _media_key_names n JOIN cotton_msg_messages x ON x.id=n.row_id WHERE n.key=?2 AND n.tbl='cotton_msg_messages' LIMIT 1),m.created_at) AS at,m.last_viewed_at,(SELECT x.channel FROM _media_key_names n JOIN cotton_msg_messages x ON x.id=n.row_id WHERE n.key=?2 AND n.tbl='cotton_msg_messages' AND x.deleted_at IS NULL LIMIT 1) AS source FROM (SELECT 1) LEFT JOIN _media m ON m.key=?2 AND m.workspace_id=?1",&[text(workspace),text(key)])?.expect("one row");let tool = tool_for(row.text("tool"), key);if !holds_bytes(tool) {// A tool Storage does not rule (a meeting's audio, an avatar): every// device takes it. A Rows only Mac was already excluded above.returnOk(true); }let rule = byte_rule(db,workspace,device,if tool=="thread" {row.text("source").filter(|source|MESSAGE_SOURCES.contains(source)).unwrap_or(tool)} else {tool})?;Ok(!rule.releases(row.text("at"), row.text("last_viewed_at"), now_ms))}#[cfg(test)]#[path = "storage_rules_tests.rs"]mod tests;