//! Facts in the fold, and a device's standing read from them (slice 5a-i). //! //! A fact is a row that is only ever inserted: the fold takes one it does not //! hold, a replay changes nothing, and an update or a delete of one is never //! applied. `cotton_revocations` is the record of truth for revocation, and //! `revocation::device_standing` is its one reader. //! //! Every row is synthetic and every value invented //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). use cotton_store::actor::{Actor, DeviceId, JobName}; use cotton_store::fact_hooks::{fact_tables, is_fact_table, NO_SWAP_FACT_TABLES}; use cotton_store::fold::{arrive, fold_ops, Arrival}; 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::revocation::{device_standing, Standing}; 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-09-16T09:00:00.000Z"; const STUDY: &str = "device:01JSTUDYMAC0000000000000000"; const KITCHEN: &str = "device:01JKITCHENMAC000000000000000"; /// Device KEYS (credential ids), invented. const OLD_MAC: &str = "an-old-mac-key"; const NEW_MAC: &str = "a-new-mac-key"; const PHONE: &str = "a-synthetic-phone-key"; const T0: i64 = 1_700_000_000_000; // A claim is a separate signed fact: it may not update the admission or any // earlier claim. Every arrival order keeps both claims and the admission. #[test] fn member_person_claim_fold_preserves_admission_and_claim_facts() { let db = file(); let admission = receipt_op( Change::create( "cotton_admissions", "fern-admission", patch(json!({ "id":"fern-admission","workspace_id":WORKSPACE,"person_key":"invented-member", "person_name":"Mira Fern","rights":"member","invite_id":"fern-invite", "admitted_by_person":"invented-owner","p_sig":"original-admission-proof","admitted_at":NOW })), ), "fern-create", STUDY, T0, ); let claim = |id: &str, person: &str, ms| { receipt_op( Change::create( "cotton_member_person_claims", id, patch(json!({ "id":id,"workspace_id":WORKSPACE,"admission_id":"fern-admission","person_key":"invented-member", "person_id":person,"p_sig":"synthetic-proof","claimed_at":NOW })), ), id, STUDY, ms, ) }; let first = claim("fern-claim1", "fern-person1", T0 + 10); let second = claim("fern-claim2", "fern-person2", T0 + 20); for order in [ vec![first.clone(), second.clone()], vec![second.clone(), first.clone()], ] { let db = file(); assert_eq!( fold_ops(&db, std::slice::from_ref(&admission)) .unwrap() .applied .len(), 1 ); let born = db .get( "SELECT _born FROM cotton_admissions WHERE id='fern-admission'", &[], ) .unwrap() .unwrap() .text("_born") .unwrap() .to_string(); for op in order { assert_eq!(fold_ops(&db, &[op]).unwrap().applied.len(), 1); } assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM cotton_member_person_claims"), 2 ); for (table, id, fields) in [ ( "cotton_admissions", "fern-admission", json!({"rights":"admin"}), ), ( "cotton_member_person_claims", "fern-claim1", json!({"person_id":"another-person"}), ), ] { let op = receipt_op( Change::update(table, id, patch(fields)), "fern-bad", STUDY, T0 + 30, ); let refused = fold_ops(&db, &[op]).unwrap(); assert!(refused.applied.is_empty()); assert!(!refused.parked.is_empty()); } let held = db .get( "SELECT rights,p_sig,_born FROM cotton_admissions WHERE id='fern-admission'", &[], ) .unwrap() .unwrap(); assert_eq!(held.text("rights"), Some("member")); assert_eq!(held.text("p_sig"), Some("original-admission-proof")); assert_eq!(held.text("_born"), Some(born.as_str())); } assert!(is_fact_table("cotton_member_person_claims")); assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM cotton_member_person_claims"), 0 ); } fn text(value: &str) -> Value { Value::Text(value.to_string()) } 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) -> Map { match value { JsonValue::Object(map) => map, other => panic!("a patch is an object, got {other}"), } } thread_local! { static SCHEMA: Driver = { let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); db }; } fn receipt_op(change: Change, op_id: &str, 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, op_id.to_string())) .expect("a receipt") } /// One approval of a device key, at its own row id. fn approval(op_id: &str, row_id: &str, key: &str, approved_at: &str, ms: i64) -> CottonOp { receipt_op( Change::create( "cotton_devices", row_id, patch(json!({ "id": row_id, "workspace_id": WORKSPACE, "device_id": key, "name": "An invented device", "scope": "runner", "takes_placements": false, "approved_at": approved_at, "approved_by_device": "self", "created_at": approved_at, "updated_at": approved_at, })), ), op_id, STUDY, ms, ) } /// A revocation fact at a random-looking id, for the approval `subject`. fn fact(op_id: &str, id: &str, subject: &str, reason: &str, successor: Option<&str>, author: &str, ms: i64) -> CottonOp { receipt_op( Change::create( "cotton_revocations", id, patch(json!({ "id": id, "workspace_id": WORKSPACE, "subject_table": "cotton_devices", "subject_id": subject, "revoked_at": NOW, "actor": "owner:device-row-0", "reason": reason, "successor": successor, })), ), op_id, author, ms, ) } fn author_fact(op_id: &str, author_row: &str, device: &str, writer: &str, ms: i64) -> CottonOp { let hlc = next_hlc(writer, None, ms).expect("a stamp"); receipt_op( Change::create( "cotton_authors", author_row, patch(json!({ "id": author_row, "workspace_id": WORKSPACE, "device_id": device, "device_name": "An invented Mac", "minted_at": NOW, "reason": "first", "first_stamp": hlc, })), ), op_id, writer, ms, ) } fn count(db: &Driver, sql: &str) -> i64 { db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(0) } fn permutations(items: &[T]) -> Vec> { if items.len() <= 1 { return vec![items.to_vec()]; } let mut all = Vec::new(); for at in 0..items.len() { let mut rest = items.to_vec(); let first = rest.remove(at); for mut tail in permutations(&rest) { tail.insert(0, first.clone()); all.push(tail); } } all } /// RULE: A fact is only ever inserted: the fold never applies an update or a delete of a row in a fact table, from a peer or from this file's own writer, and the fact stays as it was first written. #[test] fn insert_only_fact_is_never_updated_or_deleted() { let db = file(); fold_ops(&db, &[approval("op-a", "row-1", PHONE, NOW, T0)]).expect("folds"); let result = fold_ops(&db, &[fact("op-f", "fact-1", "row-1", "revoked", None, STUDY, T0 + 10)]).expect("folds"); assert_eq!(result.applied, vec!["op-f".to_string()]); let update = receipt_op( Change::update("cotton_revocations", "fact-1", patch(json!({ "reason": "restored" }))), "op-u", KITCHEN, T0 + 20, ); let delete = receipt_op(Change::retract("cotton_revocations", "fact-1"), "op-d", KITCHEN, T0 + 30); for (write, word) in [(&update, "never updated"), (&delete, "never deleted")] { // A peer's parks; nothing of it lands. let result = fold_ops(&db, std::slice::from_ref(write)).expect("folds"); assert!(result.applied.is_empty(), "{word}: {result:?}"); assert_eq!(result.parked.len(), 1, "{word}: {result:?}"); assert!(result.parked[0].reason.contains(word), "got {:?}", result.parked[0].reason); // This file's own is refused to its writer. let result = arrive(&db, std::slice::from_ref(write), Arrival::Local).expect("folds"); assert!(result.applied.is_empty()); assert!(result.rejected[0].reason.contains(word), "got {:?}", result.rejected[0].reason); } assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM cotton_revocations WHERE id = 'fact-1' AND reason = 'revoked'"), 1 ); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Cut); // Every fact table refuses a delete, whether or not it holds the row. for table in fact_tables() { let delete = receipt_op(Change::retract(table, "no-such-fact"), &format!("op-d-{table}"), KITCHEN, T0 + 40); let result = fold_ops(&db, &[delete]).expect("folds"); assert_eq!(result.parked.len(), 1, "{table}: {result:?}"); } // A replay of the fact is nothing. let result = fold_ops(&db, &[fact("op-f", "fact-1", "row-1", "revoked", None, STUDY, T0 + 10)]).expect("folds"); assert_eq!(result.skipped_stale, vec!["op-f".to_string()]); assert!(result.parked.is_empty() && result.rejected.is_empty()); } /// RULE: Of two different writes to one fact id the earlier (stamp, op id) stands on every device, whichever arrives first, and the other is parked as a conflict, never applied and never dropped. #[test] fn two_writes_to_one_fact_id_end_at_the_earlier_one_in_either_order() { let early = fact("op-early", "fact-1", "row-1", "lost", None, STUDY, T0 + 10); let late = fact("op-late", "fact-1", "row-1", "revoked", None, KITCHEN, T0 + 20); for order in [[early.clone(), late.clone()], [late, early]] { let db = file(); let mut parked = Vec::new(); for write in order { parked.extend(fold_ops(&db, &[write]).expect("folds").parked); } assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_revocations WHERE reason = 'lost'"), 1); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_revocations"), 1); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _writes WHERE tbl = 'cotton_revocations'"), 1); assert_eq!(parked.len(), 1); assert_eq!(parked[0].op_id, "op-late"); assert!(parked[0].reason.contains("conflict"), "got {:?}", parked[0].reason); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _parked WHERE op_id = 'op-late'"), 1); } } /// RULE: A device's standing is the same on every device whatever order its approval rows and its revocation facts arrive in. #[test] fn revocation_reaches_every_device_in_any_order() { let cut = [ approval("op-a", "row-1", PHONE, NOW, T0), fact("op-f1", "fact-1", "row-1", "revoked", None, STUDY, T0 + 10), fact("op-f2", "fact-2", "row-1", "lost", None, KITCHEN, T0 + 20), ]; for order in permutations(&cut) { let db = file(); for write in &order { let result = fold_ops(&db, std::slice::from_ref(write)).expect("folds"); assert_eq!(result.applied.len(), 1, "{result:?}"); } assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Cut); } let succeeded = [ approval("op-a0", "row-old", OLD_MAC, NOW, T0), approval("op-a1", "row-new", NEW_MAC, NOW, T0 + 1), fact("op-f1", "fact-1", "row-old", "succeeded", Some(NEW_MAC), STUDY, T0 + 10), fact("op-f2", "fact-2", "row-old", "lost", None, KITCHEN, T0 + 20), ]; for order in permutations(&succeeded) { let db = file(); for write in &order { fold_ops(&db, std::slice::from_ref(write)).expect("folds"); } assert_eq!( device_standing(&db, OLD_MAC).expect("reads"), Standing::Succeeded(NEW_MAC.to_string()) ); assert_eq!(device_standing(&db, NEW_MAC).expect("reads"), Standing::Live); } } /// RULE: A revocation fact's id is random, so two devices revoking one subject write two facts: both are taken and neither parks as a conflict. #[test] fn two_revocation_facts_for_one_device_do_not_clash() { let db = file(); fold_ops(&db, &[approval("op-a", "row-1", PHONE, NOW, T0)]).expect("folds"); let result = fold_ops( &db, &[ fact("op-f1", "0b6f1c1e-fact-study", "row-1", "revoked", None, STUDY, T0 + 10), fact("op-f2", "9d2a77c4-fact-kitchen", "row-1", "revoked", None, KITCHEN, T0 + 10), ], ) .expect("folds"); assert_eq!(result.applied.len(), 2, "{result:?}"); assert!(result.parked.is_empty() && result.rejected.is_empty(), "{result:?}"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_revocations WHERE subject_id = 'row-1'"), 2); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Cut); } /// RULE: A device a `succeeded` fact hands to a live successor stays Succeeded when a later `lost` or `revoked` fact names it, so what it minted before the hand-over keeps standing. #[test] fn revoking_a_succeeded_device_keeps_what_it_minted() { // The standing is what `admit` reads for a credential's minter and // holder: `Succeeded(by live)` stands for what the device minted. let db = file(); fold_ops( &db, &[ approval("op-a0", "row-old", OLD_MAC, NOW, T0), approval("op-a1", "row-new", NEW_MAC, NOW, T0 + 1), fact("op-f1", "fact-1", "row-old", "succeeded", Some(NEW_MAC), STUDY, T0 + 10), ], ) .expect("folds"); let handed = Standing::Succeeded(NEW_MAC.to_string()); assert_eq!(device_standing(&db, OLD_MAC).expect("reads"), handed); fold_ops(&db, &[fact("op-f2", "fact-2", "row-old", "lost", None, KITCHEN, T0 + 20)]).expect("folds"); assert_eq!(device_standing(&db, OLD_MAC).expect("reads"), handed); // Only the successor's own end ends it. fold_ops(&db, &[fact("op-f3", "fact-3", "row-new", "revoked", None, KITCHEN, T0 + 30)]).expect("folds"); assert_eq!(device_standing(&db, NEW_MAC).expect("reads"), Standing::Cut); assert_eq!(device_standing(&db, OLD_MAC).expect("reads"), Standing::Cut); } /// RULE: fold.rs names no fact table and no side effect of folding a fact or an erase: it asks fact_hooks.rs, so a later slice fills a hook in its own file and never edits the fold. #[test] fn fold_rs_names_no_fact_table() { let source = include_str!("../src/fold.rs"); let mut named = Vec::new(); for (at, line) in source.lines().enumerate() { let code = line.trim_start(); if code.starts_with("//") { continue; } for needle in fact_tables().chain(["cotton_serving_machine", "erase::", "revocation::"]) { if code.contains(needle) { named.push(format!("fold.rs:{}: {needle}", at + 1)); } } } assert!(named.is_empty(), "fold.rs reaches past the fact-hook registry: {named:?}"); assert!(is_fact_table("cotton_revocations") && is_fact_table("cotton_authors")); } /// RULE: A device row whose revoked_at mirror is set and which has no revocation fact reads Cut, never Live, and a key this file has no row for reads Unknown, never barred. #[test] fn device_row_with_mirror_and_no_fact_reads_cut() { let db = file(); fold_ops(&db, &[approval("op-a", "row-1", PHONE, NOW, T0)]).expect("folds"); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Live); let mirror = receipt_op( Change::update("cotton_devices", "row-1", patch(json!({ "revoked_at": NOW, "revoked_reason": "revoked" }))), "op-m", STUDY, T0 + 10, ); fold_ops(&db, &[mirror]).expect("folds"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_revocations"), 0); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Cut); assert_eq!(device_standing(&db, "a-key-nobody-approved").expect("reads"), Standing::Unknown); } /// RULE: A device revoked and then approved again is Live: standing reads the facts of the one approval row the key order puts first, never the facts of the key's ended approvals. #[test] fn revoked_then_re_paired_device_is_live_and_owes_no_rotation() { // The standing half. The auth half is the cotton-server test of this name // (`auth_tests.rs`); the rotation half waits for slice 12. let db = file(); fold_ops( &db, &[ approval("op-a1", "row-r1", PHONE, "2026-09-16T09:00:00.000Z", T0), fact("op-f1", "fact-1", "row-r1", "revoked", None, STUDY, T0 + 10), ], ) .expect("folds"); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Cut); // Re-paired: a NEW row for the same key, and it is live. fold_ops(&db, &[approval("op-a2", "row-r2", PHONE, "2026-09-17T09:00:00.000Z", T0 + 20)]).expect("folds"); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Live); // An OLDER live approval beside a newer ended one is ended with it (slice // 12, V10-1 (b)): its create is stamped below a fact on another approval // of the key, so it is a late copy and never makes the key live. let db = file(); fold_ops( &db, &[ approval("op-a1", "row-old-live", PHONE, "2026-09-15T09:00:00.000Z", T0), approval("op-a2", "row-new-ended", PHONE, "2026-09-17T09:00:00.000Z", T0 + 1), fact("op-f1", "fact-1", "row-new-ended", "lost", None, STUDY, T0 + 10), ], ) .expect("folds"); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Cut); } /// RULE: An author's fact this file holds is never replaced: a different write to the same author id parks as a conflict even when its stamp is earlier, because every receipt of the stream was admitted under the held one. #[test] fn held_author_fact_is_never_swapped_by_an_earlier_twin() { assert!(NO_SWAP_FACT_TABLES.contains(&"cotton_authors")); let db = file(); let held = author_fact("op-held", STUDY, "the-study-mac-key", STUDY, T0 + 100); assert_eq!(fold_ops(&db, &[held]).expect("folds").applied, vec!["op-held".to_string()]); let twin = author_fact("op-twin", STUDY, "another-key-entirely", KITCHEN, T0); let result = fold_ops(&db, &[twin]).expect("folds"); assert!(result.applied.is_empty(), "{result:?}"); assert_eq!(result.parked.len(), 1, "{result:?}"); assert!(result.parked[0].reason.contains("conflict"), "got {:?}", result.parked[0].reason); assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM cotton_authors WHERE device_id = 'the-study-mac-key'"), 1 ); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_authors"), 1); } /// One row of each keys table, as its serving Mac would make it. fn keys_rows() -> Vec<(&'static str, &'static str, JsonValue)> { vec![ ( "cotton_admissions", "an admission", json!({ "id": "adm-1", "workspace_id": WORKSPACE, "person_key": "an-invented-person-key", "person_name": "An invented person", "rights": "member", "invite_id": "inv-1", "admitted_by_person": "the-owner-person-key", "p_sig": "c2ln", "admitted_at": NOW, }), ), ( "cotton_device_statements", "a device statement", json!({ "id": "st-1", "workspace_id": WORKSPACE, "person_key": "an-invented-person-key", "device_key": PHONE, "vault_public_key": "an-invented-vault-key", "device_name": "An invented phone", "p_sig": "c2ln", "d_sig": "c2ln", "made_at": NOW, }), ), ( "cotton_invites", "an invite", json!({ "id": "inv-1", "workspace_id": WORKSPACE, "secret_hash": "0f0f", "rights": "member", "expires_at": NOW, "made_by_person": "the-owner-person-key", "p_sig": "c2ln", "made_at": NOW, }), ), ] } /// RULE: An admission, a device statement and an invite are each written once, when they are made: a fresh file holds none, and the fold never applies a change or a delete of one or swaps a held one. #[test] fn keys_tables_exist_empty_and_insert_only() { let db = file(); for (n, (table, what, row)) in keys_rows().into_iter().enumerate() { assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM {table}")), 0, "{table} starts empty"); assert!(is_fact_table(table) && NO_SWAP_FACT_TABLES.contains(&table), "{table}"); let id = row["id"].as_str().expect("an id").to_string(); let ms = T0 + 100 * (n as i64 + 1); let made = receipt_op(Change::create(table, &id, patch(row.clone())), &format!("op-make-{n}"), STUDY, ms); let result = fold_ops(&db, &[made]).expect("folds"); assert_eq!(result.applied.len(), 1, "{table}: {result:?}"); let change = receipt_op( Change::update(table, &id, patch(json!({ "p_sig": "forged" }))), &format!("op-change-{n}"), KITCHEN, ms + 10, ); let refusal = format!("{what} is written once, when it is made"); let result = fold_ops(&db, std::slice::from_ref(&change)).expect("folds"); assert!(result.applied.is_empty(), "{table}: {result:?}"); assert!(result.parked[0].reason.contains(&refusal), "got {:?}", result.parked[0].reason); let result = arrive(&db, std::slice::from_ref(&change), Arrival::Local).expect("folds"); assert!(result.rejected[0].reason.contains(&refusal), "got {:?}", result.rejected[0].reason); let delete = receipt_op(Change::retract(table, &id), &format!("op-delete-{n}"), KITCHEN, ms + 20); let result = fold_ops(&db, &[delete]).expect("folds"); assert!(result.applied.is_empty() && result.parked.len() == 1, "{table}: {result:?}"); // An earlier-stamped second write of the same id never replaces the held one. let twin = receipt_op(Change::create(table, &id, patch(row)), &format!("op-twin-{n}"), KITCHEN, ms - 50); let result = fold_ops(&db, &[twin]).expect("folds"); assert!(result.applied.is_empty() && result.parked.len() == 1, "{table}: {result:?}"); assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM {table} WHERE p_sig = 'forged'")), 0); assert_eq!(count(&db, &format!("SELECT COUNT(*) AS n FROM {table}")), 1); } } // ── the old-author cut-off (slice 12) ──────────────────────────────────────── /// One serving fact, as a first run (`epoch` 1) or a take-over's act wrote it. fn serving_fact(db: &Driver, id: &str, epoch: i64, device: &str, since: &str) { db.run( "INSERT INTO cotton_serving_machine \ (id, workspace_id, epoch, device_credential_id, author_id, since) \ VALUES (?, ?, ?, ?, 'an-invented-author', ?)", &[text(id), text(WORKSPACE), Value::Integer(epoch), text(device), text(since)], ) .expect("the serving fact"); } fn todo(op_id: &str, row_id: &str, author: &str, ms: i64) -> CottonOp { receipt_op( Change::create( "cotton_todos", row_id, patch(json!({ "id": row_id, "workspace_id": WORKSPACE, "title": "An invented todo", "created_at": NOW, "updated_at": NOW, })), ), op_id, author, ms, ) } /// RULE: After a take-over, a receipt by an author of the Mac that stopped serving, stamped after the act's since, is parked conflict and never applied, and stays parked when retried; at or below since it is judged like any receipt. #[test] fn old_author_receipt_after_take_over_is_parked_not_merged() { let db = file(); // STUDY is the old serving Mac's author; e2's act began at T0 + 1000. fold_ops(&db, &[author_fact("op-a", STUDY, OLD_MAC, STUDY, T0)]).expect("folds"); serving_fact(&db, "s-1", 1, OLD_MAC, NOW); serving_fact(&db, "s-2", 2, NEW_MAC, "2023-11-14T22:13:21.000Z"); assert_eq!(cotton_store::protocol::js::parse_date_ms("2023-11-14T22:13:21.000Z"), Some(T0 + 1000)); let below = todo("op-below", "t-below", STUDY, T0 + 500); let at = todo("op-at", "t-at", STUDY, T0 + 1000); let above = todo("op-above", "t-above", STUDY, T0 + 1001); // A device the old Mac approved after the act, brought back by a hand-over. let device = approval("op-device", "d-late", "a-late-device-key", NOW, T0 + 2000); let result = fold_ops(&db, &[below, at, above, device]).expect("folds"); assert!(result.applied.contains(&"op-below".to_string()), "{result:?}"); assert!(result.applied.contains(&"op-at".to_string()), "{result:?}"); let parked: Vec<&str> = result.parked.iter().map(|park| park.op_id.as_str()).collect(); assert_eq!(parked, ["op-above", "op-device"], "{result:?}"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id IN ('t-below','t-at')"), 2); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't-above'"), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_devices WHERE id = 'd-late'"), 0); assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM _parked WHERE class = 'conflict' AND op_id IN ('op-above','op-device')"), 2, "parked conflict, never dropped" ); let retried = cotton_store::rejected::retry_rejected(&db, None, NOW).expect("retries"); assert!(retried.folded.is_empty(), "{retried:?}"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't-above'"), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _parked WHERE class = 'conflict'"), 2); } /// RULE: The Mac that serves now has no cut-off: its own author's receipts above its since are judged like any receipt, and so is every author of a file with one epoch. #[test] fn the_serving_macs_author_has_no_cut_off() { let db = file(); fold_ops( &db, &[ author_fact("op-a", STUDY, OLD_MAC, STUDY, T0), author_fact("op-k", KITCHEN, NEW_MAC, KITCHEN, T0), ], ) .expect("folds"); serving_fact(&db, "s-1", 1, OLD_MAC, NOW); let early = fold_ops(&db, &[todo("op-1", "t-1", STUDY, T0 + 5000)]).expect("folds"); assert!(early.applied.contains(&"op-1".to_string()), "one epoch: {early:?}"); serving_fact(&db, "s-2", 2, NEW_MAC, "2023-11-14T22:13:21.000Z"); let now = fold_ops(&db, &[todo("op-2", "t-2", KITCHEN, T0 + 5000)]).expect("folds"); assert!(now.applied.contains(&"op-2".to_string()), "{now:?}"); } // ── a serving author acts for the devices that ask it ─────────────────────── /// The authors of [`acting_for_devices`]: the Mac that served epoch 1 under /// the author its file was born with, that Mac's re-dated author from after it /// stopped serving, the Mac that took over at epoch 2 — its author from its /// client days and its take-over author — and a phone's own author. const BIRTH: &str = "device:01JSERVEDFIRST00000000000000"; const BIRTH_LATER: &str = "device:01JSERVEDFIRSTLATER000000000"; const CLIENT_DAYS: &str = "device:01JTAKERASCLIENT0000000000"; const TAKER: &str = "device:01JTAKERSERVING000000000000"; const PHONES: &str = "device:01JAPHONE0000000000000000000"; const MEMBER_KEY: &str = "a-synthetic-member-phone-key"; /// Epoch 1 began at S1, epoch 2 at S2 (T0 + 1000). const S1: &str = "2023-11-14T00:00:00.000Z"; const S2: &str = "2023-11-14T22:13:21.000Z"; fn author_row(db: &Driver, id: &str, device: &str, reason: &str, minted_at: &str) { db.run( "INSERT INTO cotton_authors (id, workspace_id, device_id, minted_at, reason, first_stamp) \ VALUES (?,?,?,?,?,'0')", &[text(id), text(WORKSPACE), text(device), text(minted_at), text(reason)], ) .expect("the author row"); } fn fact_by(db: &Driver, id: &str, epoch: i64, device: &str, author: &str, since: &str) { db.run( "INSERT INTO cotton_serving_machine \ (id, workspace_id, epoch, device_credential_id, author_id, since) \ VALUES (?, ?, ?, ?, ?, ?)", &[text(id), text(WORKSPACE), Value::Integer(epoch), text(device), text(author), text(since)], ) .expect("the serving fact"); } fn device_held(db: &Driver, row_id: &str, key: &str, person_key: Option<&str>) { db.run( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \ approved_by_device, created_at, updated_at, person_key) VALUES (?, ?, ?, 'An invented device', ?, 'self', ?, ?, ?)", &[ text(row_id), text(WORKSPACE), text(key), text(NOW), text(NOW), text(NOW), person_key.map_or(Value::Null, text), ], ) .expect("the device row"); } /// A file served at epoch 1 by OLD_MAC (BIRTH) and from S2 at epoch 2 by /// NEW_MAC (TAKER), holding the phone's owner device row and a member's. fn acting_for_devices() -> Driver { let db = file(); author_row(&db, BIRTH, OLD_MAC, "first", "2023-11-13T00:00:00.000Z"); author_row(&db, BIRTH_LATER, OLD_MAC, "redate", "2023-11-15T00:00:00.000Z"); author_row(&db, CLIENT_DAYS, NEW_MAC, "first", "2023-11-13T00:00:00.000Z"); author_row(&db, TAKER, NEW_MAC, "take-over", S2); author_row(&db, PHONES, PHONE, "first", "2023-11-13T00:00:00.000Z"); fact_by(&db, "s-1", 1, OLD_MAC, BIRTH, S1); fact_by(&db, "s-2", 2, NEW_MAC, TAKER, S2); device_held(&db, "d-phone", PHONE, None); device_held(&db, "d-member", MEMBER_KEY, Some("PersonKeyOfAnInventedMember")); device_held(&db, "d-new", NEW_MAC, None); db } /// A todo created by `author` as `actor`. fn todo_as(op_id: &str, row_id: &str, author: &str, actor: &Actor, ms: i64) -> CottonOp { let hlc = next_hlc(author, None, ms).expect("a stamp in range"); let change = Change::create( "cotton_todos", row_id, patch(json!({ "id": row_id, "workspace_id": WORKSPACE, "title": "An invented todo", "created_at": NOW, "updated_at": NOW, })), ); SCHEMA .with(|db| op_of_change(db, &change, &hlc, author, actor, op_id.to_string())) .expect("a receipt") } fn owner_at(db: &Driver, row: &str) -> Actor { Actor::owner(DeviceId::in_file(db, row).expect("the device row")) } /// RULE: The serving Mac's current author may name another device's owner or member, as it does minting for a phone that asked; its author from client days and a plain device's author may not, and no author names a member's device as the owner. #[test] fn a_serving_author_may_name_another_devices_owner() { let db = acting_for_devices(); let phone = owner_at(&db, "d-phone"); let member = Actor::Member(DeviceId::in_file(&db, "d-member").expect("the row")); let member_as_owner = owner_at(&db, "d-member"); let mac = owner_at(&db, "d-new"); let result = fold_ops( &db, &[ todo_as("op-serving", "t-serving", TAKER, &phone, T0 + 2000), todo_as("op-serving-member", "t-serving-member", TAKER, &member, T0 + 2001), todo_as("op-client-days", "t-client-days", CLIENT_DAYS, &phone, T0 + 500), todo_as("op-plain", "t-plain", PHONES, &mac, T0 + 2002), todo_as("op-member-as-owner", "t-member-as-owner", TAKER, &member_as_owner, T0 + 2003), ], ) .expect("folds"); assert_eq!(result.applied, ["op-serving", "op-serving-member"], "{result:?}"); let refused = |op: &str| { result .rejected .iter() .chain(&result.parked) .find(|refusal| refusal.op_id == op) .map(|refusal| refusal.reason.clone()) .unwrap_or_else(|| panic!("{op} is refused: {result:?}")) }; assert!(refused("op-client-days").contains("at another device"), "{}", refused("op-client-days")); assert!(refused("op-plain").contains("at another device"), "{}", refused("op-plain")); assert!(refused("op-member-as-owner").contains("never writes as the owner"), "{}", refused("op-member-as-owner")); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos"), 2); } /// RULE: An earlier epoch's serving author may name another device's owner below the cut-off; above it the cut-off parks the receipt conflict, and that Mac's author minted after it stopped serving is no serving author even when it serves again. #[test] fn an_earlier_epochs_serving_author_is_bounded_by_the_cut_off() { let db = acting_for_devices(); let phone = owner_at(&db, "d-phone"); let result = fold_ops( &db, &[ todo_as("op-below", "t-below", BIRTH, &phone, T0 + 500), todo_as("op-above", "t-above", BIRTH, &phone, T0 + 1001), ], ) .expect("folds"); assert_eq!(result.applied, ["op-below"], "{result:?}"); assert!(result.rejected.is_empty(), "{result:?}"); let parked: Vec<&str> = result.parked.iter().map(|park| park.op_id.as_str()).collect(); assert_eq!(parked, ["op-above"], "{result:?}"); assert!(result.parked[0].reason.contains("no longer serves"), "{}", result.parked[0].reason); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _parked WHERE class = 'conflict' AND op_id = 'op-above'"), 1); // OLD_MAC serves again from epoch 3: it has no cut-off now, and its author // re-dated while a client (between epochs 2 and 3) still names only its own device. fact_by(&db, "s-3", 3, OLD_MAC, BIRTH, "2023-11-16T00:00:00.000Z"); let result = fold_ops(&db, &[todo_as("op-later", "t-later", BIRTH_LATER, &phone, T0 + 3000)]).expect("folds"); assert!(result.applied.is_empty(), "{result:?}"); assert!(result.rejected[0].reason.contains("at another device"), "{result:?}"); } // ── a serving author whose serving fact has not arrived yet ────────────────── /// [`acting_for_devices`] before NEW_MAC's epoch-2 fact has reached it, with /// NEW_MAC's author re-dated while it was a client (before S2). fn before_the_taker_fact() -> Driver { let db = file(); author_row(&db, BIRTH, OLD_MAC, "first", "2023-11-13T00:00:00.000Z"); author_row(&db, CLIENT_DAYS, NEW_MAC, "first", "2023-11-13T00:00:00.000Z"); author_row(&db, TAKER, NEW_MAC, "take-over", S2); author_row(&db, REDATED_AS_CLIENT, NEW_MAC, "redate", "2023-11-14T10:00:00.000Z"); fact_by(&db, "s-1", 1, OLD_MAC, BIRTH, S1); device_held(&db, "d-phone", PHONE, None); db } const REDATED_AS_CLIENT: &str = "device:01JTAKERREDATEDASCLIENT000000"; /// NEW_MAC's epoch-2 serving fact, as the op that carries it from TAKER's stream. fn taker_fact() -> CottonOp { receipt_op( Change::create( "cotton_serving_machine", "s-2", patch(json!({ "id": "s-2", "workspace_id": WORKSPACE, "epoch": 2, "device_credential_id": NEW_MAC, "author_id": TAKER, "since": S2, })), ), "op-s2", TAKER, T0 + 1000, ) } fn parked_class(db: &Driver, op_id: &str) -> Option { db.get("SELECT class FROM _parked WHERE op_id = ?", &[text(op_id)]) .expect("reads") .and_then(|row| row.text("class").map(str::to_string)) } /// RULE: A receipt by a take-over author naming another device, arriving before the serving fact that makes it a serving author, parks waiting and applies when that fact arrives; in the other order it applies at once. #[test] fn a_serving_authors_receipt_waits_for_its_serving_fact_in_either_order() { // Receipt first: parked `waiting`, not refused; the fact frees it. let db = before_the_taker_fact(); let phone = owner_at(&db, "d-phone"); let token = todo_as("op-token", "t-token", TAKER, &phone, T0 + 2000); let folded = cotton_store::exchange::fold_incoming(&db, std::slice::from_ref(&token)).expect("folds"); assert!(folded.rejected.is_empty(), "{folded:?}"); assert_eq!(parked_class(&db, "op-token").as_deref(), Some("waiting")); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos"), 0); cotton_store::exchange::fold_incoming(&db, &[taker_fact()]).expect("folds"); assert_eq!(parked_class(&db, "op-token"), None, "the fact's arrival applied it"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't-token'"), 1); // Fact first: applied at once. let db = before_the_taker_fact(); let phone = owner_at(&db, "d-phone"); cotton_store::exchange::fold_incoming(&db, &[taker_fact()]).expect("folds"); let token = todo_as("op-token", "t-token", TAKER, &phone, T0 + 2000); let folded = cotton_store::exchange::fold_incoming(&db, &[token]).expect("folds"); assert!(folded.rejected.is_empty(), "{folded:?}"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't-token'"), 1); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _parked"), 0); } /// Hands out op ids for a mint in these tests. struct Ids(u32); impl cotton_store::mint::IdSource for Ids { fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result { self.0 += 1; Ok(format!("op-minted-{:05}", self.0)) } } /// RULE: A serving fact this file mints for itself frees the receipts parked waiting for it, as one that arrives from a peer does — the serving Mac re-keying writes its own epoch's fact, and a receipt its new serving author wrote, parked before that fact, must not wait for some unrelated touch (a phone re-offered such receipts every pass: syncpage5 row 3). #[test] fn a_serving_fact_minted_here_frees_the_receipts_waiting_for_it() { use cotton_store::meta::{seed_meta, Meta}; use cotton_store::mint::{mint, Act, Clock, Held, History}; use cotton_store::schema::ddl::SCHEMA_VERSION; let db = before_the_taker_fact(); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: "owner-1".to_string(), device_id: NEW_MAC.to_string(), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds"); db.run("UPDATE _meta SET author_id = ?", &[text(TAKER)]).expect("the file's author"); let phone = owner_at(&db, "d-phone"); let token = todo_as("op-token", "t-token", TAKER, &phone, T0 + 2000); let folded = cotton_store::exchange::fold_incoming(&db, std::slice::from_ref(&token)).expect("folds"); assert!(folded.rejected.is_empty(), "{folded:?}"); assert_eq!(parked_class(&db, "op-token").as_deref(), Some("waiting")); let act = Act { actor: Actor::device_job(JobName::named("test").expect("a job name")), verb: "serve".to_string(), history: History::Kept, changes: vec![Change::create( "cotton_serving_machine", "s-2", patch(json!({ "id": "s-2", "workspace_id": WORKSPACE, "epoch": 2, "device_credential_id": NEW_MAC, "author_id": TAKER, "since": S2, })), )], }; mint(&db, &act, &Clock::wall(T0 + 3000), &mut Ids(0), Held::Served).expect("mints the serving fact"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_serving_machine WHERE id = 's-2'"), 1); assert_eq!(parked_class(&db, "op-token"), None, "the minted fact applied it"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't-token'"), 1); } /// RULE: A client author naming another device is refused at once and parks conflict, and stays conflict after a serving fact naming its Mac arrives; a serving-reason author the arrived fact does not cover goes from waiting to conflict. #[test] fn a_client_author_naming_another_device_is_conflict_whatever_arrives() { let db = before_the_taker_fact(); let phone = owner_at(&db, "d-phone"); let client = todo_as("op-client", "t-client", CLIENT_DAYS, &phone, T0 + 500); let result = fold_ops(&db, std::slice::from_ref(&client)).expect("folds"); assert_eq!(result.rejected.len(), 1, "{result:?}"); let reason = result.rejected[0].reason.clone(); assert!(reason.contains("at another device"), "{reason}"); // As the exchange parks a refusal it pulled. let class = cotton_store::rejected::Class::of_refusal(&reason); assert_eq!(class, cotton_store::rejected::Class::Conflict); cotton_store::rejected::park(&db, &client, cotton_store::rejected::Direction::Pull, class, &reason, NOW) .expect("parks"); // Re-dated while a client: no fact names its Mac yet, so it waits. let early = todo_as("op-early", "t-early", REDATED_AS_CLIENT, &phone, T0 + 600); cotton_store::exchange::fold_incoming(&db, std::slice::from_ref(&early)).expect("folds"); assert_eq!(parked_class(&db, "op-early").as_deref(), Some("waiting")); cotton_store::exchange::fold_incoming(&db, &[taker_fact()]).expect("folds"); cotton_store::rejected::retry_rejected(&db, None, NOW).expect("retries"); assert_eq!(parked_class(&db, "op-client").as_deref(), Some("conflict")); assert_eq!(parked_class(&db, "op-early").as_deref(), Some("conflict"), "its Mac's fact is here and does not cover it"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos"), 0); } // ── a serving Mac's re-dated author, folded in any batching ───────────────── /// NEW_MAC's author re-dated while it serves epoch 2 (after S2). const REDATED_SERVING: &str = "device:01JTAKERREDATEDSERVING0000000"; /// A replica that knows epoch 2 and its authors but holds no phone row yet. fn replica_before_the_phone() -> Driver { let db = file(); author_row(&db, BIRTH, OLD_MAC, "first", "2023-11-13T00:00:00.000Z"); author_row(&db, TAKER, NEW_MAC, "take-over", S2); author_row(&db, REDATED_SERVING, NEW_MAC, "redate", "2023-11-15T00:00:00.000Z"); fact_by(&db, "s-1", 1, OLD_MAC, BIRTH, S1); fact_by(&db, "s-2", 2, NEW_MAC, TAKER, S2); db } /// The phone's device row and a token minted for its owner, both by the /// serving Mac's re-dated author, as a pairing then a token mint writes them. fn phone_row_and_its_token() -> (CottonOp, CottonOp) { let device = { let hlc = next_hlc(REDATED_SERVING, None, T0 + 3000).expect("a stamp"); let change = Change::create( "cotton_devices", "d-phone", patch(json!({ "id": "d-phone", "workspace_id": WORKSPACE, "device_id": PHONE, "name": "An invented phone", "approved_at": NOW, "approved_by_device": "self", "created_at": NOW, "updated_at": NOW, })), ); let actor = Actor::device_job(JobName::named("pairing").expect("a job name")); SCHEMA .with(|db| op_of_change(db, &change, &hlc, REDATED_SERVING, &actor, "op-phone".to_string())) .expect("a receipt") }; // The actor names the phone's row; build it from a scratch file holding it. let scratch = file(); device_held(&scratch, "d-phone", PHONE, None); let phone = owner_at(&scratch, "d-phone"); let hlc = next_hlc(REDATED_SERVING, None, T0 + 3001).expect("a stamp"); let change = Change::create( "cotton_mcp_tokens", "k-phone", patch(json!({ "id": "k-phone", "owner_user_id": "owner-1", "workspace_id": WORKSPACE, "name": "An invented token", "token_hash": "ab".repeat(32), "scopes": "[]", "created_at": NOW, })), ); let token = SCHEMA .with(|db| op_of_change(db, &change, &hlc, REDATED_SERVING, &phone, "op-token".to_string())) .expect("a receipt"); (device, token) } /// RULE: A token the serving Mac's re-dated author minted for a phone's owner applies on a replica whether the phone's row arrived in an earlier batch, earlier in the same batch, or after it in the same batch. #[test] fn a_redated_serving_authors_token_for_a_phone_applies_in_any_batching() { let (device, token) = phone_row_and_its_token(); let batchings: [(&str, Vec>); 3] = [ ("phone row in an earlier batch", vec![vec![device.clone()], vec![token.clone()]]), ("phone row first in one batch", vec![vec![device.clone(), token.clone()]]), ("token first in one batch", vec![vec![token.clone(), device.clone()]]), ]; for (name, batches) in batchings { let db = replica_before_the_phone(); for batch in &batches { let result = cotton_store::fold::fold_pulled(&db, batch).expect("folds"); assert!(result.rejected.is_empty() && result.parked.is_empty(), "{name}: {result:?}"); } assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_devices WHERE id = 'd-phone'"), 1, "{name}"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_mcp_tokens WHERE id = 'k-phone'"), 1, "{name}"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _parked"), 0, "{name}"); } } // ── late approvals and skipped claimants (slice 12) ────────────────────────── /// [`file`], with the `_meta` row a real file holds, so the fold's marks land. fn file_with_meta() -> Driver { let db = file(); cotton_store::meta::seed_meta( &db, &cotton_store::meta::Meta { workspace_id: WORKSPACE.to_string(), owner_id: "owner-1".to_string(), device_id: KITCHEN.to_string(), last_server_seq: 0, last_hlc: None, }, cotton_store::migrate::SCHEMA_VERSION, ) .expect("seeds the identity"); db } fn rotation_check_due(db: &Driver) -> Option { db.get("SELECT rotation_check_due FROM _meta", &[]) .expect("reads") .and_then(|row| row.text("rotation_check_due").map(str::to_string)) } /// RULE: A late or duplicate approval of a key a succeeded fact ended, created below that fact, never makes the key Live or Cut: it reads Succeeded by the live successor, and its arrival alone marks the serving Mac's pass due. #[test] fn late_or_duplicate_approval_of_a_succeeded_key_keeps_it_succeeded() { let db = file_with_meta(); fold_ops( &db, &[ approval("op-a0", "row-old", OLD_MAC, NOW, T0), approval("op-a1", "row-new", NEW_MAC, NOW, T0 + 1), fact("op-f1", "fact-1", "row-old", "succeeded", Some(NEW_MAC), STUDY, T0 + 10), ], ) .expect("folds"); db.run("UPDATE _meta SET rotation_check_due = NULL", &[]).expect("cleared"); // A second approval of the old root's key, made before the act and // arriving after it, alone. KEY_ORDER alone would put it first. fold_ops(&db, &[approval("op-dup", "row-dup", OLD_MAC, "2026-09-16T09:00:01.000Z", T0 + 5)]).expect("folds"); assert_eq!( device_standing(&db, OLD_MAC).expect("reads"), Standing::Succeeded(NEW_MAC.to_string()) ); assert!(cotton_store::revocation::approval_ended_late(&db, "row-dup").expect("reads")); assert!(rotation_check_due(&db).is_some(), "the late approval wakes the pass"); let owed = cotton_store::revocation::ended_late_approvals(&db).expect("reads"); assert_eq!(owed.len(), 1, "{owed:?}"); assert_eq!(owed[0].approval, "row-dup"); assert_eq!((owed[0].reason.as_str(), owed[0].successor.as_deref()), ("succeeded", Some(NEW_MAC))); } /// RULE: An honest re-pair, created after the fact that ended its key, stays Live and owes the pass nothing; an approval older than that fact arriving later is ended. #[test] fn an_honest_re_pair_after_the_revoke_stays_live() { let db = file_with_meta(); fold_ops( &db, &[ approval("op-a1", "row-r1", PHONE, NOW, T0), fact("op-f1", "fact-1", "row-r1", "revoked", None, STUDY, T0 + 10), ], ) .expect("folds"); db.run("UPDATE _meta SET rotation_check_due = NULL", &[]).expect("cleared"); fold_ops(&db, &[approval("op-a2", "row-r2", PHONE, NOW, T0 + 20)]).expect("folds"); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Live); assert_eq!(rotation_check_due(&db), None); assert!(cotton_store::revocation::ended_late_approvals(&db).expect("reads").is_empty()); // An older approval of the key arriving now is ended; the re-pair stands. fold_ops(&db, &[approval("op-a0", "row-r0", PHONE, NOW, T0 + 5)]).expect("folds"); assert!(cotton_store::revocation::approval_ended_late(&db, "row-r0").expect("reads")); assert!(!cotton_store::revocation::approval_ended_late(&db, "row-r2").expect("reads")); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Live); } /// RULE: A key a serving fact's start_positions.skipped names reads Succeeded by that fact's Mac, whatever its approvals say, so applying the claimant's approval never makes it Live. #[test] fn a_skipped_claimant_reads_succeeded_by_the_mac_that_skipped_it() { let db = file_with_meta(); fold_ops( &db, &[ approval("op-a0", "row-claimant", PHONE, NOW, T0), approval("op-a1", "row-new", NEW_MAC, NOW, T0 + 1), ], ) .expect("folds"); assert_eq!(device_standing(&db, PHONE).expect("reads"), Standing::Live); db.run( "INSERT INTO cotton_serving_machine \ (id, workspace_id, epoch, device_credential_id, author_id, since, start_positions) \ VALUES ('s-3', ?, 3, ?, 'an-invented-author', ?, ?)", &[ text(WORKSPACE), text(NEW_MAC), text(NOW), text(&json!({"positions": {}, "skipped": [{"epoch": 2, "device": PHONE}]}).to_string()), ], ) .expect("the serving fact"); assert_eq!( device_standing(&db, PHONE).expect("reads"), Standing::Succeeded(NEW_MAC.to_string()) ); assert_eq!(device_standing(&db, NEW_MAC).expect("reads"), Standing::Live); } /// RULE: A receipt the fold parks `waiting` for its author's fact is named in `Folded::waiting` as a held `author_waiting` refusal and never as a rejection, so the route can tell a pusher that asked and that pusher stops re-sending it on every pass (16 Oct 2026: 95 KB a pass, no row). #[test] fn a_receipt_parked_waiting_is_named_for_its_pusher() { let db = before_the_taker_fact(); let phone = owner_at(&db, "d-phone"); let token = todo_as("op-token", "t-token", TAKER, &phone, T0 + 2000); let folded = cotton_store::exchange::fold_incoming(&db, std::slice::from_ref(&token)).expect("folds"); assert!(folded.rejected.is_empty(), "{folded:?}"); assert_eq!(parked_class(&db, "op-token").as_deref(), Some("waiting")); let named: Vec<(&str, Option<&str>, Option)> = folded .waiting .iter() .map(|held| (held.op_id.as_str(), held.code.as_deref(), held.retryable)) .collect(); assert_eq!( named, vec![("op-token", Some(cotton_store::protocol::types::REJECTION_AUTHOR_WAITING), Some(true))] ); }