//! A receipt the object served, kept as its identity while its row says it//! (TRIM, 21 Nov 2026; schema 151).//!//! A phone keeps every row the object serves twice: the row in its table,//! and the receipt in `_writes` — the same fields again, as canonical bytes,//! with their names. Measured on 20,000 invented messages, the receipt and//! its indexes were 62% of the copy. The object is the authority: the phone//! never sends or proves a served receipt, it only needs to know it holds//! that version — and, for the fold, what the receipt says.//!//! So a served receipt whose row says every field it names, as it names it,//! with no retract beside it, is IMPLIED: `bytes` and `fields` go, `implied` names its//! [`_field_sets`] entry (its field names and the schema it was minted at),//! and its bytes are made again, when anything reads them, from the row —//! exactly, because a receipt is implied only after [`imply`] has made its//! bytes from the row and found them equal, byte for byte, to the bytes//! minted. Nothing reads a different receipt than before.//!//! The rule that keeps it so: a row's implied receipt is put back whole//! ([`materialize_row`]) BEFORE any other receipt of that row is stored, so//! a merge, a change of one's own, a bin, a restore or a retract always//! assembles from the bytes as minted. A phone's own writes are never//! implied (only the object's author is), held or sent.//!//! [`trim_step`] trims an existing copy in place, a bounded page at a time.use rusqlite::types::ValueasSqlValue;usecrate::canonical::{self, Kind, Receipt};usecrate::driver::{Driver, Row};usecrate::error::Result;usecrate::schema::codecs::decode_value;usecrate::schema::specs::spec_for;/// The author every receipt the personal object serves carries.pubconst OBJECT_AUTHOR: &str = "object";/// How many `_writes` rows one [`trim_step`] reads at most: each step holds the writer, and at 500 one/// step on the big-account run held it 31 s on a loaded box (21 Nov 2026).pubconst TRIM_PAGE: i64 = 100;/// The field set `names` (canonical JSON of the names, in order) at `schema`,/// made once.fn set_id(db: &Driver, schema: u32, names: &str) -> Result<i64> { db.run("INSERT OR IGNORE INTO _field_sets (schema, names) VALUES (?1, ?2)", &[SqlValue::Integer(i64::from(schema)), SqlValue::Text(names.to_string())], )?;Ok(db .get("SELECT id FROM _field_sets WHERE schema = ?1 AND names = ?2", &[SqlValue::Integer(i64::from(schema)), SqlValue::Text(names.to_string())], )? .and_then(|row| row.int("id")) .unwrap_or(0))}fn set_of(db: &Driver, id: i64) -> Result<Option<(u32, Vec<String>)>> {letSome(row) = db.get("SELECT schema, names FROM _field_sets WHERE id = ?1", &[SqlValue::Integer(id)])? else {returnOk(None); };let schema = u32::try_from(row.int("schema").unwrap_or(0)).unwrap_or(0);let names: Vec<String> = serde_json::from_str(row.text("names").unwrap_or("[]")).unwrap_or_default();Ok(Some((schema, names)))}/// A stored value as a served receipt says it: in its column's storage form,/// as the object's values are minted (an integer flag as the integer).fn as_said(codec: crate::schema::decl::Codec, value: &SqlValue) -> Result<serde_json::Value> {Ok(match value {SqlValue::Null => serde_json::Value::Null,SqlValue::Integer(n) => serde_json::Value::from(*n),SqlValue::Real(x) => serde_json::Number::from_f64(*x).map_or(serde_json::Value::Null, serde_json::Value::Number),SqlValue::Text(text) => serde_json::Value::String(text.clone()),SqlValue::Blob(_) => decode_value(codec, value)?, })}/// The bytes a served receipt of `table`'s `row_id` would have, made from the/// row as it stands: `None` when the row is not here, or names a field this/// build's table does not keep.fn made_from_row(db: &Driver, table: &str, row_id: &str, stamp: &str, actor: &str, schema: u32, names: &[String]) -> Result<Option<Vec<u8>>> {letSome(spec) = spec_for(table) else { returnOk(None) };ifsuper::PER_KEY_COLUMNS.iter().any(|(t, _)| *t == table) {returnOk(None); }letSome(row) = db.get(&format!("SELECT * FROM \"{table}\" WHERE \"{}\" = ?", spec.pk), &[SqlValue::Text(row_id.to_string())])? else {returnOk(None); };letmut fields = std::collections::BTreeMap::new();for name in names {letSome((_, codec)) = spec.columns.iter().find(|(column, _)| column == name) else { returnOk(None) };let value = row.get(name).cloned().unwrap_or(SqlValue::Null); fields.insert(name.clone(), as_said(*codec, &value)?); }let receipt = Receipt { table: table.to_string(), row_id: row_id.to_string(), kind: Kind::Create, stamp: stamp.to_string(), author: OBJECT_AUTHOR.to_string(), actor: actor.to_string(), schema, fields, restamps: None, erase: None, undo: None, };Ok(Some(canonical::encode(&receipt)?))}/// A `_writes` row's bytes: as stored, or made again from its row when it is/// implied. `None` for a row that holds neither (a test's bare receipt).pub(crate) fn bytes_of(db: &Driver, row: &Row) -> Result<Option<Vec<u8>>> {match row.get("bytes") {Some(SqlValue::Blob(bytes)) => returnOk(Some(bytes.clone())),Some(SqlValue::Text(text)) => returnOk(Some(text.as_bytes().to_vec())), _ => {} }letSome(set) = row.int("implied") else { returnOk(None) };letSome((schema, names)) = set_of(db, set)? else { returnOk(None) }; made_from_row( db, row.text("tbl").unwrap_or_default(), row.text("row_id").unwrap_or_default(), row.text("hlc").unwrap_or_default(), row.text("actor").unwrap_or_default(), schema, &names, )}/// Imply the receipt `op_id` when it may be: the object's, not held, a/// create, unsigned, no retract beside it, and its bytes made from the row/// equal to its bytes as minted — so the row says every field it names, as/// it names it (another receipt of the row, an older create kept for the/// row's birth or a change of the phone's own to a field it does not name,/// may stand beside it). Whether it was.pubfn imply(db: &Driver, op_id: &str) -> Result<bool> {if !implies(db)? {returnOk(false); }letSome(row) = db.get("SELECT w.tbl, w.row_id, w.hlc, w.author, w.actor, w.kind, w.held, w.sig, w.bytes, w.implied, \ EXISTS (SELECT 1 FROM _tombstones t WHERE t.tbl = w.tbl AND t.row_id = w.row_id) AS retracted \ FROM _writes w WHERE w.op_id = ?1", &[SqlValue::Text(op_id.to_string())], )?else {returnOk(false); };if row.text("author") != Some(OBJECT_AUTHOR) || row.int("held") != Some(0) || row.text("kind") != Some("create") || !matches!(row.get("sig"), None | Some(SqlValue::Null)) || row.int("implied").is_some() || row.int("retracted") != Some(0) {returnOk(false); }let bytes = match row.get("bytes") {Some(SqlValue::Blob(bytes)) => bytes.clone(),Some(SqlValue::Text(text)) => text.as_bytes().to_vec(), _ => returnOk(false), };let receipt = canonical::decode(&bytes)?;if receipt.restamps.is_some() || receipt.erase.is_some() || receipt.undo.is_some() {returnOk(false); }let names: Vec<String> = receipt.fields.keys().cloned().collect();let table = row.text("tbl").unwrap_or_default();let row_id = row.text("row_id").unwrap_or_default();let made = made_from_row(db, table, row_id, &receipt.stamp, &receipt.actor, receipt.schema, &names)?;if made.as_deref() != Some(bytes.as_slice()) {returnOk(false); }let set = set_id(db, receipt.schema, &serde_json::to_string(&names).unwrap_or_else(|_| "[]".into()))?; db.run("UPDATE _writes SET bytes = NULL, fields = NULL, implied = ?1 WHERE op_id = ?2", &[SqlValue::Integer(set), SqlValue::Text(op_id.to_string())], )?;Ok(true)}/// Put every implied receipt of `table`'s `row_id` back whole, from the row/// while it still says it: called before any other receipt of the row is/// stored, so every merge reads the bytes as minted.pubfn materialize_row(db: &Driver, table: &str, row_id: &str) -> Result<()> {if !implies(db)? {returnOk(()); }let implied = db.all("SELECT op_id, tbl, row_id, hlc, actor, implied FROM _writes WHERE tbl = ?1 AND row_id = ?2 AND implied IS NOT NULL", &[SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())], )?;for row in implied {letSome(bytes) = bytes_of(db, &row)? else {returnErr(crate::error::StoreError::encode(format!("the implied receipt of {table} {row_id} cannot be made again: its row is not here" ))); };let receipt = canonical::decode(&bytes)?; db.run("UPDATE _writes SET bytes = ?1, fields = ?2, implied = NULL WHERE op_id = ?3", &[SqlValue::Blob(bytes),SqlValue::Text(super::field_names(&receipt)),SqlValue::Text(row.text("op_id").unwrap_or_default().to_string()), ], )?; }Ok(())}/// One bounded step of trimming a copy in place: up to [`TRIM_PAGE`]/// receipts of the object after `after` (a `_writes` rowid), each implied/// when it may be. `(next, implied)`: `next` is `None` when the walk is done.pubfn trim_step(db: &Driver, after: i64) -> Result<(Option<i64>, usize)> {if !implies(db)? {returnOk((None, 0)); }let rows = db.all("SELECT rowid AS at, op_id FROM _writes WHERE rowid > ?1 ORDER BY rowid LIMIT ?2", &[SqlValue::Integer(after), SqlValue::Integer(TRIM_PAGE)], )?;letmut implied = 0;for row in &rows {ifletSome(op_id) = row.text("op_id") {if imply(db, op_id)? { implied += 1; } } }let next = (rows.len() as i64 == TRIM_PAGE).then(|| rows.last().and_then(|row| row.int("at")).unwrap_or(after));Ok((next, implied))}/// A field of a `_writes` row `alias` of `table`, as SQL: the receipt's own/// when it holds its bytes, the row's column when it holds none (an implied/// receipt, whose row says every field it names) — what `json_extract(CAST(/// bytes AS TEXT), '$.fields."<column>"')` said before receipts could be/// implied. It names no 151 column, so it reads a file of any shape.pub(crate) fn field_sql(alias: &str, table: &str, column: &str) -> String {let pk = spec_for(table).map(|spec| spec.pk).unwrap_or("id"); format!("CASE WHEN {alias}.bytes IS NOT NULL THEN json_extract(CAST({alias}.bytes AS TEXT), '$.fields.\"{column}\"') \ ELSE (SELECT r.\"{column}\" FROM \"{table}\" r WHERE r.\"{pk}\" = {alias}.row_id) END" )}/// Whether this file is of a shape that implies receipts (151 or later):/// a file at an earlier shape, folded by this build before it moves, keeps/// every receipt whole.fn implies(db: &Driver) -> Result<bool> {Ok(db.get("SELECT 1 AS here FROM pragma_table_info('_writes') WHERE name = 'implied'", &[])?.is_some())}/// Make whole every implied receipt of `table`'s rows that `ids` (SQL/// selecting row ids, bound with `args`) names, before those rows leave the/// table: a receipt is implied only while its row is here.pubfn materialize_rows(db: &Driver, table: &str, ids: &str, args: &[SqlValue]) -> Result<()> {if !implies(db)? {returnOk(()); }letmut params = vec![SqlValue::Text(table.to_string())]; params.extend(args.iter().cloned());let rows = db.all(&format!("SELECT DISTINCT row_id FROM _writes WHERE tbl = ?1 AND implied IS NOT NULL AND row_id IN ({ids})"), ¶ms)?;for row in rows {ifletSome(id) = row.text("row_id") { materialize_row(db, table, id)?; } }Ok(())}/// Where the in-place trim stands: `(after, done)`.fn trim_at(db: &Driver) -> Result<(i64, bool)> {Ok(db .get("SELECT after, done FROM _trim WHERE only_one = 1", &[])? .map_or((0, false), |row| (row.int("after").unwrap_or(0), row.int("done") == Some(1))))}/// Carry the in-place trim of this copy at most `steps` bounded steps on,/// each in its own transaction, and keep where it stands. `(implied, done)`./// A copy made at 151 or later trims as it folds; this walks one made before.pubfn carry(db: &Driver, steps: usize) -> Result<(usize, bool)> {letmut implied = 0;for _ in0..steps {let (after, done) = trim_at(db)?;if done {returnOk((implied, true)); }let finished = db.transaction(|db| {let (next, n) = trim_step(db, after)?; implied += n; db.run("INSERT INTO _trim (only_one, after, done) VALUES (1, ?1, ?2) \ ON CONFLICT(only_one) DO UPDATE SET after = excluded.after, done = excluded.done", &[SqlValue::Integer(next.unwrap_or(after)), SqlValue::Integer(i64::from(next.is_none()))], )?;Ok(next.is_none()) })?;if finished {returnOk((implied, true)); } }Ok((implied, trim_at(db)?.1))}