//! The device row travels, and a revocation survives the journey (version 9).//!//! `cotton_devices` is the first row in the file whose whole point is that//! several MACHINES write it and one of them may be revoked while it writes.//! Two rules answer that, and both are asserted here through a real//! `fold_ops` rather than through a unit test of the arithmetic://!//! 1. **A revocation is a fact** — `cotton_revocations`, never updated or//! deleted (`tests/facts_in_the_fold.rs`); `revoked_at` is its mirror and//! settles by the clock like any column.//! 2. **A clearing patch is REJECTED** — the fence refuses an arriving change//! that names a mirror column as NULL, whatever the row holds, and says//! which op and why.//!//! The identity-shaped fence — "and the author of this op IS the device the row//! is about" — is deliberately NOT here: an op's `device_id` is an AUTHOR id//! minted by the file's own replica and a device row's `device_id` is a//! CREDENTIAL id, and `cotton_client::replica::resolve_device_id` says why//! conflating them is not on offer. That fence lives at the server's//! chokepoint, which holds the key that signed.//!//! Every row is synthetic and every value invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use cotton_store::actor::{Actor, JobName};use cotton_store::fold::{fold_ops, policy_for, Policy, COLUMN_POLICIES};use cotton_store::migrate::migrate_store;use cotton_store::mint::Change;use cotton_store::protocol::hlc::next_hlc;use cotton_store::protocol::types::CottonOp;use cotton_store::wire::op_of_change;use cotton_store::{Driver, Row};use rusqlite::types::Value;use serde_json::{json, Map, ValueasJsonValue};const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";const NOW: &str = "2026-09-16T09:00:00.000Z";/// The Mac that admitted the phone, as an op AUTHOR.const STUDY: &str = "device:01JSTUDYMAC0000000000000000";/// The other Mac of the same household — the one that has not heard yet.const KITCHEN: &str = "device:01JKITCHENMAC000000000000000";/// The device row's own key — a CREDENTIAL id, invented.const PHONE_KEY: &str = "a-synthetic-phone-key";const EARLY: &str = "2026-09-16T10:00:00.000Z";const LATER: &str = "2026-09-16T18:00:00.000Z";fn text(value: &str) -> Value {Value::Text(value.to_string())}/// A real file at `SCHEMA_VERSION`, with the workspace row every device row's/// foreign key points at.fn file() -> Driver {let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); 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 patch(value: JsonValue) -> Option<Map<String, JsonValue>> {match value {JsonValue::Object(map) => Some(map), other => panic!("a patch is an object, got {other}"), }}thread_local! {/// A file at this build's schema, which is all a receipt is built against.static SCHEMA: Driver = {let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); db };}/// The op for `change`, its receipt as `mint` would make it.fn receipt_op(change: Change, n: u32, author: &str, ms: i64) -> CottonOp {let hlc = next_hlc(author, None, ms).expect("a stamp in range");let actor = Actor::device_job(JobName::named("test").expect("a job name")); SCHEMA .with(|db| op_of_change(db, &change, &hlc, author, &actor, format!("op-{n:06}"))) .expect("a receipt")}/// A change to the device row.fn op(n: u32, author: &str, ms: i64, body: JsonValue) -> CottonOp {let patch = patch(body).expect("a patch"); receipt_op(Change::update("cotton_devices", "device-row-1", patch), n, author, ms)}/// The device row's retract.fn retract(n: u32, author: &str, ms: i64) -> CottonOp { receipt_op(Change::retract("cotton_devices", "device-row-1"), n, author, ms)}/// The whole row, as the approving Mac first writes it.fn approval(n: u32, author: &str, ms: i64) -> CottonOp { receipt_op(Change::create("cotton_devices","device-row-1", patch(json!({"id": "device-row-1","workspace_id": WORKSPACE,"device_id": PHONE_KEY,"name": "An invented iPhone","scope": "runner", "takes_placements": false,"platform": "ios","approved_at": NOW,"approved_by_device": "self","created_at": NOW,"updated_at": NOW, })) .expect("a patch"), ), n, author, ms, )}fn row(db: &Driver) -> Row { db.get("SELECT * FROM cotton_devices WHERE id = 'device-row-1'", &[]) .expect("reads") .expect("the device row")}/// RULE: No policy settles `revoked_at` any more — a revocation is a fact, the column its mirror — and the fold still refuses an arriving write that clears a mirror this file holds set.#[test]fn the_fence_still_refuses_a_clearing_receipt_now_the_policy_is_gone() { assert_eq!( COLUMN_POLICIES, &[ ("cotton_oauth_grants", "refresh_generation", Policy::MaxNonNull), ("cotton_oauth_grants", "refresh_rotated_at", Policy::MaxNonNull), ("cotton_oauth_grants", "refresh_digest", Policy::MaxNonNull), ],"the refresh chain is what is left: its position cannot be wound back into the window \ where a spent token is honoured" );for table in ["cotton_devices", "cotton_oauth_grants", "cotton_code_credentials"] { assert_eq!(policy_for(table, "revoked_at"), Policy::Lww); }let db = file(); fold_ops(&db, &[approval(1, STUDY, 1_700_000_000_000)]).expect("folds"); fold_ops( &db, &[op(2, STUDY, 1_700_000_050_000, json!({ "revoked_at": EARLY }))], ) .expect("folds");let clear = op(3, KITCHEN, 1_700_000_200_000, json!({ "revoked_at": JsonValue::Null }));let result = fold_ops(&db, &[clear]).expect("folds"); assert!(result.applied.is_empty()); assert!( result.rejected[0].reason.contains("a revoked row is not un-revoked by a patch"),"got {:?}", result.rejected[0].reason ); assert_eq!(row(&db).text("revoked_at"), Some(EARLY));}/// Two Macs each set the mirror: the column is on the clock like any other,/// so both files end at the later STAMP's value whichever arrives first. The/// record of truth is the pair of facts, which never clash.#[test]fn two_mirror_writes_converge_on_the_later_stamp_in_either_order() {let study = || op(2, STUDY, 1_700_000_050_000, json!({ "revoked_at": EARLY, "revoked_by_device": "study" }));let kitchen = || op(3, KITCHEN, 1_700_000_100_000, json!({ "revoked_at": LATER, "revoked_by_device": "kitchen" }));for order in [[study(), kitchen()], [kitchen(), study()]] {let db = file(); fold_ops(&db, &[approval(1, STUDY, 1_700_000_000_000)]).expect("folds");for write in order { fold_ops(&db, &[write]).expect("folds"); }let after = row(&db); assert_eq!(after.text("revoked_at"), Some(LATER)); assert_eq!(after.text("revoked_by_device"), Some("kitchen")); }}#[test]fn a_patch_that_clears_the_revocation_is_rejected_and_says_so() {let db = file(); fold_ops(&db, &[approval(1, STUDY, 1_700_000_000_000)]).expect("folds"); fold_ops( &db, &[op(2, STUDY,1_700_000_050_000, json!({ "revoked_at": EARLY, "revoked_by_device": "study" }), )], ) .expect("folds");// The revoked device's own last act, replayed by the merge: a newer stamp,// the whole row, and `revoked_at` back to null.let resurrect = op(3, KITCHEN,1_700_000_200_000, json!({"revoked_at": JsonValue::Null,"revoked_by_device": JsonValue::Null,"revoked_reason": JsonValue::Null,"name": "A renamed iPhone", }), );let result = fold_ops(&db, &[resurrect]).expect("folds"); assert!(result.applied.is_empty(), "nothing of it lands"); assert_eq!(result.rejected.len(), 1); assert_eq!(result.rejected[0].op_id, "op-000003"); assert!( result.rejected[0] .reason .contains("a revoked row is not un-revoked by a patch: cotton_devices"),"the rejection names the rule, got {:?}", result.rejected[0].reason );let after = row(&db); assert_eq!(after.text("revoked_at"), Some(EARLY)); assert_eq!( after.text("name"),Some("An invented iPhone"),"the WHOLE op is refused, not merely its null: a patch that tried to bring a revoked key \ back is not a patch whose other columns are trustworthy" );}#[test]fn a_patch_that_does_not_name_the_revocation_is_ordinary_and_lands() {let db = file(); fold_ops(&db, &[approval(1, STUDY, 1_700_000_000_000)]).expect("folds"); fold_ops( &db, &[op(2, STUDY,1_700_000_050_000, json!({ "revoked_at": EARLY }), )], ) .expect("folds");// Renaming a revoked device is allowed — the row is the audit, and the// fence is about the one column that decides admission.let rename = op(3, KITCHEN,1_700_000_200_000, json!({ "name": "The iPhone that was revoked" }), );let result = fold_ops(&db, &[rename]).expect("folds"); assert_eq!(result.applied, vec!["op-000003".to_string()]);let after = row(&db); assert_eq!(after.text("name"), Some("The iPhone that was revoked")); assert_eq!(after.text("revoked_at"), Some(EARLY));}/// RULE: The fence asks the receipt, not the row: a change naming a mirror column as NULL is refused on a live row too, because the revoke it would clear may simply not have arrived here yet.#[test]fn a_clearing_patch_on_a_live_row_is_refused_too() {let db = file(); fold_ops(&db, &[approval(1, STUDY, 1_700_000_000_000)]).expect("folds");let clearing = op(2, KITCHEN,1_700_000_100_000, json!({ "revoked_at": JsonValue::Null, "name": "A renamed iPhone" }), );let result = fold_ops(&db, &[clearing]).expect("folds"); assert!(result.applied.is_empty(), "nothing of it lands"); assert_eq!(result.rejected.len(), 1); assert!( result.rejected[0].reason.contains("a revoked row is not un-revoked by a patch: cotton_devices"),"got {:?}", result.rejected[0].reason );let after = row(&db); assert_eq!(after.text("name"), Some("An invented iPhone")); assert_eq!(after.text("revoked_at"), None);}/// RULE: A revocation outlives a retract of its row (design 3.7 point 3): a create at the same id brings the row back revoked, so a re-admitted key is a NEW row beside the revoked one, never the old row with its revocation cleared./// RULE: A removed device's approval remains as a revocation audit; a retract is refused, and rejoining creates a new approval rather than clearing the old revocation.#[test]fn a_revoked_key_comes_back_as_a_new_row_rather_than_as_a_cleared_column() {let db = file(); fold_ops(&db, &[approval(1, STUDY, 1_700_000_000_000)]).expect("folds"); fold_ops( &db, &[op(2, STUDY,1_700_000_050_000, json!({ "revoked_at": EARLY }), )], ) .expect("folds");let remove = retract(3, STUDY, 1_700_000_100_000);let refused = fold_ops(&db, &[remove]).expect("folds"); assert!(refused.applied.is_empty()); assert!(refused.parked.iter().any(|rejection| rejection.reason.contains("revoking their key")), "a peer receipt is parked as a conflict, never applied: {refused:?}"); assert_eq!(row(&db).text("revoked_at"), Some(EARLY), "the approval audit stays"); fold_ops(&db, &[approval(4, STUDY, 1_700_000_150_000)]).expect("folds");let after = row(&db); assert_eq!( after.text("revoked_at"),Some(EARLY),"a create at the same id does not un-say the revocation" );let again = receipt_op(Change::create("cotton_devices","device-row-2", patch(json!({"workspace_id": WORKSPACE,"device_id": PHONE_KEY,"name": "An invented iPhone","platform": "ios","approved_at": LATER,"approved_by_device": "self","created_at": LATER,"updated_at": LATER, })) .expect("a patch"), ),5, STUDY,1_700_000_200_000, );let result = fold_ops(&db, &[again]).expect("folds"); assert!(result.rejected.is_empty(), "{:?}", result.rejected);let admitted = db .get("SELECT * FROM cotton_devices WHERE id = 'device-row-2'", &[]) .expect("reads") .expect("the new approval row"); assert_eq!(admitted.text("revoked_at"), None, "the new row is a live admission"); assert_eq!(admitted.text("device_id"), Some(PHONE_KEY));}/// RULE: A device row's `superseded by …` reason beats any other reason whatever the stamps, and its `revoked_by_device` comes from the same receipt, so a `lost` written offline above the take-over act converges everywhere.#[test]fn superseded_reason_converges_on_the_writer_that_relabelled_it() {// The take-over act's revoke, and a phone's `lost` written offline a// minute later — heard in opposite orders by the new Mac and the phone.let act = op(2, STUDY,1_700_000_100_000, json!({ "revoked_at": EARLY, "revoked_by_device": "new-mac", "revoked_reason": "superseded by new-mac" }), );let lost = op(3, KITCHEN,1_700_000_160_000, json!({ "revoked_at": LATER, "revoked_by_device": "the-phone", "revoked_reason": "lost" }), );letmut ends = Vec::new();for order in [[act.clone(), lost.clone()], [lost, act]] {let db = file(); fold_ops(&db, &[approval(1, STUDY, 1_700_000_000_000)]).expect("folds");for receipt in order { fold_ops(&db, &[receipt]).expect("folds"); }let after = row(&db); ends.push(( after.text("revoked_reason").map(str::to_string), after.text("revoked_by_device").map(str::to_string), )); } assert_eq!(ends[0], ends[1], "both orders end the same"); assert_eq!( ends[0], (Some("superseded by new-mac".to_string()), Some("new-mac".to_string())),"the act's reason and its writer stand" );}