//! Slice 4, V11-1 (b): the identity columns of a device row and an MCP token //! row are written only by the op that creates the row. A `change` receipt //! naming one is refused on every device, whatever its stamp and whatever the //! row's state there, and an arrival parks it `conflict` — and a parked write //! comes back only through the same arrival checks, so a retry never lands //! what the first arrival refused. use cotton_store::actor::{Actor, JobName}; use cotton_store::exchange::{fold_answer, Handed, Handover}; use cotton_store::fold::{fold_ops, fold_pulled, IDENTITY_WRITE_ONCE}; use cotton_store::meta::{seed_meta, Meta}; use cotton_store::migrate::{migrate_store, SCHEMA_VERSION}; use cotton_store::mint::Change; use cotton_store::protocol::hlc::next_hlc; use cotton_store::protocol::types::{CottonOp, ExchangeResponse}; use cotton_store::rejected::{park, retry_rejected, sweep_parked, list_parked, Class, Direction, PARK_SWEEP_OPS}; use cotton_store::wire::op_of_change; use cotton_store::Driver; use rusqlite::types::Value; use serde_json::{json, Map, Value as JsonValue}; const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111"; const NOW: &str = "2026-10-04T09:00:00.000Z"; const LATER: &str = "2026-10-04T10:00:00.000Z"; const PEER: &str = "device:01JPEERMAC00000000000000000"; fn text(value: &str) -> Value { Value::Text(value.to_string()) } /// A real file at this build's schema, with an identity and the workspace /// row every device and token row points at. fn file() -> Driver { let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: "owner-1".to_string(), device_id: "device:mine".to_string(), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds the 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 } fn object(value: JsonValue) -> Map { value.as_object().cloned().expect("an object") } thread_local! { static SCHEMA: Driver = { let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); db }; } fn receipt(change: Change, n: u32, ms: i64) -> CottonOp { let hlc = next_hlc(PEER, None, ms).expect("a stamp"); let actor = Actor::device_job(JobName::named("test").expect("a job name")); SCHEMA .with(|db| op_of_change(db, &change, &hlc, PEER, &actor, format!("op-{n:06}"))) .expect("a receipt") } fn device_create(n: u32) -> CottonOp { receipt( Change::create( "cotton_devices", "device-row-1", object(json!({ "id": "device-row-1", "workspace_id": WORKSPACE, "device_id": "a-phone-key", "name": "An iPhone", "platform": "ios", "approved_at": NOW, "approved_by_device": "self", "created_at": NOW, "updated_at": NOW, })), ), n, 1_790_000_000_000, ) } fn token_create(n: u32) -> CottonOp { receipt( Change::create( "cotton_mcp_tokens", "token-row-1", object(json!({ "id": "token-row-1", "workspace_id": WORKSPACE, "owner_user_id": "owner-1", "name": "a token", "token_hash": "0f".repeat(32), "scopes": "[]", "created_at": NOW, })), ), n, 1_790_000_000_000, ) } /// A change of `column` on the row of `table`, to a value of its shape. fn identity_change(table: &str, column: &str, n: u32) -> CottonOp { let row = match table { "cotton_devices" => "device-row-1", "cotton_workspaces" => WORKSPACE, _ => "token-row-1", }; let value = match column { "workspace_id" => json!(WORKSPACE), "relay_domain" => json!("relay.example.org"), "relay_tunnel_host" => json!("tunnel.example.org"), "token_hash" => json!("1e".repeat(32)), "scopes" => json!("[\"admin\"]"), "scope" => json!("runner"), _ => json!("2026-10-04T09:30:00.000Z"), }; receipt( Change::update(table, row, object(json!({ column: value }))), n, 1_790_000_100_000 + i64::from(n), ) } fn page(ops: Vec) -> ExchangeResponse { ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WORKSPACE.to_string(), schema_version: Some(SCHEMA_VERSION), cursors: ops.iter().map(|op| (op.device_id.clone(), op.hlc.clone())).collect(), ops, has_more: false, applied_rows: Default::default(), rejected: Vec::new(), seen: Default::default(), serving_epoch: None, server_time: None, restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, } } fn take(db: &Driver, ops: Vec) { fold_answer(db, &Handed::nothing(WORKSPACE), &page(ops), NOW, &mut Handover::default()) .expect("the page folds"); } fn column_of(db: &Driver, table: &str, column: &str) -> Option { db.get(&format!("SELECT {column} AS v FROM {table}"), &[]) .expect("reads") .and_then(|row| row.text("v").map(str::to_string)) } /// RULE: A change naming an identity column of a device row, an MCP token row or a database's own row never lands, on any device, whatever its stamp or the row's state; an arrival parks it `conflict`, and the row keeps what its create wrote. #[test] fn device_and_token_identity_columns_are_write_once() { let mut n = 10; for (table, columns) in IDENTITY_WRITE_ONCE { for column in *columns { // No row here yet: refused all the same, a pure function of the // receipt — the order two devices hear a create and a change in // never decides the outcome. let empty = file(); n += 1; let change = identity_change(table, column, n); let pulled = fold_pulled(&empty, std::slice::from_ref(&change)).expect("folds"); assert_eq!(pulled.rejected.len(), 1, "{table}.{column} with no row: {pulled:?}"); let handed = fold_ops(&empty, std::slice::from_ref(&change)).expect("folds"); assert_eq!(handed.rejected.len(), 1, "{table}.{column} handed over: {handed:?}"); // A live row: refused, and the page parks it `conflict`. let db = file(); // (A database's own row is already in `file()`.) match *table { "cotton_devices" => drop(fold_pulled(&db, &[device_create(1)]).expect("the create folds")), "cotton_mcp_tokens" => drop(fold_pulled(&db, &[token_create(1)]).expect("the create folds")), _ => {} } let before = column_of(&db, table, column); n += 1; take(&db, vec![identity_change(table, column, n)]); assert_eq!(column_of(&db, table, column), before, "{table}.{column} kept its create's value"); let parked = list_parked(&db, 10).expect("the parked list"); assert_eq!(parked.len(), 1, "{table}.{column}: {parked:?}"); assert_eq!(parked[0].class, "conflict", "{table}.{column}"); assert!(parked[0].reason.contains("written once"), "{}", parked[0].reason); } } // Columns that are not identity stay free: the session host's sample of // a device, a token's revoke. let db = file(); fold_pulled(&db, &[device_create(1), token_create(2)]).expect("the creates fold"); let free = [ receipt(Change::update("cotton_devices", "device-row-1", object(json!({"app_version": "1.0"}))), 3, 1_790_000_200_000), receipt(Change::update("cotton_mcp_tokens", "token-row-1", object(json!({"revoked_at": LATER}))), 4, 1_790_000_200_001), ]; let result = fold_pulled(&db, &free).expect("folds"); assert_eq!(result.applied.len(), 2, "{result:?}"); } /// RULE: The relay a household is reached through is fixed when its database is made — no change of `relay_domain` or `relay_tunnel_host` lands on any device, from any writer, not even from empty — because those two values are where every Mac of the household dials and under whose domain it orders its certificate. A database made without them (the owner's) is on Cotton's relay for good. #[test] fn a_households_relay_cannot_be_changed_after_its_database_is_made() { let db = file(); let unset = |db: &Driver| { db.get("SELECT relay_domain, relay_tunnel_host FROM cotton_workspaces", &[]) .expect("reads") .map(|row| (row.text("relay_domain").map(str::to_string), row.text("relay_tunnel_host").map(str::to_string))) }; assert_eq!(unset(&db), Some((None, None)), "a database is made on Cotton's relay"); // Both at once — a whole address, the only shape a reader would take. let moved = receipt( Change::update( "cotton_workspaces", WORKSPACE, object(json!({ "relay_domain": "relay.example.org", "relay_tunnel_host": "tunnel.example.org" })), ), 40, 1_790_000_300_000, ); let handed = fold_ops(&db, std::slice::from_ref(&moved)).expect("folds"); assert_eq!(handed.rejected.len(), 1, "{handed:?}"); take(&db, vec![moved]); assert_eq!(unset(&db), Some((None, None)), "and it is still there"); let parked = list_parked(&db, 10).expect("the parked list"); assert!(parked.iter().any(|row| row.class == "conflict" && row.reason.contains("written once")), "{parked:?}"); // The name beside it is NOT fixed: a household may still be named. let named = receipt( Change::update("cotton_workspaces", WORKSPACE, object(json!({ "relay_name": "harbour-lamp" }))), 41, 1_790_000_300_001, ); assert_eq!(fold_pulled(&db, &[named]).expect("folds").applied.len(), 1); } /// RULE: A parked write is offered again only through `fold::arrive`, so a retry meets every arrival check and never lands what an arrival would refuse. #[test] fn parked_op_reapplies_only_through_arrival_checks() { let db = file(); fold_pulled(&db, &[token_create(1)]).expect("the create folds"); // Parked as if it were only waiting: a retry that skipped the arrival // checks would land it and end the park. let forged = identity_change("cotton_mcp_tokens", "token_hash", 2); park(&db, &forged, Direction::Pull, Class::Waiting, "waiting: a parent", NOW).expect("parks"); let report = retry_rejected(&db, None, LATER).expect("a retry"); assert!(report.folded.is_empty(), "{report:?}"); sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); let parked = list_parked(&db, 10).expect("the parked list"); assert_eq!(parked.len(), 1, "{parked:?}"); assert_eq!(parked[0].class, "conflict", "the arrival's own verdict replaced the waiting one"); assert_eq!( column_of(&db, "cotton_mcp_tokens", "token_hash"), Some("0f".repeat(32)), "the token still authenticates only the secret it was minted for" ); }