//! What a parked write is worth, and when it stops being parked.//!//! The shape every case here is built on is a CHILD that arrives before its//! PARENT: a money account created against a counterparty person this file//! has not got, refused on `counterparty_person_id`'s foreign key. That key//! only points, so the child PARKS; the child of an owning key waits dormant//! instead, and a key to the workspace is never followed by a page's retry.//! (A change that reaches a row before its create is no park any more — it is//! stored dormant and shows when the create lands, 3.7 point 6 — so a foreign//! key is what a park is now.) Nothing is lost, because the parent follows;//! the question these cases answer is what happens when it does.usesuper::*;usecrate::exchange::fold_answer;usecrate::fold::fold_ops;usecrate::protocol::types::{ExchangeResponse, PushRejection};usecrate::mint::Change;usecrate::test_support::{seeded_file, WORKSPACE as WS};use serde_json::json;use std::collections::{BTreeMap, BTreeSet};const NOW: &str = "2026-09-08T10:00:00.000Z";const LATER: &str = "2026-09-08T11:00:00.000Z";const LATEST: &str = "2026-09-08T12:00:00.000Z";const PEER: &str = "device:peer";/// The table every CHILD below is a row of.const CHILD_TABLE: &str = "cotton_money_accounts";/// A file with an identity and a workspace row, and nothing else.fn seeded() -> Driver { seeded_file("device:mine")}/// A stamp for this peer at a given millisecond. Handwritten rather than taken/// from `next_hlc`, so a case says out loud which write is older.fn hlc(ms: i64) -> String { format!("{ms:013}:0000:{PEER}")}thread_local! {/// The file receipts are made against — any file with the schema will do.static SCRATCH: Driver = seeded_file("device:scratch");}/// A receipt as `mint` would make it, at a stamp of this peer's.fn op_of(change: Change, ms: i64, op_id: String) -> CottonOp { SCRATCH.with(|db| {crate::wire::op_of_change(db, &change, &hlc(ms), PEER, &crate::fixtures::fixture_actor(), op_id) .expect("a receipt") })}fn obj(value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> { value.as_object().cloned().expect("an object")}/// The person a money account `row_id` is held against.fn person_of(row_id: &str) -> String { format!("person-{row_id}")}/// The PARENT: the person the child's foreign key points at.fn parent(row_id: &str, title: &str, ms: i64) -> CottonOp {let id = person_of(row_id); op_of(Change::create("cotton_people", &id, obj(json!({"id": id,"full_name": title,"workspace_id": WS,"created_at": NOW,"updated_at": NOW, })), ), ms, format!("op-parent-{row_id}"), )}/// A money account's create, naming its counterparty — refused while that/// person is missing. `extra` adds columns to it.fn child_with(op_id: String, row_id: &str, title: &str, extra: serde_json::Value, ms: i64) -> CottonOp {letmut fields = obj(json!({"id": row_id,"name": title,"kind": "bank","subtype": "bank","currency": "INR","counterparty_person_id": person_of(row_id),"workspace_id": WS,"created_at": NOW,"updated_at": NOW, })); fields.extend(obj(extra)); op_of(Change::create(CHILD_TABLE, row_id, fields), ms, op_id)}/// The CHILD — the write that cannot land before its parent.fn child(row_id: &str, title: &str, ms: i64) -> CottonOp { child_with(format!("op-child-{row_id}"), row_id, title, json!({}), ms)}/// One page of an answer carrying these ops and nothing else.fn page(ops: Vec<CottonOp>) -> ExchangeResponse {let cursors = ops .iter() .map(|op| (op.device_id.clone(), op.hlc.clone())) .collect::<BTreeMap<String, String>>();ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: crate::test_support::WORKSPACE.to_string(), schema_version: Some(crate::schema::ddl::SCHEMA_VERSION), ops, cursors, has_more: false, applied_rows: BTreeMap::new(), rejected: Vec::<PushRejection>::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, }}/// Fold one page as a caller would, with nothing of our own in flight.fn take(db: &Driver, response: &ExchangeResponse, now: &str) { fold_answer( db, &crate::exchange::Handed::nothing(crate::test_support::WORKSPACE), response, now, &mutcrate::exchange::Handover::default(), ) .expect("the page folds");}/// The one parked row, or a panic naming what was there instead.fn only_parked(db: &Driver) -> RejectedOp {let parked = list_parked(db, 10).expect("the parked list"); assert_eq!(parked.len(), 1, "{parked:?}"); parked.into_iter().next().expect("the row")}fn title_of(db: &Driver, row_id: &str) -> Option<String> { db.get("SELECT name AS title FROM cotton_money_accounts WHERE id = ?", &[SqlValue::Text(row_id.to_string())], ) .expect("reads") .and_then(|row| row.text("title").map(str::to_string))}// ─────────────────────────────────────────────────────────────────────────────// The patch is kept, and it is the whole op// ─────────────────────────────────────────────────────────────────────────────#[test]fn a_parked_op_can_be_rebuilt_whole() {let db = seeded();let refused = child("t1", "Renamed", 1_787_394_600_000); take(&db, &page(vec![refused.clone()]), NOW);let parked = only_parked(&db);let rebuilt = rebuild(&parked).expect("a rebuildable op");// EVERY field, not a spot check: what makes a retry safe is that the op is// the same op — same id, so a second fold is a no-op, and same stamp, so// the fold's verdict per column is unchanged. assert_eq!(rebuilt, refused);}#[test]fn a_delete_rebuilds_with_no_patch_and_a_row_without_its_receipt_refuses() {let db = seeded();// A delete is parked with a NULL patch by design; rebuilding it must not// turn that into an upsert that names nothing. park( &db, &op_of(Change::retract(CHILD_TABLE, "t1"), 1_787_394_600_000, "op-delete".to_string()),Direction::Pull,Class::Conflict,"a reason", NOW, ) .expect("a park");let parked = only_parked(&db);let rebuilt = rebuild(&parked).expect("a delete rebuilds"); assert_eq!(rebuilt.kind, OpKind::Delete); assert!(rebuilt.patch.is_none());// The same row with no receipt is a row an older build parked: there is// no honest way to invent the write.let unreceipted = RejectedOp { bytes: None, ..parked };let reason = rebuild(&unreceipted).expect_err("a row with no receipt is not an op"); assert!(reason.contains("no receipt"), "{reason}");}#[test]fn a_row_parked_without_its_receipt_says_so_rather_than_retrying() {let db = seeded(); take(&db, &page(vec![child("t1", "Renamed", 1_787_394_600_000)]), NOW);// What a row parked before receipts looks like: the bytes column is empty. db.run("UPDATE _parked SET bytes = NULL", &[]).expect("the old shape");let report = retry_rejected(&db, None, LATER).expect("a retry"); assert!(report.folded.is_empty()); assert_eq!(report.still_rejected.len(), 1); assert!( report.still_rejected[0].1.contains("no receipt"),"{:?}", report.still_rejected ); assert_eq!(only_parked(&db).retried_at.as_deref(), Some(LATER));}// ─────────────────────────────────────────────────────────────────────────────// Retrying// ─────────────────────────────────────────────────────────────────────────────#[test]fn the_count_is_the_whole_table_and_never_the_listed_page() {// The join's merge sentence says "N records need a look", and the list it// would otherwise be counted from is capped at a page. Two parked writes// and a limit of one is the smallest shape that tells the two apart.let db = seeded(); assert_eq!(count_parked(&db).expect("a count"), 0); take( &db, &page(vec![ child("t1", "Renamed", 1_787_394_600_001), child("t2", "Also renamed", 1_787_394_600_002), ]), NOW, ); assert_eq!(list_parked(&db, 1).expect("one page").len(), 1); assert_eq!(count_parked(&db).expect("a count"), 2);}#[test]fn a_retry_that_folds_clears_the_row() {let db = seeded(); take( &db, &page(vec![child("t1", "Renamed", 1_787_394_600_001)]), NOW, ); assert_eq!(only_parked(&db).table, CHILD_TABLE);// The parent lands by some other route — a direct fold, so this case is// about `retry_rejected` alone and not about the automatic hook. fold_ops(&db, &[parent("t1", "Original", 1_787_394_600_000)]).expect("the parent"); assert_eq!(title_of(&db, "t1"), None, "nothing re-offered the child yet");let report = retry_rejected(&db, None, LATER).expect("a retry"); assert_eq!(report.folded.len(), 1); assert!(report.still_rejected.is_empty()); assert!(list_parked(&db, 10).expect("the list").is_empty()); assert_eq!( title_of(&db, "t1").as_deref(),Some("Renamed"),"the child landed once its parent was here" );}#[test]fn a_retry_that_fails_again_updates_the_reason() {let db = seeded(); take( &db, &page(vec![child("t1", "Renamed", 1_787_394_600_001)]), NOW, );let first = only_parked(&db).reason;// Nothing has created the parent, so the retry meets the same wall — with a// reason of its own, written in this pass. db.run("UPDATE _parked SET reason = 'a stale sentence from the first pass'", &[], ) .expect("a rewrite");let report = retry_rejected(&db, None, LATER).expect("a retry"); assert!(report.folded.is_empty()); assert_eq!(report.still_rejected.len(), 1);let parked = only_parked(&db); assert_eq!(parked.reason, report.still_rejected[0].1); assert_eq!( parked.reason, first,"the same wall gives the same sentence — the point is that it was rewritten" ); assert_eq!(parked.retried_at.as_deref(), Some(LATER));}#[test]fn the_first_verdict_is_kept() {let db = seeded(); take( &db, &page(vec![child("t1", "Renamed", 1_787_394_600_001)]), NOW, ); retry_rejected(&db, None, LATER).expect("a retry");let parked = only_parked(&db); assert_eq!( parked.at, NOW,"`at` is when the write was FIRST lost — how long it has been stuck is \ the fact a person acts on, and a retry every page would reset it for ever" ); assert_eq!(parked.retried_at.as_deref(), Some(LATER));}#[test]fn a_retry_names_the_rows_it_was_given_and_no_others() {let db = seeded(); take( &db, &page(vec![ child("t1", "One", 1_787_394_600_001), child("t2", "Two", 1_787_394_600_002), ]), NOW, ); fold_ops( &db, &[ parent("t1", "First", 1_787_394_600_000), parent("t2", "Second", 1_787_394_600_000), ], ) .expect("both parents");let report = retry_rejected(&db, Some(&["op-child-t1".to_string()]), LATER).expect("a retry"); assert_eq!(report.folded, vec!["op-child-t1".to_string()]); assert_eq!(title_of(&db, "t1").as_deref(), Some("One")); assert_eq!(title_of(&db, "t2"), None, "t2 was not named, so nothing touched it"); assert_eq!(only_parked(&db).op_id, "op-child-t2");}#[test]fn a_write_the_peer_refused_is_never_retried_here() {let db = seeded(); park( &db, &parent("t1", "Ours", 1_787_394_600_000),Direction::Push,Class::Conflict,"UNIQUE constraint failed", NOW, ) .expect("a park");let report = retry_rejected(&db, None, LATER).expect("a retry"); assert!( report.is_empty(),"a push row is the PEER's verdict on our own write, and no local fold \ can change it: {report:?}" );let parked = only_parked(&db); assert_eq!(parked.direction, "push"); assert_eq!(parked.retried_at, None); assert_eq!(parked.reason, "UNIQUE constraint failed");}// ─────────────────────────────────────────────────────────────────────────────// The automatic pass// ─────────────────────────────────────────────────────────────────────────────#[test]fn a_row_split_across_two_pages_is_folded_on_the_second() {let db = seeded();// PAGE ONE carries only the child. This file has never seen its parent, so// it is refused on the foreign key — and the cursor moves past it, or the// page arrives for ever. take( &db, &page(vec![child("t1", "Renamed", 1_787_394_600_001)]), NOW, ); assert_eq!(only_parked(&db).row_id, "t1"); assert_eq!(title_of(&db, "t1"), None);// PAGE TWO carries the parent. Nothing asks for the retry: folding the// page runs it, scoped to the rows this page named and what waits on them. take( &db, &page(vec![parent("t1", "Original", 1_787_394_600_000)]), LATER, ); assert!( list_parked(&db, 10).expect("the list").is_empty(),"the parked child is not parked any more" ); assert_eq!( title_of(&db, "t1").as_deref(),Some("Renamed"),"the write that arrived first is the write that survived" );}#[test]fn a_page_that_changes_nothing_a_parked_op_is_waiting_on_leaves_it_alone() {let db = seeded(); take( &db, &page(vec![child("t1", "Renamed", 1_787_394_600_001)]), NOW, );// A different row entirely. The scope is `(table, row)`, so this page must// not spend anything on the parked op — and must not clear it either. take( &db, &page(vec![parent("t2", "Unrelated", 1_787_394_600_002)]), LATER, );let parked = only_parked(&db); assert_eq!(parked.op_id, "op-child-t1"); assert_eq!( parked.retried_at.as_deref(),Some(NOW),"the only page that ever offered it again was its own, and this one — \ naming a row it is not waiting on — left it exactly where it was" );}#[test]fn a_retry_that_fails_inside_a_page_keeps_the_row_and_the_page() {let db = seeded(); take( &db, &page(vec![child("t1", "Renamed", 1_787_394_600_003)]), NOW, );// The parent arrives with a workspace this file does not have, so it is// refused too; the page itself is unharmed.let id = person_of("t1");let orphan = op_of(Change::create("cotton_people", &id, obj(json!({"id": id, "full_name": "Original","workspace_id": "no-such-workspace", "created_at": NOW, "updated_at": NOW, })), ),1_787_394_600_002,"op-orphan-parent".to_string(), ); take(&db, &page(vec![orphan]), LATER);// Two parked rows now: the parent this page refused, and the child that// was already waiting.let parked = list_parked(&db, 10).expect("the list"); assert_eq!(parked.len(), 2, "{parked:?}"); assert_eq!(crate::cursors::read_cursors(&db) .expect("cursors") .get(PEER) .cloned(),Some(hlc(1_787_394_600_003)),"the cursor sat past both pages from the first one — FORWARDS ONLY, so \ a refusal never rewinds it and neither page arrives again" );}// ── the PUSH half: a write the peer refused, offered again ──────────────────//// A parked push is a write this file HAS and the peer does not. Re-folding it// here proves nothing, so the retry is the queue: the op goes back in the// `_outbox` when the row moves again, bounded by `PUSH_RETRY_CEILING`, and the// parked row is cleared only when the peer actually takes it./// The op as this device wrote it, parked because the peer refused it.fn parked_push(db: &Driver, row_id: &str, ms: i64) -> CottonOp {let op = child(row_id, "the write the peer refused", ms); park( db, &op,Direction::Push,Class::Conflict,"CHECK constraint failed: state <> 'queued' OR external_id IS NULL", NOW, ) .expect("parks"); op}fn queued_op_ids(db: &Driver) -> Vec<String> { db.all("SELECT op_id FROM _outbox ORDER BY op_id", &[]) .expect("reads") .iter() .filter_map(|row| row.text("op_id").map(str::to_string)) .collect()}/// RULE: A change a device refused is offered again the next time that row moves, so nothing is silently dropped.#[test]fn a_parked_push_goes_back_in_the_queue_when_its_row_moves_again() {let db = seeded();let op = parked_push(&db, "t1", 1_000);let queued = requeue_touched_pushes( &db, &[(CHILD_TABLE.to_string(), "t1".to_string())], LATER, ) .expect("requeues"); assert_eq!(queued, vec![op.op_id.clone()]); assert_eq!(queued_op_ids(&db), vec![op.op_id.clone()]);let row = db .get("SELECT tries AS retries, tried_at AS retried_at, first_at AS at FROM _parked WHERE op_id = ?", &[SqlValue::Text(op.op_id.clone())], ) .expect("reads") .expect("the parked row is still here"); assert_eq!(row.int("retries"), Some(1)); assert_eq!(row.text("retried_at"), Some(LATER)); assert_eq!( row.text("at"),Some(NOW),"how long a write has been stuck is the fact a person acts on" );}#[test]fn a_push_nothing_touched_is_left_alone() {let db = seeded(); parked_push(&db, "t1", 1_000);let queued = requeue_touched_pushes( &db, &[(CHILD_TABLE.to_string(), "somebody-else".to_string())], LATER, ) .expect("requeues"); assert!(queued.is_empty(), "the scope is the rows that moved"); assert!(queued_op_ids(&db).is_empty());}#[test]fn a_push_already_waiting_in_the_queue_is_not_queued_twice() {let db = seeded();let op = parked_push(&db, "t1", 1_000);let moved = [(CHILD_TABLE.to_string(), "t1".to_string())]; requeue_touched_pushes(&db, &moved, LATER).expect("requeues");let again = requeue_touched_pushes(&db, &moved, LATER).expect("requeues"); assert!(again.is_empty(), "`_outbox.op_id` is a primary key"); assert_eq!(queued_op_ids(&db), vec![op.op_id]);}#[test]fn a_push_stops_being_offered_once_it_has_had_its_turns() {let db = seeded();let op = parked_push(&db, "t1", 1_000);let moved = [(CHILD_TABLE.to_string(), "t1".to_string())];for _ in0..PUSH_RETRY_CEILING { requeue_touched_pushes(&db, &moved, LATER).expect("requeues");// The drain took it and the peer refused it again: off the queue, still// parked. db.run("DELETE FROM _outbox", &[]).expect("drains"); }let past_the_ceiling = requeue_touched_pushes(&db, &moved, LATER).expect("requeues"); assert!( past_the_ceiling.is_empty(),"a write refused by a constraint must not cost an exchange slot for ever" );let row = db .get("SELECT tries AS retries FROM _parked WHERE op_id = ?", &[SqlValue::Text(op.op_id)], ) .expect("reads") .expect("parked"); assert_eq!(row.int("retries"), Some(PUSH_RETRY_CEILING));}#[test]fn the_parked_row_goes_when_the_peer_finally_takes_the_write() {let db = seeded();let op = parked_push(&db, "t1", 1_000); clear_delivered_pushes(&db, std::slice::from_ref(&op.op_id)).expect("clears"); assert_eq!( count_parked(&db).expect("counts"),0,"`_parked` means writes that are still missing" );}#[test]fn a_pull_is_never_put_in_the_queue() {let db = seeded();let op = child("t1", "a peer's write this file refused", 1_000); park(&db, &op, Direction::Pull, Class::Conflict, "NOT NULL constraint failed", NOW).expect("parks");let queued = requeue_touched_pushes( &db, &[(CHILD_TABLE.to_string(), "t1".to_string())], LATER, ) .expect("requeues"); assert!( queued.is_empty(),"a pull is missing HERE — the fold is its retry, not the queue" );}// ─────────────────────────────────────────────────────────────────────────────// The retries ask by row, and one page's worth of rows is ONE ask per table// ─────────────────────────────────────────────────────────────────────────────/// More touched rows than one `IN (…)` may carry, so the chunk boundary is/// crossed rather than described.const OVER_A_CHUNK: usize = ROW_CHUNK + 7;#[test]fn every_parked_write_of_a_page_bigger_than_one_chunk_is_still_found() {// The failure this guards is silent: a batch that outgrew its `IN (…)` and// quietly retried only the first four hundred rows would look exactly like// a healthy sync while the rest stayed parked for ever.let db = seeded();letmut amendments = Vec::new();for index in0..OVER_A_CHUNK { amendments.push(child(&format!("row-{index:04}"), "amended", 9_000 + index as i64)); } take(&db, &page(amendments), NOW); assert_eq!( list_parked(&db, 10_000).expect("the parked list").len(), OVER_A_CHUNK,"every child is parked: there is no parent for any of them yet" );// Now the parents arrive — every one of them, in one page.let births: Vec<CottonOp> = (0..OVER_A_CHUNK) .map(|index| parent(&format!("row-{index:04}"), "born", 2_000 + index as i64)) .collect(); take(&db, &page(births), LATER); assert!( list_parked(&db, 10_000).expect("the parked list").is_empty(),"every parked child was retried, not just the first chunk" );for index in0..OVER_A_CHUNK { assert_eq!( title_of(&db, &format!("row-{index:04}")).as_deref(),Some("amended"),"row {index} landed" ); }}#[test]fn a_row_id_another_table_also_uses_does_not_retry_the_wrong_write() {// The lookup is `(direction, tbl, row_id)` and the table is half of it: two// tables can hold the same row id, and grouping the ask BY TABLE is only// correct if the table is still part of the question.let db = seeded();let shared = "1111aaaa-0000-4000-8000-000000000001"; take(&db, &page(vec![child(shared, "amended", 1_000)]), NOW);let parked = only_parked(&db); assert_eq!(parked.table, CHILD_TABLE);// A row with the SAME id in a different table moves. Nothing the account was// waiting on has arrived, so it stays parked.let moved = vec![("cotton_notes".to_string(), shared.to_string())];let report = retry_touched_rows(&db, &moved, &BTreeSet::new(), LATER).expect("retries"); assert!(report.is_empty(), "{report:?}"); assert_eq!(only_parked(&db).op_id, parked.op_id);}#[test]fn the_same_row_named_twice_in_a_page_is_asked_about_once() {// `applied_rows` is whatever the fold moved, and a page can name one row// more than once. A retry that ran per NAME would offer the same op to the// fold twice and report it twice; the ask is over the distinct rows.let db = seeded();let row = "2222bbbb-0000-4000-8000-000000000002"; take(&db, &page(vec![child(row, "amended", 1_000)]), NOW); take(&db, &page(vec![parent(row, "born", 2_000)]), LATER); assert!(list_parked(&db, 10).expect("the parked list").is_empty());let twice = vec![ (CHILD_TABLE.to_string(), row.to_string()), (CHILD_TABLE.to_string(), row.to_string()), ];let report = retry_touched_rows(&db, &twice, &BTreeSet::new(), LATER).expect("retries"); assert!(report.is_empty(), "nothing is parked, so nothing is reported: {report:?}");}// ─────────────────────────────────────────────────────────────────────────────// A write said again is not a second write missing// ─────────────────────────────────────────────────────────────────────────────/// The same write, as a given pass of a worker would send it again.fn pass(row_id: &str, title: &str, ms: i64) -> CottonOp { child_with(format!("op-pass-{ms}-{row_id}"), row_id, title, json!({}), ms)}#[test]fn a_row_that_never_lands_parks_one_write_and_not_one_per_pass() {// The shape that put 41,112 parked ops on one standby Mac for 485 rows: a// row that can never land is sent again on every pass of its mirror — the// same columns, refused the same way, and parked under a NEW op id once a// minute, for ever.let db = seeded();let row = "3333cccc-0000-4000-8000-000000000003";for minute in0..20 { take(&db, &page(vec![pass(row, "from the mirror", 1_000 + minute)]), NOW); }let parked = list_parked(&db, 100).expect("the parked list"); assert_eq!( parked.len(),1,"twenty passes of one unchanged sentence are one write missing, not twenty: {parked:?}" ); assert_eq!(parked[0].hlc.as_deref(), Some(hlc(1_019).as_str()), "the NEWEST is the one kept");}#[test]fn the_kept_row_says_how_long_the_write_has_been_stuck_and_not_how_long_ago_it_was_repeated() {// `at` is the fact a person acts on. A supersede that took the new// arrival's clock would report a four-day loss as a one-minute-old one on// every pass, for ever.let db = seeded();let row = "4444dddd-0000-4000-8000-000000000004"; take(&db, &page(vec![pass(row, "first", 1_000)]), NOW); take(&db, &page(vec![pass(row, "again", 2_000)]), LATER);let parked = only_parked(&db); assert_eq!(parked.at, NOW, "the FIRST verdict's time came across with the row"); assert_eq!(parked.hlc.as_deref(), Some(hlc(2_000).as_str()));}#[test]fn a_write_naming_a_column_the_newer_one_does_not_is_still_the_only_copy_of_it() {// The rule is a SUBSET, and this is the whole reason it has to be: the// creation carries columns no amendment does, and losing it would lose the// row for good.let db = seeded();let row = "5555eeee-0000-4000-8000-000000000005";let wider = child_with("op-wider".to_string(), row,"both", json!({ "institution": "the only copy of this column" }),1_000, ); take(&db, &page(vec![wider]), NOW); take(&db, &page(vec![child(row, "narrower", 2_000)]), LATER);let parked = list_parked(&db, 100).expect("the parked list"); assert_eq!( parked.len(),2,"the older write names `institution`; nothing the newer one says covers it: {parked:?}" );}#[test]fn a_delete_is_never_said_again_by_an_upsert() {// A delete carries no patch and says something no upsert says. There is no// subset to test, so there is nothing to supersede in either direction.let db = seeded();let row = "6666ffff-0000-4000-8000-000000000006";let removal = op_of(Change::retract(CHILD_TABLE, row), 1_000, "op-delete".to_string()); park(&db, &removal, Direction::Pull, Class::Conflict, "a refusal", NOW).expect("parks");let later = op_of(Change::update(CHILD_TABLE, row, obj(json!({ "name": "said later" }))),2_000,"op-upsert".to_string(), ); park(&db, &later, Direction::Pull, Class::Conflict, "a refusal", LATER).expect("parks"); assert_eq!(list_parked(&db, 10).expect("the parked list").len(), 2);}#[test]fn our_own_refused_write_is_not_said_again_by_the_peers() {// The two directions are two different losses — ours refused THERE, theirs// refused HERE — and one never speaks for the other.let db = seeded();let row = "7777aaaa-0000-4000-8000-000000000007"; park(&db, &pass(row, "same columns", 1_000), Direction::Push, Class::Conflict, "refused", NOW).expect("parks"); park(&db, &pass(row, "same columns", 2_000), Direction::Pull, Class::Conflict, "refused", LATER) .expect("parks"); assert_eq!(list_parked(&db, 10).expect("the parked list").len(), 2);}// ─────────────────────────────────────────────────────────────────────────────// THE CREATION ITSELF IS REFUSED — the shape every park on a real replica had//// Above, the amendment is the write that cannot stand alone and the creation// always lands. On a standby Mac holding 23,841 parked pull ops, not one of// them looked like that: the op that got refused was the WHOLE ROW — a session// whose project had not arrived, a prompt whose session had not — and every// later fragment of the same row was then refused too, because an INSERT of// three columns cannot satisfy a NOT NULL it does not name.//// That shape used to be unhealable by construction. The page's retry was// scoped to the rows the fold APPLIED, and a row whose creation is refused has// no applied op, so nothing ever offered the creation again: every one of// those 23,841 rows read `retries = 0`. Two things fix it and the cases below// are one each — the page retries the rows it NAMED, and the cycle sweeps.//// Since schema 81 a session's project is a plain reference that refuses// nothing, so the cases below take the same shape from a key that still// does: an account whose counterparty person has not arrived, with person handles// (owned by that person) waiting dormant beside it.// ─────────────────────────────────────────────────────────────────────────────const PERSON: &str = "88880000-0000-4000-8000-000000000001";const ACCOUNT: &str = "88880000-0000-4000-8000-000000000002";/// The person an account's foreign key points at.fn person_birth(ms: i64) -> CottonOp { op_of(Change::create("cotton_people", PERSON, obj(json!({"id": PERSON,"workspace_id": WS,"full_name": "Asha Rao","created_at": NOW,"updated_at": NOW, })), ), ms,"op-person".to_string(), )}/// The op that CREATES the account. Its `counterparty_person_id` only/// points, but it still holds a foreign key, so while the person is missing/// the create is refused on it and parked.fn account_birth(ms: i64) -> CottonOp { account_birth_of(ACCOUNT, ms, "op-account-birth")}/// [`account_birth`] for an account of its own id.fn account_birth_of(id: &str, ms: i64, op_id: &str) -> CottonOp { op_of(account_change(id), ms, op_id.to_string())}fn account_change(id: &str) -> Change {Change::create( CHILD_TABLE, id, obj(json!({"id": id,"workspace_id": WS,"kind": "bank","subtype": "bank","name": "Joint savings","currency": "INR","counterparty_person_id": PERSON,"created_at": NOW,"updated_at": NOW, })), )}/// A later change to the same account. Before its create it is no park: it/// waits DORMANT (3.7 point 6) and shows when the create lands.fn account_fragment(ms: i64, institution: &str) -> CottonOp { op_of(Change::update(CHILD_TABLE, ACCOUNT, obj(json!({ "institution": institution, "updated_at": LATER }))), ms, format!("op-account-fragment-{ms}"), )}/// The create of a handle filed under the same person. `person_id` OWNS the/// handle, so while the person is not present the handle is DORMANT — stored,/// reported applied, never parked — and the person's arrival re-assembles it.fn handle_change(seq: i64) -> Change {let row_id = format!("88880000-0000-4000-8000-00000000100{seq}");Change::create("cotton_person_handles", &row_id, obj(json!({"id": row_id,"workspace_id": WS,"person_id": PERSON,"kind": "email","value": format!("asha-{seq}@example.test"),"normalised": format!("asha-{seq}@example.test"),"source": "manual","created_at": NOW,"updated_at": NOW, })), )}fn handle_birth(seq: i64, ms: i64) -> CottonOp { op_of(handle_change(seq), ms, format!("op-handle-{seq}"))}/// How many pull writes this file is still missing.fn parked_pulls(db: &Driver) -> usize { list_parked(db, 1_000) .expect("the parked list") .iter() .filter(|row| row.direction == "pull") .count()}/// The account's `institution`, or `None` while the account is not here.fn institution(db: &Driver) -> Option<String> { db.get("SELECT COALESCE(institution, '') AS v FROM cotton_money_accounts WHERE id = ?", &[SqlValue::Text(ACCOUNT.to_string())], ) .expect("reads") .and_then(|row| row.text("v").map(str::to_string))}#[test]fn a_refused_creation_is_folded_by_the_next_page_that_names_its_row() {let db = seeded();// PAGE ONE: the whole account, refused — its person has not arrived. take(&db, &page(vec![account_birth(1_000)]), NOW); assert_eq!(parked_pulls(&db), 1); assert_eq!(institution(&db), None);// The person arrives by a road that retries nothing — a fold with no page// around it — so the account is still parked.let person = fold_ops(&db, &[person_birth(2_000)]).expect("folds"); assert!(person.rejected.is_empty(), "{person:?}"); assert_eq!(parked_pulls(&db), 1);// PAGE TWO: a fragment of the account — two columns of a row this file// still has not got. It is stored dormant, and THEN the page retries the// parked writes of every row it NAMED: the creation lands, and the row// shows whole with the fragment's value on top. take(&db, &page(vec![account_fragment(3_000, "Quillmere")]), LATER); assert_eq!( parked_pulls(&db),0,"the creation landed once the page named the row" ); assert_eq!(institution(&db).as_deref(), Some("Quillmere"));}// ── the parks WAITING ON a row a page names ─────────────────────────────────#[test]fn a_child_parked_pages_before_its_parent_lands_with_the_page_that_brings_the_parent() {// An answer is not causal across pages: a handle can come pages before its// person, while the account also waits on that person. The page// that brings the person re-offers what waited on it, and then what waited on// THAT, in the same transaction — no sweep, no row named twice.let db = seeded(); take(&db, &page(vec![handle_birth(1, 3_000), handle_birth(2, 3_100)]), NOW); take(&db, &page(vec![account_birth(2_000), account_fragment(2_500, "SBI")]), NOW); assert_eq!(parked_pulls(&db), 1, "the account and handles wait on the missing person"); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM cotton_person_handles"), 0); take(&db, &page(vec![person_birth(1_000)]), LATER); assert_eq!(parked_pulls(&db), 0, "the whole chain landed with its root"); assert_eq!(institution(&db).as_deref(), Some("SBI"), "the fragment landed on top of its creation"); assert_eq!( count(&db, "SELECT COUNT(*) AS c FROM cotton_person_handles"),2,"both handles behind the person" );}#[test]fn a_park_whose_parent_never_arrives_stays_parked_and_names_why() {let db = seeded(); take(&db, &page(vec![handle_birth(1, 3_000)]), NOW); take(&db, &page(vec![account_birth(2_000)]), NOW);// A page naming a row nothing waits on: nothing is offered at all.let report = retry_touched_rows( &db, &[(CHILD_TABLE.to_string(), "no-such-account".to_string())], &BTreeSet::new(), LATER, ) .expect("retries"); assert!(report.is_empty(), "{report:?}");// The account is named, but its person is still missing: it is offered// and refused again, once. The handle under that person is dormant, not parked.let report = retry_touched_rows( &db, &[(CHILD_TABLE.to_string(), ACCOUNT.to_string())], &BTreeSet::new(), LATER, ) .expect("retries"); assert!(report.folded.is_empty(), "{report:?}"); assert_eq!(report.still_rejected.len(), 1, "{report:?}"); assert_eq!(parked_pulls(&db), 1); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM cotton_person_handles"), 0);}fn count(db: &Driver, sql: &str) -> i64 { db.get(sql, &[]) .expect("reads") .and_then(|row| row.int("c")) .unwrap_or(-1)}#[test]fn a_page_that_applies_nothing_still_retries_the_rows_it_named() {// The regression in one sentence. A page whose ops land nothing visible —// here one dormant fragment — must still re-offer the parks of the rows it// NAMED; the old scope (what the fold APPLIED) meant a row whose creation// was refused could never heal.let db = seeded(); take(&db, &page(vec![account_birth(1_000)]), NOW); db.run("INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \ VALUES (?,?,?,?,?)", &[SqlValue::Text(PERSON.to_string()),SqlValue::Text(WS.to_string()),SqlValue::Text("Asha Rao".to_string()),SqlValue::Text(NOW.to_string()),SqlValue::Text(NOW.to_string()), ], ) .expect("the person arrives by some other road");// One op, dormant (the row is not there yet), naming the parked row. take(&db, &page(vec![account_fragment(3_000, "ICICI")]), LATER); assert_eq!(parked_pulls(&db), 0); assert_eq!(institution(&db).as_deref(), Some("ICICI"));}// ── the sweep: the parks whose cause is a DIFFERENT row ─────────────────────#[test]fn the_sweep_folds_a_park_whose_parent_arrived_in_some_other_page() {let db = seeded();// Three accounts of a person this file has not got: whole rows, each// refused on the (pointing) foreign key. No later page will ever name them —// the peer's cursor is past them — so only a sweep can reach them. take( &db, &page(vec![ account_birth_of("a-1", 1_000, "op-account-1"), account_birth_of("a-2", 1_100, "op-account-2"), account_birth_of("a-3", 1_200, "op-account-3"), ]), NOW, ); assert_eq!(parked_pulls(&db), 3);// The person arrives by a road that retries nothing — the shape of a// file that was carrying parks before any page could reach them.let parents = fold_ops(&db, &[person_birth(2_000)]).expect("folds"); assert!(parents.rejected.is_empty(), "{parents:?}"); assert_eq!(parked_pulls(&db), 3, "no page names an account ever again");let swept = sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); assert_eq!(swept.parked, 3); assert_eq!(swept.retried, 3); assert_eq!(swept.cleared, 3); assert_eq!(parked_pulls(&db), 0);}#[test]fn the_sweep_folds_a_whole_chain_of_parents_in_one_pass() {// The stamp order inside the batch is what does this: a row is created// before anything can point at it, so a parent sorts ahead of the child// whose foreign key wants it and one pass is enough however deep the chain// goes. (Inside ONE page the fold's own second pass already does this; the// chain here is spread over pages, which is where it could not.)let db = seeded(); take(&db, &page(vec![handle_birth(1, 3_000)]), NOW); take(&db, &page(vec![account_birth(2_000)]), NOW); assert_eq!(parked_pulls(&db), 1, "the account and handle wait on the person");// The person arrives by a road that retries nothing.let person = fold_ops(&db, &[person_birth(1_000)]).expect("folds"); assert!(person.rejected.is_empty(), "{person:?}"); assert_eq!(parked_pulls(&db), 1);let swept = sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); assert_eq!(swept.retried, 1); assert_eq!(swept.cleared, 1, "the account, while the handle re-assembled behind the person"); assert_eq!(parked_pulls(&db), 0); assert_eq!(institution(&db).as_deref(), Some(""), "the account landed, with no institution"); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM cotton_person_handles"), 1);}#[test]fn the_sweep_spends_its_budget_and_no_more_and_rotates_over_the_rest() {let db = seeded(); take( &db, &page(vec![ account_birth_of("a-1", 1_000, "op-account-1"), account_birth_of("a-2", 1_100, "op-account-2"), account_birth_of("a-3", 1_200, "op-account-3"), account_birth_of("a-4", 1_300, "op-account-4"), ]), NOW, ); assert_eq!(parked_pulls(&db), 4);// Nothing can fold yet — the person is still missing — so this pass is// purely about WHICH writes a bounded sweep picks up.let first = sweep_parked(&db, 2, LATER).expect("a sweep"); assert_eq!(first.parked, 4); assert_eq!(first.retried, 2, "the budget is a budget"); assert_eq!(first.cleared, 0); assert_eq!( tried_at(&db, LATER), vec!["op-account-1".to_string(), "op-account-2".to_string()],"the two oldest stamps went first" );// The next pass takes the two least recently tried: a ROTATION, so no// parked write can starve behind another however long the list is. sweep_parked(&db, 2, LATEST).expect("a second sweep"); assert_eq!( tried_at(&db, LATEST), vec!["op-account-3".to_string(), "op-account-4".to_string()],"and the two nobody had got to yet" );}/// The parked ops whose last attempt was at this moment, by op id.fn tried_at(db: &Driver, at: &str) -> Vec<String> {letmut ids: Vec<String> = list_parked(db, 50) .expect("the list") .into_iter() .filter(|row| row.retried_at.as_deref() == Some(at)) .map(|row| row.op_id) .collect(); ids.sort(); ids}#[test]fn a_file_with_nothing_parked_has_nothing_to_say() {let db = seeded();let swept = sweep_parked(&db, PARK_SWEEP_OPS, NOW).expect("a sweep"); assert!(swept.is_empty()); assert_eq!(swept, SweepReport::default());}#[test]fn the_sweep_never_touches_our_own_refused_writes() {// A push is the PEER's verdict on a write this file already holds. Folding// it here would answer "stale" and delete the one record that says the// peer has not got it.let db = seeded();let row = "7777aaaa-0000-4000-8000-000000000009"; park(&db, &pass(row, "ours", 1_000), Direction::Push, Class::Conflict, "the peer refused", NOW) .expect("parks");let swept = sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); assert_eq!((swept.parked, swept.retried), (0, 0), "there are no parked PULLS here"); assert_eq!(list_parked(&db, 10).expect("the list").len(), 1);}/// RULE: A parked write is never dropped for being refused often: a `waiting` park outlives any number of sweeps, counting each, until it applies or the owner discards it.#[test]fn waiting_op_survives_more_than_sixty_sweeps() {// An account of a person who never arrives: refused on the foreign key// by every sweep, for as long as the file lives.let db = seeded(); take(&db, &page(vec![account_birth(1_000)]), NOW); assert_eq!(parked_pulls(&db), 1); assert_eq!(only_parked(&db).class, "waiting", "a parent never seen is waiting");for _ in0..61 {let swept = sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); assert_eq!((swept.retried, swept.cleared), (1, 0)); }let row = only_parked(&db);// 61 sweeps, each refusal counted once; the page's own verdict is the// park itself, never an offer again. assert_eq!(row.retries, 61, "each refusal counted once"); assert_eq!(row.class, "waiting"); assert_eq!(row.at, NOW, "the first verdict's time never moves");// And the parent arriving still heals it, however long it waited. take(&db, &page(vec![person_birth(500)]), LATEST); sweep_parked(&db, PARK_SWEEP_OPS, LATEST).expect("a sweep"); assert_eq!(parked_pulls(&db), 0);}/// RULE: A park the owner discards ends, and only that park.#[test]fn the_owner_discards_a_park() {let db = seeded(); take(&db, &page(vec![account_birth(1_000)]), NOW);let parked = only_parked(&db); assert_eq!(discard(&db, &["op-unknown".to_string()]).expect("discards"), 0); assert_eq!(discard(&db, &[parked.op_id]).expect("discards"), 1); assert_eq!(parked_pulls(&db), 0);}/// RULE: The owner's board names every `conflict` park and every `waiting` park older than seven days, one line each, and nothing else.#[test]fn the_board_names_conflicts_and_old_waiting_parks() {let db = seeded(); take(&db, &page(vec![account_birth(1_000)]), NOW); assert!(board(&db, LATER).expect("a board").is_empty(), "a fresh waiting park is not news");let a_week_on = "2026-09-15T10:00:01.000Z"; assert_eq!(board(&db, a_week_on).expect("a board").len(), 1, "a week-old waiting park is");let row = "7777aaaa-0000-4000-8000-00000000000b"; park(&db, &pass(row, "clash", 2_000), Direction::Pull, Class::Conflict, "UNIQUE constraint failed", NOW) .expect("parks");let lines = board(&db, LATER).expect("a board"); assert_eq!(lines.len(), 1, "{lines:?}"); assert!(lines[0].contains("conflict") && lines[0].contains(row), "{lines:?}");}/// RULE: A parked pull stamped with a schema newer than this build's stays parked and is never dropped, because the update is what folds it.#[test]fn a_park_from_a_newer_schema_is_kept_for_the_update() {let db = seeded();// A receipt minted by a newer build: its schema is in the bytes.let ahead = SCRATCH.with(|db| {letmut receipt = crate::mint::receipt_of( db,"test", &account_change(ACCOUNT), &hlc(1_000), PEER, &crate::fixtures::fixture_actor().to_wire(), ) .expect("a receipt"); receipt.schema = crate::schema::ddl::SCHEMA_VERSION + 1;crate::wire::from_receipt("op-account-birth".to_string(), &receipt).expect("an op") }); take(&db, &page(vec![ahead]), NOW);// Every pull park, whatever its class: from rise 136 this one is// `newer-shape`, which the owner's list leaves out. assert_eq!(select(&db, None).expect("parks").len(), 1);for _ in0..=61 { sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); } assert_eq!(select(&db, None).expect("parks").len(), 1); assert_eq!( newest_parked_schema(&db).expect("reads"),Some(crate::schema::ddl::SCHEMA_VERSION + 1) );}// ── a HUB parent is never followed ──────────────────────────────────────────/// A page renaming the workspace — one column of a row this file holds.fn workspace_rename(ms: i64) -> CottonOp { op_of(Change::update("cotton_workspaces", WS, obj(json!({ "name": "Renamed" }))), ms, format!("op-workspace-rename-{ms}"), )}#[test]fn touching_the_workspace_re_offers_no_park_that_merely_names_it() {// Every parked creation carries `workspace_id`. Following that key would// make one rename a re-fold of every park in the file, inside one page.// The handles and the account wait on a person: neither is the// workspace's to heal.let db = seeded();// The workspace row's own create, so a change to it has a row to land on// (a row with no create receipt is dormant to every change, 3.7 point 6). fold_ops( &db, &[op_of(Change::create("cotton_workspaces", WS, obj(json!({"id": WS,"name": "Asha","owner_user_id": crate::test_support::OWNER,"created_at": "2026-08-22T10:30:00.000Z", })), ),500,"op-workspace".to_string(), )], ) .expect("the workspace's create"); take(&db, &page(vec![handle_birth(1, 3_000), handle_birth(2, 3_100)]), NOW); take(&db, &page(vec![account_birth(2_000), account_fragment(2_500, "SBI")]), NOW); assert_eq!(parked_pulls(&db), 1, "the account and handles wait on the person");let before = list_parked(&db, 1_000).expect("the parked list");// The same path a page takes: the rename folds, then the page retries// the rows it named — the workspace row. take(&db, &page(vec![workspace_rename(4_000)]), LATER); assert_eq!( count(&db, "SELECT COUNT(*) AS c FROM cotton_workspaces WHERE name = 'Renamed'"),1,"the rename landed" );// A re-offer that fails again rewrites `retried_at` (and `reason`): an// untouched list is a list nothing was offered from.let after = list_parked(&db, 1_000).expect("the parked list"); assert_eq!(after, before, "a park was re-offered by the rename"); assert!(after.iter().all(|row| row.retried_at.as_deref() != Some(LATER)));// And asked directly: nothing offered, nothing folded, nothing refused.let report = retry_touched_rows( &db, &[("cotton_workspaces".to_string(), WS.to_string())], &BTreeSet::new(), LATEST, ) .expect("retries"); assert!(report.is_empty(), "{report:?}");}#[test]fn a_non_hub_parent_landing_still_re_offers_the_children_that_name_the_workspace_too() {// The account carries BOTH keys — the workspace and the person.// Skipping the hub must not skip the person: when it lands, the account// lands, and the dormant handles and account come back with it.let db = seeded(); take(&db, &page(vec![handle_birth(1, 3_000), handle_birth(2, 3_100)]), NOW); take(&db, &page(vec![account_birth(2_000)]), NOW); assert_eq!(parked_pulls(&db), 1); take(&db, &page(vec![person_birth(1_000)]), LATER); assert_eq!(parked_pulls(&db), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM cotton_money_accounts"), 1); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM cotton_person_handles"), 2);}// ── newer-shape: a receipt minted above this file's schema ─────────────────/// This file's `_parked` as rise 136 builds it: the CHECK admits/// `newer-shape`. The file stays at this build's stamp; only the park/// table's shape moves, which is all the class needs.fn at_rise_136(db: &Driver) {let sql = crate::schema::ddl::PARKED_TABLE .replace(",'newer-shape'))", "))") .replace("'unverified'))", "'unverified','newer-shape'))") .replace("IF NOT EXISTS ", ""); assert!(sql.contains("'newer-shape'"), "the CHECK is where this fixture expects it"); db.exec("ALTER TABLE _parked RENAME TO _parked_before").expect("renames"); db.exec(&sql).expect("the 136 _parked"); db.exec("INSERT INTO _parked SELECT * FROM _parked_before").expect("copies"); db.exec("DROP TABLE _parked_before").expect("drops"); db.exec(crate::schema::ddl::PARKED_ROW_INDEX).expect("indexes");}/// `op` as the build one schema ahead would mint it: the same write, its/// receipt saying `schema + 1`.fn minted_ahead(op: &CottonOp) -> CottonOp {letmut receipt = crate::canonical::decode(op.receipt.as_bytes()).expect("decodes"); receipt.schema += 1;let bytes = crate::canonical::encode(&receipt).expect("encodes");crate::wire::from_bytes(op.op_id.clone(), &bytes).expect("reads back")}fn people(db: &Driver, id: &str) -> i64 { db.get("SELECT COUNT(*) AS n FROM cotton_people WHERE id = ?", &[SqlValue::Text(id.to_string())]) .expect("counts") .and_then(|row| row.int("n")) .unwrap_or(0)}/// RULE: A receipt minted above this file's schema is parked newer-shape — not folded, not refused to its pusher, off the owner's board, the parked list and the parked count — stays parked through every retry while the file is below it, and folds the moment refold_newer_shape runs after the file has moved to its schema; folding it earlier would write a shape this file cannot hold, and showing it would ask the owner about a write nothing is wrong with (schema programme, 12 Oct 2026).#[test]fn a_receipt_above_the_file_waits_off_the_board_and_folds_after_the_move() {let db = seeded(); at_rise_136(&db);let ahead = minted_ahead(&parent("ahead", "Asha", 1_000));let here = crate::meta::file_schema_version(&db).expect("stamp");let folded = crate::exchange::fold_incoming(&db, std::slice::from_ref(&ahead)).expect("folds"); assert!(folded.rejected.is_empty(), "the pusher is not refused: {:?}", folded.rejected); assert_eq!(people(&db, &person_of("ahead")), 0, "not folded while the file is below it");let parked = select(&db, None).expect("parks"); assert_eq!(parked.len(), 1); assert_eq!(parked[0].class, "newer-shape"); assert!(board(&db, LATEST).expect("board").is_empty(), "off the owner's board"); assert!(list_parked(&db, 100).expect("list").is_empty(), "off the parked list"); assert_eq!(count_parked(&db).expect("count"), 0, "off the parked count");let retried = retry_rejected(&db, None, LATER).expect("retries"); assert!(retried.folded.is_empty(), "a retry below its schema folds nothing"); assert_eq!(people(&db, &person_of("ahead")), 0); assert_eq!(select(&db, None).expect("parks")[0].class, "newer-shape");// The move, as far as the park is concerned: the file's stamp reaches it. db.exec(&format!("PRAGMA user_version = {}", here + 1)).expect("stamps");let refolded = refold_newer_shape(&db, LATEST).expect("refolds"); assert_eq!(refolded.folded, vec![ahead.op_id.clone()]); assert_eq!(people(&db, &person_of("ahead")), 1, "folded after the move"); assert!(select(&db, None).expect("parks").is_empty(), "the park ended");}/// RULE: A phone's pulled answer parks a receipt above its file as newer-shape too and folds the rest of the page — the same rule on both sides of the exchange, because one implementation of who wins runs on the server and the phone.#[test]fn a_pulled_receipt_above_the_file_waits_and_its_page_folds() {let db = seeded(); at_rise_136(&db);let ahead = minted_ahead(&parent("ahead", "Asha", 1_000));let level = parent("level", "Bela", 2_000);let response = ExchangeResponse { answered_by: None, wanted: Vec::new(), copy: None, workspace_id: WS.to_string(), ops: vec![ahead.clone(), level], cursors: BTreeMap::new(), has_more: false, schema_version: Some(crate::schema::ddl::SCHEMA_VERSION + 1), applied_rows: BTreeMap::new(), 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, }; fold_answer( &db, &crate::exchange::Handed::nothing(WS), &response, NOW, &mutcrate::exchange::Handover::shut(), ) .expect("folds the answer"); assert_eq!(people(&db, &person_of("level")), 1, "the rest of the page folds"); assert_eq!(people(&db, &person_of("ahead")), 0);let parked = select(&db, None).expect("parks"); assert_eq!(parked.len(), 1); assert_eq!((parked[0].op_id.as_str(), parked[0].class.as_str()), (ahead.op_id.as_str(), "newer-shape"));}/// This file's `_parked` as every build before rise 136 made it: the CHECK/// without `newer-shape`.fn before_rise_136(db: &Driver) {let sql = crate::schema::ddl::PARKED_TABLE .replace(",'newer-shape'))", "))") .replace("IF NOT EXISTS ", ""); db.exec("DROP TABLE _parked").expect("drops"); db.exec(&sql).expect("the pre-136 _parked"); db.exec(crate::schema::ddl::PARKED_ROW_INDEX).expect("indexes");}/// RULE: In a file whose _parked cannot hold newer-shape (every file before rise 136), a receipt above it is held retryable and coded server_behind — kept on its device, never refused for good and never folded — so the parking switches on with the CHECK and not one build before it.#[test]fn a_file_whose_parked_cannot_hold_newer_shape_holds_the_receipt_on_its_device() {let db = seeded(); before_rise_136(&db); assert!(!keeps_newer_shape(&db).expect("reads"), "a pre-136 _parked cannot hold the class");let ahead = minted_ahead(&parent("ahead", "Asha", 1_000));let folded = crate::exchange::fold_incoming(&db, std::slice::from_ref(&ahead)).expect("folds"); assert_eq!(folded.rejected.len(), 1); assert_eq!(folded.rejected[0].retryable, Some(true)); assert_eq!( folded.rejected[0].code.as_deref(),Some(crate::protocol::types::REJECTION_SERVER_BEHIND) ); assert_eq!(people(&db, &person_of("ahead")), 0); assert!(select(&db, None).expect("parks").is_empty(), "nothing parked");}// ─────────────────────────────────────────────────────────────────────────────// A conflict waits for its row or the shape, not for the clock// ─────────────────────────────────────────────────────────────────────────────/// A money account the file's own CHECK refuses: no foreign key in the way,/// a subtype this shape does not name.fn refused_by_the_shape(row_id: &str, ms: i64) -> CottonOp { child_with( format!("op-refused-{row_id}"), row_id,"a shape the file refuses", json!({"counterparty_person_id": null, "subtype": "not-a-subtype"}), ms, )}/// RULE: A `conflict` park is offered by the sweep once at each shape: the page that parked it tried it, so no sweep offers it again — however many — until the file's shape moves (`shape_changed`, which a move, a served column and a package's table call) or its row moves; and the write arriving again is the park already said, not a new one.#[test]fn a_conflict_is_swept_once_at_each_shape_and_waits_for_its_row_or_the_shape() {let db = seeded();let row = "8888eeee-0000-4000-8000-00000000000c";let refused = refused_by_the_shape(row, 1_000); take(&db, &page(vec![refused.clone()]), NOW);let parked = only_parked(&db); assert_eq!(parked.class, "conflict", "{parked:?}");let tries = parked.retries;for _ in0..5 {let swept = sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); assert_eq!((swept.parked, swept.retried), (1, 0), "a tried conflict waits for its row or the shape"); } assert_eq!(only_parked(&db).retries, tries, "no sweep offered it"); assert!( !park(&db, &refused, Direction::Pull, Class::Conflict, "said again", LATER).expect("parks"),"the same write arriving again is the park already said" ); assert_eq!(shape_changed(&db).expect("the shape moved"), 1);let swept = sweep_parked(&db, PARK_SWEEP_OPS, LATEST).expect("a sweep"); assert_eq!(swept.retried, 1, "once at the new shape"); assert_eq!(only_parked(&db).retries, tries + 1); assert_eq!(sweep_parked(&db, PARK_SWEEP_OPS, LATEST).expect("a sweep").retried, 0, "and once only"); assert_eq!(only_parked(&db).at, NOW, "the first verdict's time never moves");}/// RULE: A column the copy takes for the object's definition is a shape that moved: the conflicts it holds are due again.#[test]fn a_column_the_copy_takes_makes_its_conflicts_due_again() {let db = seeded(); take(&db, &page(vec![refused_by_the_shape("8888eeee-0000-4000-8000-00000000000d", 1_000)]), NOW); assert_eq!(sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep").retried, 0);let column = crate::schema::package_shape::served_column("note_line", "text", false).expect("a text column");crate::schema::package_shape::add_served(&db, CHILD_TABLE, &[column]).expect("adds"); assert_eq!(sweep_parked(&db, PARK_SWEEP_OPS, LATEST).expect("a sweep").retried, 1);}/// A money account the file's shape refuses, as a copy minted it from a row/// its writer served, stamped by `author`.fn served_by(author: &str, row_id: &str, ms: i64, op_id: &str) -> CottonOp {let change = Change::create( CHILD_TABLE, row_id, obj(json!({"id": row_id, "name": "served", "kind": "bank", "subtype": "not-a-subtype", "currency": "INR","workspace_id": WS, "created_at": NOW, "updated_at": NOW, })), ); SCRATCH.with(|db| {crate::wire::op_of_change(db, &change, &format!("{ms:013}:0002:{author}"), author, &crate::fixtures::fixture_actor(), op_id.to_string()) .expect("a receipt") })}fn parked_ids(db: &Driver) -> Vec<String> {letmut ids: Vec<String> = list_parked(db, 50).expect("the list").into_iter().map(|row| row.op_id).collect(); ids.sort(); ids}/// RULE: A parked receipt of an author's old name ends once the copy holds the same row under the new name from the same moment or later — parked or folded: the writer said the row again, and the old reading is the copy's own, never a write missing. A new name's reading from before says nothing of it, and the new name's own park stays until it folds.#[test]fn a_park_under_an_authors_old_name_ends_when_the_new_name_says_its_row_again() {let (was, is) = (format!("{RETIRED_AUTHOR_PREFIX}object"), "object");let was = was.as_str(); assert_eq!(now_named(was), Some(is));let db = seeded();let row = "9999ffff-0000-4000-8000-00000000000e";let alone = "9999ffff-0000-4000-8000-00000000000f";let refused = |op: CottonOp| { park(&db, &op, Direction::Pull, Class::Conflict, "refused by the shape", NOW).expect("parks"); }; refused(served_by(was, row, 1_000, "op-1-old-name")); refused(served_by(was, alone, 1_000, "op-2-old-name-alone")); refused(served_by(is, row, 900, "op-3-new-name-before")); sweep_parked(&db, PARK_SWEEP_OPS, LATER).expect("a sweep"); assert_eq!(parked_ids(&db).len(), 3, "a new name's reading from before says nothing of it"); refused(served_by(is, row, 1_000, "op-4-new-name")); shape_changed(&db).expect("due again"); sweep_parked(&db, PARK_SWEEP_OPS, LATEST).expect("a sweep");// The new name's earlier reading is said again by its later one (the// fold's own last-writer-wins, `superseded_by`); the old name's goes// with it; the row the new name never said again keeps its park. assert_eq!(parked_ids(&db), vec!["op-2-old-name-alone", "op-4-new-name"]);}/// RULE: A receipt of the new name folded for the row ends the old name's park as surely as a parked one.#[test]fn a_folded_receipt_under_the_new_name_ends_the_old_names_park() {let (was, is) = (format!("{RETIRED_AUTHOR_PREFIX}object"), "object");let was = was.as_str();let db = seeded();let row = "9999ffff-0000-4000-8000-000000000010"; park(&db, &served_by(was, row, 1_000, "op-old-name"), Direction::Pull, Class::Conflict, "refused by the shape", NOW).expect("parks");let change = Change::create( CHILD_TABLE, row, obj(json!({"id": row, "name": "served", "kind": "bank", "subtype": "bank", "currency": "INR","workspace_id": WS, "created_at": NOW, "updated_at": NOW, })), );let said_again = SCRATCH.with(|scratch| {crate::wire::op_of_change(scratch, &change, &format!("{:013}:0002:{is}", 2_000), is, &crate::fixtures::fixture_actor(), "op-new-name".to_string()) .expect("a receipt") }); take(&db, &page(vec![said_again]), LATER); assert_eq!(title_of(&db, row).as_deref(), Some("served"), "the new name's reading folded"); assert!(parked_ids(&db).is_empty(), "{:?}", parked_ids(&db));}// ── what a page of refusals costs ───────────────────────────────────────────/// `n` parent-less money accounts, each naming a person this file has not got.fn orphans(n: usize) -> Vec<CottonOp> { (0..n).map(|i| child(&format!("acct-{i:06}"), "a", 10_000 + i as i64)).collect()}/// Fold `response` as [`take`] does, answering how long it took and in how/// many folds (`held::tally`).fn timed(db: &Driver, response: &ExchangeResponse) -> (std::time::Duration, usize) {let tally = crate::held::tally();let started = std::time::Instant::now(); take(db, response, NOW);let took = started.elapsed(); (took, tally.done().folds)}/// RULE (3 Nov 2026): a page whose rows all wait for a parent folds ONCE —/// its own refusals are not offered again by the page that just refused them/// — and costs about what the same page costs when its parents are held.////// Measured on one Mac (debug, alone): 2.9 s a page before, the fold and the/// retry that re-offered every refusal; 1.3 s once the retry offers none, and/// 4.7 s beside the other `rejected` tests running in parallel. The budget was/// eight seconds of wall clock, which the Linux box that runs rust-main (a/// slower debug build, shared with every crate's suite) passed or missed by/// its load: 11.6 s there for the same code that measured within it on a quiet/// box. So the budget is the page's cost beside the same 5,000 rows landing/// with their parents held, timed on the same machine in the same run: a/// refusal that is offered again, or folded once per row, costs many times/// that. The fold count is still the guard that fails first.#[test]fn a_page_of_five_thousand_refusals_folds_once_and_inside_its_budget() {let held = seeded(); take(&held, &page((0..5_000).map(|i| parent(&format!("acct-{i:06}"), "p", 1_000 + i as i64)).collect()), NOW);let (landing, _) = timed(&held, &page(orphans(5_000))); assert_eq!(count(&held, "SELECT COUNT(*) AS c FROM _parked"), 0, "with their parents held, the rows land");let db = seeded();let (took, folds) = timed(&db, &page(orphans(5_000))); eprintln!("a page of 5,000 refusals: {:.2}s in {folds} fold(s); landing them: {:.2}s", took.as_secs_f64(), landing.as_secs_f64()); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM _parked WHERE direction = 'pull'"), 5_000); assert_eq!(folds, 1, "the page's own refusals were offered again"); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM _parked WHERE tries > 0"), 0, "nothing was retried"); assert!(took < landing * 3, "a page of 5,000 refusals took {took:?}, landing them {landing:?}");}/// RULE (3 Nov 2026): the page that brings the parents lands every child/// parked for them in ONE fold, not one fold per child — a fold's cost is/// per batch (on a phone the money engine works the whole book out after/// each), so 8,870 folds of one money row each took 2,680 s.#[test]fn the_page_that_brings_the_parents_lands_every_waiting_child_in_one_fold() {let db = seeded();for chunk in orphans(10_000).chunks(5_000) { take(&db, &page(chunk.to_vec()), NOW); }let parents: Vec<CottonOp> = (0..10_000).map(|i| parent(&format!("acct-{i:06}"), "p", 1_000 + i as i64)).collect();let (took, folds) = timed(&db, &page(parents)); eprintln!("the parents' page healing 10,000 parks: {:.2}s in {folds} fold(s)", took.as_secs_f64()); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM _parked"), 0, "every child landed with its parent"); assert_eq!(count(&db, "SELECT COUNT(*) AS c FROM cotton_money_accounts"), 10_000); assert_eq!(folds, 2, "the page, then every child it unblocked in one fold");}