//! A server-only table is written like any other row and handed over to//! nobody (version 13).//!//! `cotton_mcp_audit` answers "what did an assistant do in my database". It is//! asked on the server, of the server, by the transparency log — and there are//! about two hundred thousand rows of it on the owner's own file, none of which//! any screen on a phone opens. Handing them over spends a phone's first sync//! on rows nothing there will ever read.//!//! This is NOT a retirement. R96's `retired_tables` means the name is gone and//! the fold must step over it; here the table is live, the server reads and//! writes it every day, and a build that already handed rows over must still//! take them back rather than parking them in `_parked`. So the exclusion//! is its own named list with its own three readers, and this file asks each of//! them.//!//! Every row is synthetic and every value invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use std::collections::BTreeMap;use cotton_store::exchange::answer;use cotton_store::migrate::{is_retired_table, migrate_store};use cotton_store::actor::{Actor, JobName};use cotton_store::mint::{changes_of, mint, Act, Clock, Held, History};use cotton_store::outbox::LocalChange;use cotton_store::protocol::types::OpKind;use cotton_store::protocol::ulid::Monotonic;use cotton_store::schema::table_specs::{ handed_over_specs, is_server_only, SERVER_ONLY_TABLES, TABLE_SPECS,};use cotton_store::snapshot::NOT_ON_A_PHONE;use cotton_store::{Driver, Row};use rusqlite::types::Value;use serde_json::json;const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";/// An explicit instant, never the wall clock.const NOW: &str = "2026-09-17T09:00:00.000Z";const NOW_MS: i64 = 1_789_635_000_000;const DEVICE: &str = "device:01J0000000000000000000000A";fn text(value: &str) -> Value {Value::Text(value.to_string())}fn one(db: &Driver, sql: &str) -> Row { db.get(sql, &[]).expect("reads").expect("a row")}/// A real file at `SCHEMA_VERSION`, with the rows the two writes need.fn file() -> Driver {let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); cotton_store::meta::seed_meta( &db, &cotton_store::meta::Meta { workspace_id: WORKSPACE.to_string(), owner_id: "owner-1".to_string(), device_id: DEVICE.to_string(), last_server_seq: 0, last_hlc: None, }, cotton_store::migrate::SCHEMA_VERSION, ) .expect("the file's own identity"); db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[ text(WORKSPACE), text("A workspace"), text("owner-1"), text(NOW), ], ) .expect("the workspace row"); db.run("INSERT INTO cotton_mcp_tokens (id, owner_user_id, workspace_id, name, token_hash, \ scopes, created_at) VALUES (?,?,?,?,?,?,?)", &[ text("token-1"), text("owner-1"), text(WORKSPACE), text("A synthetic assistant"), text(&"a".repeat(64)),// A JSON array, because the column's codec is Json and this row is// in the origin stream like any other. text(r#"["read","write"]"#), text(NOW), ], ) .expect("the token row"); db}fn audit_row(id: &str) -> LocalChange {LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_mcp_audit".to_string(), row_id: id.to_string(), patch: json!({"id": id,"token_id": "token-1","workspace_id": WORKSPACE,"tool": "list_todos","args_summary": "{}","ok": true,"created_at": NOW, }) .as_object() .cloned(), }}fn a_todo(id: &str) -> LocalChange {LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: "cotton_todos".to_string(), row_id: id.to_string(), patch: json!({"id": id,"workspace_id": WORKSPACE,"title": "A synthetic errand nobody has to run","created_at": NOW,"updated_at": NOW, }) .as_object() .cloned(), }}/// A boxed seed so the signature below names one concrete type.typeSeededIds = Monotonic<Box<dynFnMut(&mut [u8])>>;fn ids() -> SeededIds {// Every fill draws from one counter, high in the bytes so the ids a// `Monotonic` counts up within one write never reach the next write's.static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);Monotonic::new(Box::new(|bytes: &mut [u8]| {let next = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed).to_be_bytes(); bytes.fill(0);let take = bytes.len().min(next.len()); bytes[..take].copy_from_slice(&next[next.len() - take..]); }))}/// One write through the one write path, held as `held`. Op ids are unique/// across calls: the same id again is a replay of the same write.fn write_held(db: &Driver, changes: &[LocalChange], held: Held, verb: &str) {letmut source = ids(); mint( db, &Act { actor: Actor::DeviceJob(JobName::named("test").expect("a job name")), verb: verb.to_string(), history: History::None, changes: changes_of(db, changes), }, &Clock::wall(NOW_MS), &mut source, held, ) .expect("the write");}/// The server's own write: stamped and folded, queued for nobody.fn write_as_the_server(db: &Driver, changes: &[LocalChange]) { write_held(db, changes, Held::Served, "the server's own write");}// ── the stream ──────────────────────────────────────────────────────────────#[test]fn a_pull_carries_the_ordinary_row_and_never_the_audit_line() {let db = file(); write_as_the_server(&db, &[a_todo("todo-1"), audit_row("audit-1")]);// Both rows are IN the file — this is not a retirement, and nothing was// dropped. assert_eq!( one(&db, "SELECT count(*) AS c FROM cotton_mcp_audit").int("c"),Some(1) );let answered = answer(&db, &BTreeMap::new(), 5_000).expect("answers");let tables: Vec<&str> = answered.ops.iter().map(|op| op.table.as_str()).collect(); assert!( tables.contains(&"cotton_todos"),"an ordinary row still goes out" ); assert!( !tables.contains(&"cotton_mcp_audit"),"the audit line is served to nobody, whatever the caller's cursor says" );}/// A row served by nobody must raise nobody's SERVE ceiling, or the author/// whose only newer write is that row reads as "behind" on every pass and is/// answered an empty page for ever — a caller that never stops asking and never/// gets anything.////// Asked the way the exchange asks it: a caller folds what it was given, records/// the stamps it saw, and comes back after the server has written an audit line/// and nothing else.#[test]fn an_audit_line_leaves_a_caught_up_caller_caught_up() {let db = file(); write_as_the_server(&db, &[a_todo("todo-1")]);let first = answer(&db, &BTreeMap::new(), 5_000).expect("answers"); assert!(!first.ops.is_empty());// What a caller holds after folding: the newest stamp it saw per author.letmut seen: BTreeMap<String, String> = BTreeMap::new();for op in &first.ops {let author = op.hlc.rsplit(':').next().unwrap_or_default().to_string();let entry = seen.entry(author).or_insert_with(|| op.hlc.clone());if op.hlc > *entry { *entry = op.hlc.clone(); } } seen.extend(first.seen.clone());// The server writes an audit line and nothing else. write_as_the_server(&db, &[audit_row("audit-1")]);let again = answer(&db, &seen, 5_000).expect("answers"); assert!( again.ops.is_empty(),"the audit line came back as work for a caller that is already caught up: {:?}", again.ops.iter().map(|op| &op.table).collect::<Vec<_>>() ); assert!(!again.has_more);}// ── the outbox ──────────────────────────────────────────────────────────────#[test]fn a_device_queues_the_ordinary_row_and_refuses_to_queue_the_audit_line() {let db = file(); write_held( &db, &[a_todo("todo-1"), audit_row("audit-1")],Held::Replica,"a device's own write", );// Both rows landed in the file; only one is queued for anybody. assert_eq!( one(&db, "SELECT count(*) AS c FROM cotton_mcp_audit").int("c"),Some(1) );let queued: Vec<String> = db .all("SELECT tbl FROM _outbox ORDER BY op_id", &[]) .expect("reads") .iter() .filter_map(|row| row.text("tbl").map(str::to_string)) .collect();// The first write in a file mints the file's author, and on a replica// that `cotton_authors` fact is queued ahead of the write like any other. assert_eq!(queued, ["cotton_authors", "cotton_todos"]);}// ── the list itself ─────────────────────────────────────────────────────────#[test]fn every_server_only_table_is_a_real_table_with_a_reason_and_is_not_retired() { assert!(!SERVER_ONLY_TABLES.is_empty());for (table, reason) in SERVER_ONLY_TABLES { assert!( TABLE_SPECS.iter().any(|spec| spec.name == *table),"{table} is server-only and has no spec — a table with no spec is excluded by the \ fold already, which is a different thing entirely" ); assert!( !is_retired_table(table),"{table} cannot be both live-on-the-server and retired" ); assert!( reason.len() > 40,"{table}: a \"no\" is never a bare flag, it is a written reason" ); assert!(is_server_only(table)); } assert!(!is_server_only("cotton_todos"));}/// The stream's list and the snapshot's are two halves of one promise: the/// exchange never hands a row over, and the bootstrap copy never carries the/// back catalogue. A table in one and not the other is a phone that starts with/// two hundred thousand rows it will never be sent again./// RULE: A table the server keeps to itself is never handed to a phone, in a live sync or in a first copy.#[test]fn a_server_only_table_is_stripped_out_of_a_phones_snapshot_too() {for (table, _) in SERVER_ONLY_TABLES { assert!( NOT_ON_A_PHONE.iter().any(|(name, _)| name == table),"{table} is never handed over and would still ride along in the snapshot" ); }}/// RULE: No metering table is in the synced set — `cotton_ai_calls` and `_ai_batches` are the serving Mac's own record of what it spent, read on other devices by one live call to that Mac, never handed over or copied to a phone — because one schema move minted twenty-one thousand of their receipts at once and they kept the owner's phone from syncing anything else (architect, 14 Oct 2026).#[test]fn no_metering_table_is_in_the_synced_set() {let handed: Vec<&str> = handed_over_specs().map(|spec| spec.name).collect();for table in cotton_store::schema::table_specs::METERING_TABLES { assert!(!handed.contains(table), "{table} is handed over"); assert!( cotton_store::snapshot::NOT_ON_A_PHONE.iter().any(|(name, _)| name == table),"{table} would reach a phone in its first copy" ); }}