//! The replica's half of the clock (slice 1, step 5): a replica judges by the//! time its server's answers carry, applies an answer whatever its stamp, and//! re-dates a `future` refusal to when the write was made — once, under one//! fresh author per answer, in the same round, so a device whose cursor passed//! the refused stamp still receives the repair.use std::collections::BTreeMap;use std::sync::atomic::{AtomicI64, Ordering};use std::sync::{Arc, Mutex};use cotton_store::exchange::{answer, answer_excluding, exchange_once, fold_incoming, handled, Handover, SyncTransport};use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::judge::{JudgeSource, Offered};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::clock::{serving, writer_clock, FUTURE_BOUND_MS, REFUSED_AFTER_REDATE};use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource};use cotton_store::protocol::hlc::hlc_parts;use cotton_store::protocol::js::{parse_date_ms, to_iso_string};use cotton_store::protocol::types::{CottonOp, ExchangeRequest, ExchangeResponse, PushRejection, EXCHANGE_PAGE_ROWS, REJECTION_FUTURE,};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::Driver;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};/// The serving Mac's judge time in these tests.const J: i64 = 1_790_000_000_000;const HOUR: i64 = 60 * 60_000;const BOOT: &str = "6f1c1f55-0000-4000-8000-000000000002";/// The continuous clock when the replica's writes were minted.const MINTED_CONT: i64 = 5_000;/// …and a minute later, when the answers arrive.const ANSWER_CONT: i64 = MINTED_CONT + 60_000;structIds(u32, &'static str);implIdSourceforIds {fn next_op_id(&mutself, _now_ms: i64) -> cotton_store::Result<String> {self.0 += 1;Ok(format!("{}{:04}", self.1, self.0)) }}/// The replica process's judge clock: every answer's judge time is taken.structProcessJudge { judge_ms: Mutex<Option<i64>>, cont: AtomicI64,}implProcessJudge {fn unheard() -> Arc<ProcessJudge> {Arc::new(ProcessJudge { judge_ms: Mutex::new(None), cont: AtomicI64::new(ANSWER_CONT), }) }}implJudgeSourceforProcessJudge {fn now(&self) -> Option<i64> { *self.judge_ms.lock().expect("the judge") }fn mint_clock(&self, wall_ms: i64) -> Result<Clock, String> {Ok(Clock::judged(self.now(), wall_ms, self.cont.load(Ordering::SeqCst), BOOT.to_string())) }fn confirm(&self, _device_ts_ms: i64) -> Result<bool, String> {Ok(false) }fn offer(&self, server_time: &str, _wall_ms: i64) -> Result<Offered, String> {let judge = parse_date_ms(server_time).ok_or_else(|| format!("unreadable {server_time}"))?; *self.judge_ms.lock().expect("the judge") = Some(judge);Ok(Offered::Taken) }}fn file(device: &str) -> Driver {let db = file_at_version(SCHEMA_VERSION); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: device.to_string(), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds the identity"); seed_workspace_row(&db); db.run("INSERT INTO cotton_sessions (id, workspace_id, tool, last_active_at, created_at, updated_at) \ VALUES ('s1', ?, 'claude-code', ?, ?, ?)", &[SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(NOW.to_string()),SqlValue::Text(NOW.to_string()),SqlValue::Text(NOW.to_string()), ], ) .expect("a session row"); db}fn minted_at(judge: i64) -> Clock {Clock::judged(Some(judge), judge, MINTED_CONT, BOOT.to_string())}/// A phone's replica, written by `judge`, with its author.fn phone(judge: &Arc<ProcessJudge>) -> Driver {let db = file("device:phone") .replica_judged_by(Arc::clone(judge) asArc<dynJudgeSource>, Box::new(Ids(0, "redate-"))); first_author(&db, "device:phone", None, AuthorReason::First, &minted_at(J - HOUR), &mutIds(0, "first-"), Held::Replica) .expect("the phone's author"); db}fn write(db: &Driver, row: &str, clock: &Clock, ids: &mutIds) -> Vec<CottonOp> {let todo: Map<String, Value> = json!({"id": row, "workspace_id": WORKSPACE, "title": row, "created_at": NOW, "updated_at": NOW}) .as_object() .expect("an object") .clone();let actor = cotton_store::actor::Actor::session(cotton_store::actor::SessionId::in_file(db, "s1").expect("the row")); mint( db, &Act { actor, verb: "create_todo".into(), history: History::Kept, changes: vec![Change::create("cotton_todos", row, todo)] }, clock, ids,Held::Replica, ) .expect("mints") .ops}fn count(db: &Driver, sql: &str) -> i64 { db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(0)}fn ms(stamp: &str) -> i64 { hlc_parts(stamp).expect("a stamp").ms}fn redate_authors(db: &Driver) -> i64 { count(db, "SELECT COUNT(*) AS n FROM cotton_authors WHERE reason = 'redate'")}/// The serving Mac: a file that folds what it is handed and answers, and/// refuses as `future` every write `refuses` names that is stamped beyond its/// judge time + the bound — with that judge time.structServingMac { db: Driver, judge_ms: i64, refuses: fn(&CottonOp) -> bool, calls: usize,}implServingMac {fn new(refuses: fn(&CottonOp) -> bool) -> ServingMac {ServingMac { db: file("device:mac"), judge_ms: J, refuses, calls: 0, } }}fn every_write(_op: &CottonOp) -> bool {true}fn todos_only(op: &CottonOp) -> bool { op.table == "cotton_todos"}implSyncTransportforServingMac {fn exchange(&mutself, request: &ExchangeRequest) -> Result<ExchangeResponse, String> {self.calls += 1;let judge_time = to_iso_string(self.judge_ms).expect("a time");let (refused, taken): (Vec<CottonOp>, Vec<CottonOp>) = request .ops .iter() .cloned() .partition(|op| (self.refuses)(op) && ms(&op.hlc) > self.judge_ms + FUTURE_BOUND_MS);let folded = fold_incoming(&self.db, &taken).map_err(|error| error.to_string())?;let answered = answer_excluding(&self.db, &request.cursors, EXCHANGE_PAGE_ROWS as usize, &handled(&taken)) .map_err(|error| error.to_string())?;letmut rejected = folded.rejected; rejected.extend(refused.iter().map(|op| PushRejection { op_id: op.op_id.clone(), reason: "ahead of the serving Mac's judge time".to_string(), retryable: Some(true), code: Some(REJECTION_FUTURE.to_string()), server_time: Some(judge_time.clone()), }));Ok(ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: request.workspace_id.clone(), ops: answered.ops, cursors: answered.cursors, has_more: answered.has_more, schema_version: Some(SCHEMA_VERSION), applied_rows: folded.applied_rows, rejected, seen: answered.seen, serving_epoch: None, server_time: Some(judge_time), restored: None, copy_night: None, behind_by: None, owed_at_start: None, owed_by_table: None, passed: None, wake_refusal: None, }) }}/// One sync ROUND, as the device's pass runs it: exchange while either side/// has more. Answers how many exchanges it took.fn round(db: &Driver, mac: &mutServingMac) -> usize {let before = mac.calls;letmut handover = Handover::default();for _ in0..20 {let exchanged = exchange_once(db, mac, WORKSPACE, None, NOW, &mut handover).expect("exchanges");if !exchanged.has_more {return mac.calls - before; } } panic!("a round that never ends");}/// RULE: A replica applies its server's answer whatever the stamps in it — nothing is parked for being ahead — and moves last_hlc no further than judge time plus the bound.#[test]fn replicas_apply_answers_whatever_their_stamp() {let judge = ProcessJudge::unheard();let db = phone(&judge);letmut mac = ServingMac::new(every_write);// The serving Mac holds a write another device made with its clock a// year ahead — the judge took it before it judged.let other = file("device:laptop"); first_author(&other, "device:laptop", None, AuthorReason::First, &minted_at(J + 365 * 24 * HOUR), &mutIds(0, "lap-a-"), Held::Replica) .expect("an author");let ahead = write(&other, "t-ahead", &minted_at(J + 365 * 24 * HOUR), &mutIds(0, "lap-"));let theirs = answer(&other, &BTreeMap::new(), 100).expect("answers").ops; fold_incoming(&mac.db, &theirs).expect("the Mac holds it"); round(&db, &mut mac); assert_eq!(judge.now(), Some(J), "the answer's judge time is this replica's reading"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't-ahead'"), 1, "applied"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _parked"), 0, "nothing parked");let last = db .get("SELECT last_hlc AS v FROM _meta", &[]) .expect("reads") .and_then(|row| row.text("v").map(str::to_string)) .expect("a clock"); assert!(ms(&last) <= J + FUTURE_BOUND_MS, "last_hlc adopts no stamp beyond the bound: {last}"); assert!(ms(&ahead[0].hlc) > J + FUTURE_BOUND_MS);}/// RULE: A future refusal is re-dated to mint time under one fresh author, and a re-dated write refused again is parked `conflict`, not re-dated — no author is minted per exchange.#[test]fn phone_refusal_redate_does_not_loop_authors() {let judge = ProcessJudge::unheard();let db = phone(&judge);letmut ids = Ids(0, "op-");// Minted while the phone's reading was three hours ahead.let refused = write(&db, "t1", &minted_at(J + 3 * HOUR), &mut ids);letmut mac = ServingMac::new(todos_only); round(&db, &mut mac); assert_eq!(redate_authors(&db), 1, "one fresh author for the answer");let redated = db .get("SELECT hlc AS v, author FROM _writes WHERE tbl = 'cotton_todos' AND row_id = 't1'", &[]) .expect("reads") .expect("the re-dated write");let stamp = redated.text("v").expect("a stamp").to_string(); assert_eq!(ms(&stamp), J - (ANSWER_CONT - MINTED_CONT), "re-dated to when it was made, never to J_r"); assert_ne!(redated.text("author"), Some(refused[0].device_id.as_str())); assert_eq!(count(&mac.db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't1'"), 1, "the Mac has it");// A second write refused and re-dated — and before the re-date goes out// the serving Mac's judge time falls two hours, so it is refused again.// It is parked, never re-dated a second time.let again = write(&db, "t2", &minted_at(J + 3 * HOUR), &mut ids);let before = redate_authors(&db); exchange_once(&db, &mut mac, WORKSPACE, None, NOW, &mutHandover::default()).expect("exchanges"); assert_eq!(redate_authors(&db), before + 1, "one author for the one refusing answer"); mac.judge_ms = J - 2 * HOUR;for _ in0..4 { round(&db, &mut mac); } assert_eq!(redate_authors(&db), before + 1, "a refused re-date mints no author"); assert_eq!( count( &db, &format!("SELECT COUNT(*) AS n FROM _parked \ WHERE reason LIKE '{REFUSED_AFTER_REDATE}%' AND class = 'conflict' AND direction = 'push'" ) ),1,"the twice-refused write is parked `conflict`, our own write the Mac would not take" ); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), 0, "nothing loops in the queue"); assert!(ms(&again[0].hlc) > J);}/// RULE: A re-date that survives a process restart goes out as it was made, under the one author it was re-dated under — the restarted process mints no second author and re-dates nothing again.#[test]fn replica_redate_across_a_process_restart_does_not_loop_or_mint_authors() {let judge = ProcessJudge::unheard();let db = phone(&judge); write(&db, "t1", &minted_at(J + 3 * HOUR), &mutIds(0, "op-"));letmut mac = ServingMac::new(every_write);// The answer refusing it arrives; the re-date is queued; the push of the// re-date never happens in this process.let handed = cotton_store::exchange::exchange_request(&db, WORKSPACE, None, &mutHandover::default()).expect("a request");let refusal = mac.exchange(&handed.request).expect("answers"); cotton_store::exchange::fold_answer(&db, &handed, &refusal, NOW, &mutHandover::default()).expect("folds"); assert_eq!(redate_authors(&db), 1);// A new process: the same file, a judge that has heard nothing yet.let restarted = ProcessJudge::unheard();let db = db.replica_judged_by(Arc::clone(&restarted) asArc<dynJudgeSource>, Box::new(Ids(0, "again-")));for _ in0..3 { round(&db, &mut mac); } assert_eq!(redate_authors(&db), 1, "the restart minted no author"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _parked"), 0); assert_eq!(count(&mac.db, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id = 't1'"), 1);}/// RULE: A device whose N writes are refused as future re-dates them all in the answer that refused them and sends them in the next page of the same round — re-dates cost no extra rounds.#[test]fn device_with_n_redates_exchanges_in_one_round() {let judge = ProcessJudge::unheard();let db = phone(&judge);letmut ids = Ids(0, "op-");for row in ["t1", "t2", "t3", "t4", "t5"] { write(&db, row, &minted_at(J + 3 * HOUR), &mut ids); }letmut mac = ServingMac::new(every_write);let exchanges = round(&db, &mut mac); assert_eq!(exchanges, 2, "one exchange refused, the next carried every re-date"); assert_eq!(redate_authors(&db), 1, "one author for all five"); assert_eq!(count(&mac.db, "SELECT COUNT(*) AS n FROM cotton_todos"), 5); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), 0);}/// RULE: A re-date goes under an author no cursor has passed, so a device whose cursor passed the refused future stamp still receives the repaired writes.#[test]fn repaired_writes_reach_every_device_whose_cursor_passed_the_future_stamp() {let judge = ProcessJudge::unheard();let db = phone(&judge);let future = write(&db, "t1", &minted_at(J + 3 * HOUR), &mutIds(0, "op-"));let old_author = future[0].device_id.clone();letmut mac = ServingMac::new(todos_only); round(&db, &mut mac);// Another device holds a cursor past the future stamp on the old author —// it heard of that author's stream as far as the bad write.letmut passed: BTreeMap<String, String> = BTreeMap::new(); passed.insert(old_author.clone(), future[0].hlc.clone());let reached = answer(&mac.db, &passed, 100).expect("answers").ops;let repaired = reached .iter() .find(|op| op.table == "cotton_todos" && op.row_id == "t1") .expect("the repaired write reaches that device"); assert_ne!(repaired.device_id, old_author, "under a fresh author"); assert!(ms(&repaired.hlc) <= J);}/// How many times `db` has asked for its held receipts since it was watched.fn held_scans(db: &Driver) -> usize { db.statements_seen().iter().filter(|sql| sql.contains("WHERE held = 1")).count()}const HELD: &str = "SELECT count(*) AS n FROM _writes WHERE held = 1";/// RULE: The release pass runs once per handle per stretch of judge time, inside a caller's transaction as outside one — a transaction of many writes scans for held receipts once, not once per write.////// Measured 11 Oct 2026 on another Mac: the media pass dropped 26,368 missing/// holds in ONE transaction, each drop a write, and each write ran the pass/// again — a scan of 916k `_writes` rows for none held — because the pass was/// marked done only at depth 0. The replica stayed locked for over an hour,/// and sync, ingest and the server's own restart stood behind it.#[test]fn many_writes_in_one_transaction_scan_for_held_receipts_once() {let judge = ProcessJudge::unheard(); *judge.judge_ms.lock().expect("the judge") = Some(J);let db = phone(&judge); db.watch_statements();let (first, last) = db .transaction(|db| { writer_clock(db, J, &mutIds(0, "w-"))?;let first = held_scans(db);for _ in0..50 { writer_clock(db, J, &mutIds(0, "w-"))?; }Ok((first, held_scans(db))) }) .expect("commits"); assert!(first > 0, "the first write in judge time runs the pass"); assert_eq!(last, first, "and no later write in the same transaction runs it again");}/// RULE: A release pass inside a transaction or savepoint that rolls back has released nothing: the next write runs the pass again and releases the receipt.#[test]fn a_release_rolled_back_with_its_transaction_runs_again() {let judge = ProcessJudge::unheard();let db = phone(&judge); write(&db, "t1", &Clock::judged(None, J, MINTED_CONT, BOOT.to_string()), &mutIds(0, "held-")); assert!(count(&db, HELD) > 0, "minted with no judge time, the write is held"); *judge.judge_ms.lock().expect("the judge") = Some(J);// The whole transaction rolls back.let failed: cotton_store::Result<()> = db.transaction(|db| { writer_clock(db, J, &mutIds(0, "w-"))?; assert_eq!(count(db, HELD), 0, "the pass released it inside the transaction");Err(cotton_store::StoreError::refused("the caller's work failed")) }); assert!(failed.is_err()); assert!(count(&db, HELD) > 0, "the rollback took the release back");// A savepoint inside a transaction that commits rolls back. db.transaction(|db| {let inner: cotton_store::Result<()> = db.transaction(|db| { writer_clock(db, J, &mutIds(0, "x-"))?;Err(cotton_store::StoreError::refused("the inner work failed")) }); assert!(inner.is_err()); assert!(count(db, HELD) > 0, "the savepoint's rollback took the release back"); writer_clock(db, J, &mutIds(0, "y-"))?; assert_eq!(count(db, HELD), 0, "the next write in the transaction ran the pass again");Ok(()) }) .expect("commits"); assert_eq!(count(&db, HELD), 0);}/// A file carrying `writes` written rows, none held, as a long-lived database's is.fn carrying(device: &str, writes: i64) -> Driver {let db = file(device); db.run("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?1) \ INSERT INTO _writes (tbl, row_id, hlc, author, op_id, kind, held, bytes) \ SELECT 'cotton_todos', 'row-' || i, printf('1789000000000:%04d:device:other', i % 10000), \ 'device:other', 'op-' || i, 'create', 0, zeroblob(200) FROM n", &[SqlValue::Integer(writes)], ) .expect("the file's writes"); db}/// The steps a FRESH handle's release pass asks of the file: the replica's,/// at its first judged write, and the serving Mac's, at its first page.fn release_steps(writes: i64) -> (u64, u64) {let judge = ProcessJudge::unheard(); *judge.judge_ms.lock().expect("the judge") = Some(J);let replica = carrying("device:phone", writes) .replica_judged_by(Arc::clone(&judge) asArc<dynJudgeSource>, Box::new(Ids(0, "r-")));let before = replica.steps(); writer_clock(&replica, J, &mutIds(0, "w-")).expect("a judged clock");let on_replica = replica.steps() - before;let served = carrying("device:mac", writes).judged_by(Arc::clone(&judge) asArc<dynJudgeSource>);let before = served.steps(); serving(&served, J, &mutIds(0, "s-")).expect("serves"); (on_replica, served.steps() - before)}/// RULE: The release pass reads the held receipts, never every write — on a fresh handle it costs the same steps among 1,000 writes as among 100,000, on a replica and on the serving Mac.////// Measured 11 Oct 2026 on the serving Mac (0.29.31): one judge pass held the/// personal file 8.0 s, 3,086,675 steps, in one statement —/// `SELECT … FROM _writes WHERE held = 1` over ~916k rows with `held`/// unindexed. The partial indexes `idx_writes_held` and `idx_tombstones_held`/// (schema 110) are what make it cheap.#[test]fn the_release_pass_costs_the_same_steps_among_1_000_and_100_000_writes() {let (replica_few, served_few) = release_steps(1_000);let (replica_many, served_many) = release_steps(100_000); assert!( replica_many <= replica_few + 100,"a replica's release pass took {replica_few} steps among 1,000 writes and {replica_many} among 100,000" ); assert!( served_many <= served_few + 100,"the serving Mac's release pass took {served_few} steps among 1,000 writes and {served_many} among 100,000" );}const QUEUED: &str = "SELECT count(*) AS n FROM _outbox";/// RULE: Folding a page is the acceptance of its judge time: a write held while the device had no server time is in `_outbox` once the next page folds, in the fold's own transaction — asked of the file, whatever the handle remembers of an earlier release.////// 13 Oct 2026: the owner's two approvals were held on the phone, which/// exchanged every few seconds and still never sent them.#[test]fn a_held_write_is_queued_by_the_next_folded_page() {let judge = ProcessJudge::unheard();let db = phone(&judge);// The handle has judge time and has released: it remembers nothing held. *judge.judge_ms.lock().expect("the judge") = Some(J); writer_clock(&db, J, &mutIds(0, "w-")).expect("releases nothing");// A writer with no server time — another launch, another handle — holds. write(&db, "t-held", &Clock::judged(None, J, MINTED_CONT, BOOT.to_string()), &mutIds(0, "held-")); assert!(count(&db, HELD) > 0, "the write is held");let queued_before = count(&db, QUEUED);letmut mac = ServingMac::new(|_| false);letmut handover = Handover::default();let handed = cotton_store::exchange::Handed::nothing(WORKSPACE);let answer = mac.exchange(&handed.request).expect("answers"); cotton_store::exchange::fold_answer(&db, &handed, &answer, NOW, &mut handover).expect("folds"); assert_eq!(count(&db, HELD), 0, "the folded page released it"); assert!(count(&db, QUEUED) > queued_before, "and queued it to go");}/// RULE: A pass that opens a file once the device has the Mac's time hands over the writes held before it, in its first page — a foreground open, a catch-up wake and a timer pass alike — so a write is never left on the phone by a hold.#[test]fn a_pass_hands_over_writes_held_before_the_macs_time() {let judge = ProcessJudge::unheard();let db = phone(&judge); write(&db, "t-held", &Clock::judged(None, J, MINTED_CONT, BOOT.to_string()), &mutIds(0, "held-")); assert!(count(&db, HELD) > 0, "minted with no server time, the write is held");// The Mac's time arrives by another road (the relay's greeting). *judge.judge_ms.lock().expect("the judge") = Some(J);letmut mac = ServingMac::new(|_| false);letmut handover = Handover::default(); exchange_once(&db, &mut mac, WORKSPACE, None, NOW, &mut handover).expect("exchanges"); assert_eq!(count(&db, HELD), 0); assert_eq!( count(&mac.db, "SELECT count(*) AS n FROM cotton_todos WHERE id = 't-held'"),1,"the Mac has the write after one exchange" );}