//! The personal object as the phone's peer, against a scripted object and a //! real replica: what a pull folds, what a write posts, and what a pass does //! not hand over twice. use std::sync::{Arc, Mutex}; use serde_json::{json, Value}; use super::*; use crate::sync::cycle::{run_cycle, run_cycle_paged}; use crate::transport::RefusalAware as _; use crate::test_support::{open_test_replica, queue_one_change, WORKSPACE}; use crate::transport::scripted::{Reply, ScriptedExchange}; const NOW: &str = "2026-10-25T10:00:00.000Z"; fn transport(exchange: &Arc, replica: &crate::Replica) -> ObjectTransport { ObjectTransport::new( ObjectAddress::named("https://cotton.example.com", "asha").expect("an address"), Arc::clone(exchange) as Arc, "synthetic-credential".into(), // Todos are sealed (e2e rulings R3); these cases write them as an open table. Arc::new(ObjectTables::personal().opening(&["todo"])), replica.path.clone(), vec![("message".into(), 90)], ) } fn page(rows: Value, version: i64, next: Option<&str>) -> Reply { let mut body = json!({"version": version, "rows": rows, "server_time": NOW}); if let Some(next) = next { body["next"] = json!(next); } Reply::ok(&body.to_string()) } /// A last page of a pass that carried `again`'s tables whole, as the Worker says it. fn again_page(rows: Value, version: i64, again: &[&str]) -> Reply { Reply::ok(&json!({"version": version, "rows": rows, "server_time": NOW, "again": again}).to_string()) } /// RULE (21 Nov 2026): an object that does not say it carried the tables again (a Worker before `again=`) gets the pull from the start, as before: nothing the cursor went past is skipped. #[test] fn a_copy_owed_a_table_pulls_from_the_start_from_an_object_that_does_not_carry_it_again() { let (_dir, _layout, replica) = open_test_replica(); let earlier = ScriptedExchange::new([page(json!([todo("t-1", "Ring the bank", 3), subscription("s-1", "Invented Pro", 4)]), 5, None)]); let mut object = transport(&earlier, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the earlier build's pass"); let now = ScriptedExchange::new([ page(json!([]), 5, None), served_with_tables(json!([served_subscription()]), "e1"), page(json!([]), 6, None), page(json!([todo("t-1", "Ring the bank", 3), subscription("s-1", "Invented Pro", 4)]), 6, None), ]); let held = HeldDefinitions::new(); let mut object = transport(&now, &replica).taking_definitions(Arc::clone(&held)); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass"); assert_eq!(now.nth(2).path, "/v1/sync?since=5&limit=5000&window=message:90&again=subscription"); assert_eq!(now.nth(3).path, "/v1/sync?since=0&limit=5000&window=message:90", "not carried: the pull from the start"); assert_eq!(subscription_name(&replica, "s-1").as_deref(), Some("Invented Pro")); assert_eq!(cursor(&replica).as_deref(), Some("w0001v0000000000000006")); } fn todo(id: &str, title: &str, version: i64) -> Value { json!({ "table": "todo", "id": id, "version": version, "owner": null, "data": {"title": title, "status": "open", "priority": 0}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }) } fn todo_title(replica: &crate::Replica, id: &str) -> Option { replica .driver .get("SELECT title FROM cotton_todos WHERE id = ?", &[rusqlite::types::Value::Text(id.into())]) .expect("a read") .and_then(|row| row.text("title").map(str::to_string)) } fn cursor(replica: &crate::Replica) -> Option { cotton_store::cursors::read_cursors(&replica.driver).expect("the cursors").get(CURSOR_KEY).cloned() } fn body(seen: &crate::transport::scripted::Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body") } #[test] fn the_shipped_map_reads_against_this_builds_store() { let tables = ObjectTables::personal(); let todo = tables.object("todo").expect("todos come"); assert_eq!(todo.store, "cotton_todos"); assert!(tables.ours("cotton_msg_messages").is_some_and(|t| t.table == "message")); let member = tables.object("group_member").expect("a list's members come"); assert!(member.columns.iter().any(|(object, ours, _)| object == "group" && ours == "group_id"), "an object column reads its _id column here"); // RULE (owner, 11 Nov 2026): Cotton Keys holds the passwords. A secret is the phone's, kept in // cotton_secrets with its value sealed v2 on the owner's devices; its hint (four characters of the // value) stays on the device that wrote it and never reaches the object. let secret = tables.object("secret").expect("a secret comes"); assert_eq!(secret.store, "cotton_secrets"); for column in ["value_enc", "vmk_version", "kind", "site", "username"] { assert!(secret.places(column), "{column} travels"); } assert!(!secret.places("hint"), "a hint never reaches the object"); assert!(tables.object("device").is_none(), "a relay registration is not this phone's"); } #[test] fn a_named_host_takes_no_prefix_and_a_workers_dev_one_names_the_database() { let named = ObjectAddress::named("https://cotton.example.com", "asha").expect("an address"); assert_eq!(named.url(routes::SYNC), "https://cotton.example.com/v1/sync"); let shared = ObjectAddress::named("https://cotton-business.example.workers.dev", "asha").expect("an address"); assert_eq!(shared.url(routes::SYNC), "https://cotton-business.example.workers.dev/b/asha/v1/sync"); } #[test] fn a_pull_folds_the_objects_rows_into_the_typed_tables_and_holds_its_version() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([page(json!([todo("t-1", "Ring the bank", 7)]), 7, None)]); let mut object = transport(&exchange, &replica); let report = run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Ring the bank")); assert!(report.tables.iter().any(|t| t == "cotton_todos"), "the screen is told: {:?}", report.tables); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000007")); let asked = exchange.only(); assert_eq!(asked.path, "/v1/sync?since=0&limit=5000&window=message:90"); assert_eq!(asked.header("authorization"), Some("Bearer synthetic-credential")); } #[test] fn a_pull_pages_until_the_object_has_no_more_and_a_tombstone_takes_the_row_away() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([todo("t-1", "One", 4)]), 0, Some("page-two")), page(json!([todo("t-2", "Two", 4)]), 4, None), page(json!([{"table": "todo", "id": "t-1", "version": 5, "deleted": true, "data": {}, "updated_at": "2026-10-21T09:00:00.000Z"}]), 5, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(exchange.nth(1).path, "/v1/sync?cursor=page-two"); assert_eq!(todo_title(&replica, "t-2").as_deref(), Some("Two")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000004")); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the next pass"); assert_eq!(exchange.nth(2).path, "/v1/sync?since=4&limit=5000&window=message:90"); assert_eq!(todo_title(&replica, "t-1"), None, "the object deleted it"); } /// RULE (owner, 22 Nov 2026): a whole table the object erased for good is /// named in `dropped` on the first page of a pass from before it; the copy /// drops every row it holds of it, and a row the object wrote since stands. A /// table this copy places nowhere is passed by. #[test] fn a_table_the_object_erased_is_dropped_from_the_copy_and_a_row_written_since_stands() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([todo("t-1", "One", 3), todo("t-2", "Two", 4)]), 4, None), Reply::ok( &json!({ "version": 9, "server_time": NOW, "dropped": {"todo": "2026-10-24T09:00:00.000Z", "news_story": "2026-10-24T09:00:00.000Z", "no_such_table": "2026-10-24T09:00:00.000Z"}, "rows": [{ "table": "todo", "id": "t-3", "version": 9, "owner": null, "data": {"title": "Written since", "status": "open", "priority": 0}, "created_at": "2026-10-25T09:00:00.000Z", "updated_at": "2026-10-25T09:00:00.000Z", }], }) .to_string(), ), page(json!([]), 9, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("One")); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass after the erase"); assert_eq!(todo_title(&replica, "t-1"), None, "the erased table's rows go"); assert_eq!(todo_title(&replica, "t-2"), None); assert_eq!(todo_title(&replica, "t-3").as_deref(), Some("Written since")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000009")); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass after"); assert_eq!(todo_title(&replica, "t-3").as_deref(), Some("Written since"), "a later pass, told nothing, drops nothing"); } #[test] fn a_page_cursor_moves_forward_as_text_whatever_the_objects_tokens_sort_like() { // The object's page token is opaque (base64 JSON): "zzz" then "aaa" is // a later page whose token sorts below the one before it, and the // file's forward-only cursor must still take it. let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([todo("t-1", "One", 4)]), 0, Some("zzz")), page(json!([todo("t-2", "Two", 4)]), 0, Some("aaa")), page(json!([todo("t-3", "Three", 4)]), 4, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(exchange.nth(1).path, "/v1/sync?cursor=zzz"); assert_eq!(exchange.nth(2).path, "/v1/sync?cursor=aaa"); assert_eq!(todo_title(&replica, "t-3").as_deref(), Some("Three")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000004")); } #[test] fn a_page_cursor_carries_its_ordinal_and_the_token_comes_back_out() { assert_eq!(page_cursor(0, 0, 1, "zzz"), "v0000000000000000.00000001.zzz"); assert!(page_cursor(0, 0, 2, "aaa") > page_cursor(0, 0, 1, "zzz"), "the next page sorts above the one before it"); assert!(String::from("v0000000000000004") > page_cursor(0, 0, 2, "aaa"), "the pass's end sorts above its pages"); assert_eq!(read_cursor("v0000000000000000.00000002.aaa"), (0, 0, Some((2, "aaa")))); assert_eq!(read_cursor("v0000000000000004"), (0, 4, None)); // A pull again from the start sorts above every cursor of the pulls before it. assert_eq!(page_cursor(1, 0, 1, "aaa"), "w0001v0000000000000000.00000001.aaa"); assert!(page_cursor(1, 0, 1, "aaa") > String::from("v0000000000010703")); assert!(version_cursor(1, 3) > page_cursor(1, 0, 1, "aaa")); assert!(version_cursor(2, 0) > version_cursor(1, 10703)); assert_eq!(read_cursor("w0001v0000000000000000.00000002.aaa"), (1, 0, Some((2, "aaa")))); assert_eq!(read_cursor("w0002v0000000000000004"), (2, 4, None)); } /// RULE (seen on the dev server, 22 Nov 2026: 100,121 invented emails refused, "email.thread_id names no email_thread"): /// a write that made a row before the row it links to queues them in that order, and the object refuses a row whose /// link names nothing it holds. When the row it names is still queued here, that row goes first, as it stands here, and /// the refused one is posted again: nothing is parked, and the linked row's own write goes without a second post. #[test] fn a_row_refused_for_a_link_still_queued_here_sends_that_row_first() { let (_dir, _layout, replica) = open_test_replica(); let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(7))); let patch = |pairs: Value| pairs.as_object().cloned().expect("a patch"); let at = "2026-09-08T10:00:00.000Z"; cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "invent_mail".to_string(), history: cotton_store::mint::History::None, // The email first, then its conversation: the order the queue goes up in. changes: vec![ cotton_store::mint::Change::create("cotton_emails", "e-1", patch(json!({"workspace_id": WORKSPACE, "thread_id": "th-1", "external_id": "", "subject": "The lake", "from_email": "ada@invented.example", "sent_at": at, "created_at": at}))), cotton_store::mint::Change::create("cotton_email_threads", "th-1", patch(json!({"workspace_id": WORKSPACE, "external_key": "invented:th-1", "subject": "The lake", "email_count": 1, "created_at": at, "updated_at": at}))), ], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_760_000_000_000, &mut ids).expect("the replica's clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("a queued write"); let exchange = ScriptedExchange::new([ Reply::new(400, br#"{"code":"bad_link","message":"email.thread_id names no email_thread"}"#.to_vec()), Reply::ok(r#"{"version": 8, "changed": []}"#), Reply::ok(r#"{"version": 9, "changed": []}"#), page(json!([]), 9, None), page(json!([]), 9, None), ]); let mut object = ObjectTransport::new( ObjectAddress::named("https://cotton.example.com", "asha").expect("an address"), Arc::clone(&exchange) as Arc, "synthetic-credential".into(), Arc::new(ObjectTables::personal().opening(&["email", "email_thread"])), replica.path.clone(), vec![("message".into(), 90)], ); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let acts: Vec<(String, String)> = exchange.seen().iter().filter(|seen| seen.path == "/v1/act").map(|seen| { let sent = body(seen); (sent["act"].as_str().unwrap_or("").to_string(), sent["args"]["table"].as_str().unwrap_or("").to_string()) }).collect(); let pair = |act: &str, table: &str| (act.to_string(), table.to_string()); assert_eq!(acts, vec![pair("create", "email"), pair("create", "email_thread"), pair("create", "email")], "the conversation went first, the email again after it, and the conversation's own write without another post"); assert_eq!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"), 0, "both taken"); let parked = replica.driver.get("SELECT COUNT(*) AS n FROM _parked", &[]).expect("a read").and_then(|row| row.int("n")); assert_eq!(parked, Some(0), "nothing parked"); } /// RULE: a row refused for a link to a row this copy has not queued (one it never held, or one long since sent) is /// refused for good as before: posted once, parked, nothing else sent. #[test] fn a_row_refused_for_a_link_not_queued_here_is_parked_as_before() { let (_dir, _layout, replica) = open_test_replica(); let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(9))); let at = "2026-09-08T10:00:00.000Z"; let patch = |pairs: Value| pairs.as_object().cloned().expect("a patch"); let mut write = |table: &str, id: &str, data: Value| { cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "invent_mail".to_string(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::create(table, id, patch(data))], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_760_000_000_000, &mut ids).expect("the replica's clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("a queued write"); }; // The conversation was sent long ago: held here, queued no more. write("cotton_email_threads", "th-9", json!({"workspace_id": WORKSPACE, "external_key": "invented:th-9", "subject": "The lake", "email_count": 1, "created_at": at, "updated_at": at})); replica.driver.run("DELETE FROM _outbox", &[]).expect("the conversation sent"); write("cotton_emails", "e-9", json!({"workspace_id": WORKSPACE, "thread_id": "th-9", "external_id": "", "subject": "The lake", "from_email": "ada@invented.example", "sent_at": at, "created_at": at})); let exchange = ScriptedExchange::new([ Reply::new(400, br#"{"code":"bad_link","message":"email.thread_id names no email_thread"}"#.to_vec()), page(json!([]), 9, None), page(json!([]), 9, None), ]); let mut object = ObjectTransport::new( ObjectAddress::named("https://cotton.example.com", "asha").expect("an address"), Arc::clone(&exchange) as Arc, "synthetic-credential".into(), Arc::new(ObjectTables::personal().opening(&["email", "email_thread"])), replica.path.clone(), vec![("message".into(), 90)], ); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(exchange.seen().iter().filter(|seen| seen.path == "/v1/act").count(), 1, "posted once"); let parked = replica.driver.get("SELECT COUNT(*) AS n FROM _parked", &[]).expect("a read").and_then(|row| row.int("n")); assert_eq!(parked, Some(1), "parked, as a refusal for good is"); } #[test] fn a_write_here_is_posted_as_the_objects_create_under_its_own_id_once() { let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "Buy milk"); let exchange = ScriptedExchange::new([ Reply::ok(r#"{"version": 8, "changed": []}"#), page(json!([]), 8, None), page(json!([]), 8, None), ]); let mut object = transport(&exchange, &replica); let report = run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let act = exchange.nth(0); assert_eq!(act.path, "/v1/act"); let sent = body(&act); assert_eq!(sent["act"], "create"); assert_eq!(sent["args"]["table"], "todo"); assert_eq!(sent["args"]["id"], "todo-Buy milk"); assert_eq!(sent["args"]["data"]["title"], "Buy milk"); assert_eq!(sent["args"]["data"]["status"], "open"); assert!(sent["args"]["data"].get("workspace_id").is_none(), "the object keeps no workspace column"); assert_eq!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"), 0, "taken, so gone from the queue"); assert!(report.pushed >= 1); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the next pass"); assert_eq!(exchange.calls(), 3, "the next pass hands nothing over again: {:?}", exchange.seen().iter().map(|s| s.path.clone()).collect::>()); } #[test] fn a_create_the_object_already_holds_is_sent_again_as_the_row_now() { let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "Twice"); let exchange = ScriptedExchange::new([ Reply::json(409, r#"{"code": "duplicate_id", "message": "todo already holds todo-Twice"}"#), Reply::ok(r#"{"version": 9, "changed": []}"#), page(json!([]), 9, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(body(&exchange.nth(1))["act"], "update"); assert_eq!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"), 0); } #[test] fn a_write_the_object_refuses_is_parked_with_its_sentence() { let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "Refused"); let exchange = ScriptedExchange::new([ Reply::json(400, r#"{"code": "missing_required", "message": "todo needs title"}"#), page(json!([]), 9, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.iter().any(|row| row.text("reason") == Some("todo needs title")), "{parked:?}"); } #[test] fn an_unreachable_object_fails_the_pass_and_keeps_the_write_queued() { let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "Offline"); let exchange = ScriptedExchange::new([]); let mut object = transport(&exchange, &replica); assert!(run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).is_err()); assert!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox") > 0, "nothing is lost"); } #[test] fn the_first_copy_is_an_empty_file_of_the_objects_database() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("client").join("db").join("replica.db"); make_copy(&path, WORKSPACE, "owner-1", "device:phone", NOW, &Default::default(), Default::default()).expect("a copy"); let db = cotton_store::driver::Driver::open(&path).expect("it opens"); let meta = cotton_store::meta::read_meta(&db).expect("its meta").expect("a meta row"); assert_eq!(meta.workspace_id, WORKSPACE); let drawn = db.get("SELECT COUNT(*) AS n FROM cotton_board_definitions", &[]).expect("a read").and_then(|row| row.int("n")).unwrap_or(0); assert!(drawn > 0, "the copy is born with the shell its decks draw from"); make_copy(&path, "another", "owner-1", "device:phone", NOW, &Default::default(), Default::default()).expect("a held copy is kept"); } /// A first sign-in that asks for its copy twice at once (Pat's You page said "this phone's copy could /// not be made (…replica.db (No such file or directory))"): both are answered with the one copy, neither fails. #[test] fn two_makes_at_once_both_answer_the_one_copy() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("client").join("db").join("replica.db"); let results: Vec> = std::thread::scope(|scope| { let makes: Vec<_> = (0..4).map(|_| scope.spawn(|| make_copy(&path, WORKSPACE, "owner-1", "device:phone", NOW, &Default::default(), Default::default()))).collect(); makes.into_iter().map(|m| m.join().expect("a make")).collect() }); for result in results { assert_eq!(result, Ok(())); } let db = cotton_store::driver::Driver::open(&path).expect("it opens"); assert_eq!(cotton_store::meta::read_meta(&db).expect("its meta").expect("a meta row").workspace_id, WORKSPACE); assert!(!dir.path().join("client").join("db").join("replica.db.making").exists()); } /// RULE (copy-installer-store, 8 Nov 2026): a copy is made under a side name and moved to its path only whole, its log folded in, so a process killed part way leaves nothing at the path (a file there is kept for good) — which is what lets a birth write with no fsync; a side file a killed make left is made again. #[test] fn a_copy_is_made_beside_its_path_and_moved_in_whole() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("replica.db"); let side = dir.path().join("replica.db.making"); std::fs::write(&side, b"a make killed part way").expect("a stale side file"); std::fs::write(dir.path().join("replica.db.making-wal"), b"its log").expect("a stale log"); make_copy(&path, WORKSPACE, "owner-1", "device:phone", NOW, &Default::default(), Default::default()).expect("a copy"); for left in ["replica.db.making", "replica.db.making-wal", "replica.db.making-shm"] { assert!(!dir.path().join(left).exists(), "{left} is gone"); } let log = dir.path().join("replica.db-wal"); assert!(!log.exists() || std::fs::metadata(&log).expect("the log").len() == 0, "the log is folded into the file"); let db = cotton_store::driver::Driver::open(&path).expect("it opens"); assert_eq!(cotton_store::meta::read_meta(&db).expect("its meta").expect("a meta row").workspace_id, WORKSPACE); } #[test] fn a_copy_that_has_written_folds_the_objects_rows_as_an_author_it_knows() { let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "Written here first"); assert!(cotton_store::fact_hooks::this_file_holds_its_authors_fact(&replica.driver).expect("a read"), "the copy's own author is minted"); let exchange = ScriptedExchange::new([ Reply::ok(r#"{"version": 8, "changed": []}"#), page(json!([todo("t-9", "From the object", 8)]), 8, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(todo_title(&replica, "t-9").as_deref(), Some("From the object")); } // ── what only the phone knows of its passes ──────────────────────────────── const START_MS: i64 = 1_792_900_000_000; /// A page as the object answers it with the pass's standing and the phone's row. fn standing(rows: Value, version: i64, next: Option<&str>, device: Value, total: i64, remaining: i64) -> Reply { let done = if next.is_some() { total - remaining } else { total }; let mut body = json!({"version": version, "rows": rows, "server_time": NOW, "total": total, "remaining": remaining, "done": done, "device": device}); if let Some(next) = next { body["next"] = json!(next); } Reply::ok(&body.to_string()) } fn act_taken() -> Reply { Reply::ok(r#"{"version": 99, "changed": []}"#) } /// A progress on a clock the test moves. fn progress_at(now: &Arc>) -> Arc { let clock = Arc::clone(now); SyncProgress::new(move || *clock.lock().expect("the clock")) } fn reporting(exchange: &Arc, replica: &crate::Replica, progress: &Arc) -> ObjectTransport { transport(exchange, replica).reporting_to(Arc::clone(progress)) } fn reporting_state(exchange: &Arc, replica: &crate::Replica, progress: &Arc, state: Value) -> ObjectTransport { reporting(exchange, replica, progress).reporting_state_to(Arc::new(move || Some(state.clone()))) } /// The update an act posted on the phone's row: its id and data. fn row_update(seen: &crate::transport::scripted::Seen) -> (String, Value) { assert_eq!(seen.path, "/v1/act"); let sent = body(seen); assert_eq!(sent["act"], "update"); assert_eq!(sent["args"]["table"], "device"); (sent["args"]["id"].as_str().expect("an id").to_string(), sent["args"]["data"].clone()) } #[test] fn the_bytes_a_pass_receives_add_up_on_the_phones_row_and_a_poll_writes_none() { let (_dir, _layout, replica) = open_test_replica(); let first = standing(json!([todo("t-1", "One", 4)]), 0, Some("page-two"), json!("dev-1"), 2, 1); let second = standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 2, 0); let (one, two) = (first.body.len() as u64, second.body.len() as u64); let exchange = ScriptedExchange::new([first, act_taken(), second, act_taken(), standing(json!([]), 4, None, json!("dev-1"), 2, 0)]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); run_cycle(&replica.driver, &mut reporting_state(&exchange, &replica, &progress, json!({"build":"328","sha":"synthetic328","schema":137})), WORKSPACE, NOW).expect("a pass"); let (id, data) = row_update(&exchange.nth(1)); assert_eq!(id, "dev-1", "the row the object named"); assert_eq!(data, json!({"sync_bytes": one}), "the first page's bytes"); let (_, data) = row_update(&exchange.nth(3)); assert_eq!(data, json!({"sync_bytes": one + two, "reported_state":{"build":"328","sha":"synthetic328","schema":137,"last_exchange_at":NOW,"last_answer":"ok"}}), "the pass's end says the whole of it and the running build"); let state = progress.state(); assert_eq!((state.pass_bytes, state.pages, state.total, state.remaining), (one + two, 2, Some(2), Some(0))); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("a poll"); assert_eq!(exchange.calls(), 5, "a pass of one page writes nothing on the row"); assert!(progress.state().caught_up); } /// RULE (owner, 22 Nov 2026: warn before the database is full): a pass's last /// page that says the object's `room` (80% of its cap or past it) is held on /// the pass state for the Storage line; a later pass's last page without it /// clears it. #[test] fn a_last_page_that_says_the_database_is_filling_is_held_until_one_says_nothing() { let (_dir, _layout, replica) = open_test_replica(); let mut full = standing(json!([]), 0, None, json!(null), 0, 0); let mut body: Value = serde_json::from_slice(&full.body).expect("json"); body["room"] = json!({"bytes": 8_000_000_000u64, "cap": 9_500_000_000u64, "used": 0.8421}); full.body = body.to_string().into_bytes(); let exchange = ScriptedExchange::new([full, standing(json!([]), 0, None, json!(null), 0, 0)]); let progress = progress_at(&Arc::new(Mutex::new(START_MS))); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("a pass"); assert_eq!(progress.state().room, Some(crate::transport::object::Room { bytes: 8_000_000_000, cap: 9_500_000_000, used: 0.8421 })); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("a second pass"); assert_eq!(progress.state().room, None, "a last page without room is room enough"); } #[test] fn each_launch_posts_its_running_build_sha_and_schema_when_a_pass_completes() { let (_dir, _layout, replica) = open_test_replica(); let first = json!({"build":"328","sha":"synthetic328","schema":137}); let first_exchange = ScriptedExchange::new([standing(json!([]), 0, None, json!("synthetic-device"), 0, 0), act_taken()]); let first_progress = progress_at(&Arc::new(Mutex::new(START_MS))); run_cycle(&replica.driver, &mut reporting_state(&first_exchange, &replica, &first_progress, first), WORKSPACE, NOW).expect("first launch completes"); let (id, data) = row_update(&first_exchange.nth(1)); assert_eq!(id, "synthetic-device"); assert_eq!(data["reported_state"], json!({"build":"328","sha":"synthetic328","schema":137,"last_exchange_at":NOW,"last_answer":"ok"}), "the page is itself an answer: a launch's first report says its time and ok"); let second = json!({"build":"329","sha":"synthetic329","schema":138}); let second_exchange = ScriptedExchange::new([standing(json!([]), 0, None, json!("synthetic-device"), 0, 0), act_taken()]); let second_progress = progress_at(&Arc::new(Mutex::new(START_MS))); run_cycle(&replica.driver, &mut reporting_state(&second_exchange, &replica, &second_progress, second), WORKSPACE, NOW).expect("second launch completes"); let (id, data) = row_update(&second_exchange.nth(1)); assert_eq!(id, "synthetic-device"); assert_eq!(data["reported_state"], json!({"build":"329","sha":"synthetic329","schema":138,"last_exchange_at":NOW,"last_answer":"ok"}), "the page is itself an answer: a launch's first report says its time and ok"); } #[test] fn the_device_records_sync_columns_say_what_the_answers_said_and_behind_holds_until_the_pass_ends() { let (_dir, _layout, replica) = open_test_replica(); let first = standing(json!([todo("t-1", "One", 4)]), 0, Some("page-two"), json!("dev-1"), 2, 1); let one = first.body.len() as u64; let exchange = ScriptedExchange::new([first, act_taken(), Reply::json(500, r#"{"code": "internal", "message": "the object failed"}"#)]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); assert!(!progress.state().behind(), "before any page this launch the phone does not know"); assert!(run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).is_err(), "the second page fails"); let state = progress.state(); assert!(state.behind(), "a pass under way is behind"); assert_eq!( Value::Object(state.columns()), json!({"synced_at": NOW, "sync_rows_total": 2, "sync_rows_done": 1, "sync_bytes": one, "caught_up": false, "stalled_at": null, "stalled_why": null}), ); let exchange = ScriptedExchange::new([standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 2, 0), act_taken()]); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the page comes"); let state = progress.state(); assert!(!state.behind(), "the pass that reaches its end is caught up"); assert_eq!(state.columns()["sync_rows_done"], json!(2)); assert_eq!(state.columns()["caught_up"], json!(true)); } /// `reply` with each table's rows in the pass and how many have come, as the object says them. fn with_tables(reply: Reply, tables: Value) -> Reply { let mut body: Value = serde_json::from_slice(&reply.body).expect("an answer"); body["tables"] = tables; Reply::ok(&body.to_string()) } /// RULE (owner, 2 Nov 2026): the deck's counter says while a tool's rows /// move what they are doing — "347 of 950 todos arriving", "25 todos /// sending" — and the plain count once the tool is settled. The phone holds /// each table's figures as the last page said them, by the object's name, /// and tells its queue of writes by the same names. #[test] fn each_table_says_its_rows_arriving_and_its_writes_sending_by_the_objects_name_until_it_is_settled() { let (_dir, _layout, replica) = open_test_replica(); let first = with_tables( standing(json!([todo("t-1", "One", 4)]), 0, Some("page-two"), json!("dev-1"), 5, 1), json!({"todo": {"rows": 2, "done": 1}, "person": {"rows": 3, "done": 3}}), ); let exchange = ScriptedExchange::new([first, act_taken(), Reply::json(500, r#"{"code": "internal", "message": "the object failed"}"#)]); let progress = progress_at(&Arc::new(Mutex::new(START_MS))); assert!(progress.state().moving(&[]).is_empty(), "before any page nothing is moving"); assert!(run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).is_err(), "the second page fails"); let state = progress.state(); let queued = [("cotton_todos".to_string(), 25), ("cotton_people".to_string(), 0), ("cotton_nowhere".to_string(), 4)]; assert_eq!( Value::Object(state.moving(&queued)), json!({"todo": {"arriving": 2, "arrived": 1, "sending": 25}}), "people came whole; a table the map does not hold is not told", ); // SYNC SEEN (`sync.row`): a row of a table still arriving may have a newer copy on its way, by either name. assert_eq!(state.arriving("todo"), Some(TablePass { rows: 2, done: 1 })); assert_eq!(state.arriving("cotton_todos"), Some(TablePass { rows: 2, done: 1 }), "this phone's own name for it"); assert_eq!(state.arriving("person"), None, "people came whole"); let last = with_tables(standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 5, 0), json!({"todo": {"rows": 2, "done": 2}, "person": {"rows": 3, "done": 3}})); let exchange = ScriptedExchange::new([last, act_taken()]); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the last page comes"); let state = progress.state(); assert_eq!(state.tables["todo"], TablePass { rows: 2, done: 2 }); assert!(state.moving(&[]).is_empty(), "every table settled"); assert_eq!(state.arriving("todo"), None, "settled: no newer copy on its way"); assert_eq!(Value::Object(state.moving(&[("cotton_people".to_string(), 1)])), json!({"person": {"sending": 1}})); } /// A phone that has not reached the object this launch still tells its /// queue by the object's names: the map is held from the transport's making. #[test] fn a_phone_that_has_not_reached_the_object_still_says_its_writes_sending() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([]); let progress = progress_at(&Arc::new(Mutex::new(START_MS))); let _transport = reporting(&exchange, &replica, &progress); assert_eq!(Value::Object(progress.state().moving(&[("cotton_todos".to_string(), 3)])), json!({"todo": {"sending": 3}})); } /// RULE (owner's phone, 2 Nov 2026: the same page asked every 30 s and nothing said why): a pass the object refuses says so on the phone's row at once — `stalled_at` when it first failed and `stalled_why` the refusal's sentence — a second failure for the same reason writes nothing more, and the next page that lands clears both. #[test] fn a_pass_the_object_refuses_says_why_on_the_phones_row_and_the_next_page_clears_it() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ standing(json!([todo("t-1", "One", 4)]), 0, Some("page-two"), json!("dev-1"), 2, 1), act_taken(), Reply::json(500, r#"{"code": "internal", "message": "the object failed"}"#), act_taken(), Reply::json(500, r#"{"code": "internal", "message": "the object failed"}"#), standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 2, 0), act_taken(), ]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); assert!(run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).is_err(), "the second page fails"); let (id, data) = row_update(&exchange.nth(3)); assert_eq!(id, "dev-1"); let stalled = chrono::DateTime::from_timestamp_millis(START_MS).expect("an instant").to_rfc3339_opts(chrono::SecondsFormat::Millis, true); assert_eq!(data["stalled_at"], json!(stalled), "{data}"); assert!(data["stalled_why"].as_str().is_some_and(|why| why.contains("the object failed")), "{data}"); assert_eq!(progress.state().stalled_at.as_deref(), Some(stalled.as_str())); assert!(!progress.state().caught_up, "the pass is under way"); assert_eq!(progress.stuck(), None, "a refusal is the object's, never the copy's"); *now.lock().expect("the clock") += STALL_AFTER_MS + 1_000; assert!(run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).is_err()); assert_eq!(exchange.calls(), 5, "the same failure again writes nothing: the row says it"); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the page comes"); let (_, data) = row_update(&exchange.nth(6)); assert_eq!((data["stalled_at"].clone(), data["stalled_why"].clone()), (Value::Null, Value::Null), "the page that lands clears the stall: {data}"); assert!(data["sync_bytes"].as_u64().is_some_and(|bytes| bytes > 0)); let state = progress.state(); assert_eq!((state.stalled_at, state.stalled_why), (None, None)); assert!(state.caught_up, "a pass whose last page has no next leaves this phone caught up"); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000004")); } /// The kit's money table with a column this copy's table lacks, which a /// pass lent no copy cannot take ([`ObjectTransport::hold_served`]): a /// definitions answer this pass cannot take. fn unreadable_definitions(etag: &str) -> Reply { let mut more = served_transaction(); more["columns"].as_array_mut().expect("columns").push(json!({"key": "invented_note", "name": "Invented note", "type": "text"})); served_with_tables(json!([more]), etag) } /// RULE (owner's phone, 2 Nov 2026: the page and the definitions came, the pass failed inside the pull and nothing anywhere said why): a page this copy cannot take — a column the definitions it brings name that the pass cannot add — fails the pass, and the next request on the exchange writes `stalled_why` and `stalled_at` on the phone's row, the row known from that very page; the same failure on the same page three passes running is the copy stuck (`SyncProgress::stuck`), and a page that lands clears the row and the run. #[test] fn a_page_the_copy_cannot_take_says_why_on_the_phones_row_and_three_running_are_the_copy_stuck() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ standing(json!([todo("t-1", "One", 4)]), 0, Some("page-two"), json!("dev-1"), 2, 1), served_with_tables(json!([]), "e1"), act_taken(), standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 2, 0), unreadable_definitions("e2"), act_taken(), standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 2, 0), unreadable_definitions("e2"), standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 2, 0), unreadable_definitions("e2"), standing(json!([todo("t-2", "Two", 4)]), 4, None, json!("dev-1"), 2, 0), served_with_tables(json!([]), "e1"), act_taken(), ]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); let held = HeldDefinitions::new(); let pass = || reporting(&exchange, &replica, &progress).taking_definitions(Arc::clone(&held)); let refused = run_cycle(&replica.driver, &mut pass(), WORKSPACE, NOW).expect_err("the second page is one the copy cannot take"); assert!(format!("{refused:?}").contains("transaction"), "{refused:?}"); assert_eq!(exchange.nth(4).path, routes::DEFINITIONS, "the definitions came, and the pass failed after them"); let (id, data) = row_update(&exchange.nth(5)); assert_eq!(id, "dev-1"); let stalled = chrono::DateTime::from_timestamp_millis(START_MS).expect("an instant").to_rfc3339_opts(chrono::SecondsFormat::Millis, true); assert_eq!(data["stalled_at"], json!(stalled), "{data}"); let why = data["stalled_why"].as_str().expect("why").to_string(); assert!(why.contains("columns of transaction"), "the pass's own sentence: {why}"); assert_eq!(progress.state().stalled_why.as_deref(), Some(why.as_str())); assert!(cursor(&replica).is_some_and(|held| held.contains(".00000001.page-two")), "the copy holds the page cursor: {:?}", cursor(&replica)); assert_eq!(progress.stuck(), None, "one pass is not a copy stuck"); assert!(run_cycle(&replica.driver, &mut pass(), WORKSPACE, NOW).is_err()); assert_eq!(progress.stuck(), None, "two are not"); assert!(run_cycle(&replica.driver, &mut pass(), WORKSPACE, NOW).is_err()); assert_eq!(progress.stuck().as_deref(), Some(why.as_str()), "three passes running on one page, for one reason, while the object answers"); assert_eq!(exchange.calls(), 10, "the row already says why: nothing more is written"); run_cycle(&replica.driver, &mut pass(), WORKSPACE, NOW).expect("the page lands"); let (_, data) = row_update(&exchange.nth(12)); assert_eq!((data["stalled_at"].clone(), data["stalled_why"].clone()), (Value::Null, Value::Null), "{data}"); assert_eq!(progress.stuck(), None, "a page that lands ends the run"); assert_eq!(progress.state().stalled_why, None); } /// RULE: only a pass that failed mid-pass while the object answered counts towards a copy stuck, and only while its reason is the last one's: a phone that reaches nothing writes nothing and ends the run, a 401, 403, 429 or 5xx refusal is said on the row but never counts, a pass's first page never counts, and the reason the row is given is cut to 500 characters. #[test] fn only_the_same_failure_mid_pass_while_the_object_answers_counts_towards_a_copy_stuck() { let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); progress.named(&json!({"device": "dev-1"})); let mid = Reached::Answered { mid_pass: true }; let long = "x".repeat(STALLED_WHY_CHARS + 40); let reports = progress.troubled(&long, mid); let [Report::Update { device, data }] = reports.as_slice() else { panic!("one write: {reports:?}") }; assert_eq!(device, "dev-1"); assert_eq!(data["stalled_why"].as_str().map(str::len), Some(STALLED_WHY_CHARS), "cut to {STALLED_WHY_CHARS}"); progress.troubled(&long, mid); assert!(progress.troubled("offline", Reached::Nothing).is_empty(), "a phone that reaches nothing is offline and writes nothing"); progress.troubled(&long, mid); progress.troubled(&long, mid); assert_eq!(progress.stuck(), None, "offline in between ended the run"); progress.troubled(&long, mid); assert!(progress.stuck().is_some(), "three running"); for (why, reached) in [("refused", Reached::Refused), ("first page", Reached::Answered { mid_pass: false })] { let progress = progress_at(&now); progress.named(&json!({"device": "dev-1"})); for _ in 0..STUCK_PASSES + 1 { progress.troubled(why, reached); } assert_eq!(progress.stuck(), None, "{why} never counts"); } let progress = progress_at(&now); for why in ["one", "two", "one", "two"] { progress.troubled(why, mid); } assert_eq!(progress.stuck(), None, "another reason begins the run again"); assert!(progress.troubled("one", mid).is_empty(), "no row named, nothing written"); } /// RULE: A copy made again from the object says so on the device row once: /// the first page that names the row carries `copy_remade_at`, and no later /// write repeats it (29 Oct 2026: the owner sees the copy was made again). #[test] fn a_copy_made_again_says_when_on_its_row_once() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ standing(json!([todo("t-1", "One", 4)]), 4, None, json!("dev-1"), 1, 0), act_taken(), standing(json!([]), 4, None, json!("dev-1"), 1, 0), act_taken(), ]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); progress.remade("2026-10-29T10:00:00.000Z".to_string()); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the page comes"); let (id, data) = row_update(&exchange.nth(1)); assert_eq!(id, "dev-1"); assert_eq!(data["copy_remade_at"], json!("2026-10-29T10:00:00.000Z"), "{data}"); assert_eq!(progress.state().copy_remade_at, None, "written, it is not held any more"); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the poll comes"); let acts: Vec<_> = exchange.seen().into_iter().filter(|seen| seen.path == "/v1/act").collect(); for seen in acts.iter().skip(1) { let (_, data) = row_update(seen); assert!(data.get("copy_remade_at").is_none(), "said once: {data}"); } } /// RULE: The media drain's queue is a fact on the device row: a pass's last page writes `media_waiting_bytes`, `media_waiting` and `media_failed` when they differ from what the row was last told, and not again while they stand. #[test] fn the_media_backlog_rides_a_passes_last_page_when_it_moved() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ standing(json!([todo("t-1", "One", 4)]), 4, None, json!("dev-1"), 1, 0), act_taken(), standing(json!([]), 4, None, json!("dev-1"), 1, 0), act_taken(), standing(json!([]), 4, None, json!("dev-1"), 1, 0), act_taken(), ]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); progress.media(MediaBacklog { waiting_bytes: 1_200_000_000, waiting: 41, failed: 1 }); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the page comes"); let (id, data) = row_update(&exchange.nth(1)); assert_eq!(id, "dev-1"); assert_eq!( (data["media_waiting_bytes"].clone(), data["media_waiting"].clone(), data["media_failed"].clone()), (json!(1_200_000_000), json!(41), json!(1)), "{data}" ); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the poll comes"); progress.media(MediaBacklog { waiting_bytes: 0, waiting: 0, failed: 1 }); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the poll comes"); let told: Vec = exchange .seen() .into_iter() .filter(|seen| seen.path == "/v1/act") .map(|seen| row_update(&seen).1) .filter(|data| data.get("media_waiting").is_some()) .collect(); assert_eq!(told.len(), 2, "told when it moved, not while it stood: {told:?}"); assert_eq!(told[1]["media_waiting_bytes"], json!(0)); assert_eq!(told[1]["media_waiting"], json!(0)); } #[test] fn a_phone_that_reaches_nothing_is_offline_not_stalled() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([standing(json!([todo("t-1", "One", 4)]), 0, Some("page-two"), json!("dev-1"), 2, 1), act_taken()]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); assert!(run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).is_err()); *now.lock().expect("the clock") += 10 * STALL_AFTER_MS; assert!(run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).is_err()); assert_eq!(progress.state().stalled_at, None); assert!(exchange.seen().iter().filter(|seen| seen.path == "/v1/act").count() == 1, "only the first page's bytes were written"); } #[test] fn each_pass_says_what_this_phone_is_called_on_its_first_page_and_files_no_row_of_its_own() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ standing(json!([todo("t-1", "One", 4)]), 0, Some("page-two"), Value::Null, 2, 1), standing(json!([todo("t-2", "Two", 4)]), 4, None, Value::Null, 2, 0), ]); let now = Arc::new(Mutex::new(START_MS)); let progress = progress_at(&now); let named = DeviceNamed { name: "Asha's iPhone".into(), platform: Some("ios".into()), app_version: Some("1.0.0 (321)".into()) }; run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress).naming(named), WORKSPACE, NOW).expect("a pass"); assert_eq!( exchange.nth(0).path, "/v1/sync?since=0&limit=5000&window=message:90&device_name=Asha%27s+iPhone&platform=ios&app_version=1.0.0+%28321%29&opens=messages,people", "the object files the credential's device from what the first page says", ); assert_eq!(exchange.nth(1).path, "/v1/sync?cursor=page-two", "a later page of the pass says nothing more"); assert_eq!(exchange.calls(), 2, "an answer naming no row is written to by nobody: the phone files none of its own"); } #[test] fn a_page_token_the_object_no_longer_reads_begins_the_pass_again_and_the_cursor_still_moves_forward() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([todo("t-1", "One", 4)]), 0, Some("old-token")), Reply::json(400, r#"{"code": "bad_cursor", "message": "that cursor is not one this object gave"}"#), page(json!([todo("t-1", "One", 4)]), 0, Some("new-token")), page(json!([todo("t-2", "Two", 4)]), 4, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(exchange.nth(1).path, "/v1/sync?cursor=old-token"); assert_eq!(exchange.nth(2).path, "/v1/sync?since=0&limit=5000&window=message:90", "the pass begins again"); assert_eq!(exchange.nth(3).path, "/v1/sync?cursor=new-token"); assert_eq!(todo_title(&replica, "t-2").as_deref(), Some("Two")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000004")); } #[test] fn a_credential_the_object_no_longer_takes_signs_the_phone_out_once_and_keeps_the_copy() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([page(json!([todo("t-1", "Kept", 2)]), 2, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass"); queue_one_change(&replica, "Written while revoked"); let heard = Arc::new(Mutex::new(Vec::::new())); let told = Arc::clone(&heard); let signed_out = SignedOut::new(move |refusal| told.lock().expect("the list").push(refusal.code.clone())); let revoked = ScriptedExchange::new([Reply::json(401, r#"{"code": "credential_revoked", "message": "this sign-in was ended; sign in again"}"#)]); let mut object = transport(&revoked, &replica).signing_out_to(Arc::clone(&signed_out)); assert!(run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).is_err(), "the pass fails"); assert!(run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).is_err(), "and so does the next"); assert_eq!(*heard.lock().expect("the list"), vec!["credential_revoked".to_string()], "told once"); assert_eq!(revoked.calls(), 1, "no pass dials the object again with that credential"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Kept"), "the copy stays"); assert!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox") > 0, "the write waits, unparked"); assert!(replica.driver.all("SELECT reason FROM _parked", &[]).expect("parked").is_empty()); } // ── the object's tools and boards ────────────────────────────────────────── /// An invented tool as the object serves it. fn served_tool(id: &str, name: &str) -> Value { json!({ "id": id, "name": name, "purpose": "Invented for a test.", "card_stock": "sage", "tables": ["todo"], "instructions": "", "automations": [], "author": {"device": "cotton", "name": "Cotton"}, "signature": null, }) } fn served(tools: Value, boards: Value, etag: &str) -> Reply { Reply::ok(&json!({"business": {"kind": "personal"}, "tools": tools, "tables": [], "flavour": {}, "boards": boards, "etag": etag}).to_string()) } fn definition_of(replica: &crate::Replica, table: &str, id: &str) -> Option<(Value, i64)> { replica .driver .get(&format!("SELECT definition, builtin FROM {table} WHERE id = ?"), &[rusqlite::types::Value::Text(id.into())]) .expect("a read") .map(|row| (serde_json::from_str(row.text("definition").expect("a definition")).expect("JSON"), row.int("builtin").expect("a flag"))) } /// RULE: the object's tools and boards reach the copy from `/v1/definitions` — on a launch's first pass and on a pass that moved the object's version, with the etag the copy matches; every non-builtin held definition the object no longer serves leaves, whoever wrote it, and the package's own tool never lands. #[test] fn the_objects_tools_and_boards_are_the_copys_and_follow_the_etag() { let (_dir, _layout, replica) = open_test_replica(); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan"}]}); let package = json!({"format_version": 1, "id": PACKAGE_TOOL, "name": "Personal", "tables": ["todo"]}); let exchange = ScriptedExchange::new([ page(json!([]), 3, None), served(json!([served_tool("garden", "Garden"), served_tool("seeds", "Seeds"), package]), json!([home]), "e1"), // The copy changed: the next pass asks again, finds it matching and holds the etag. page(json!([]), 3, None), served(json!([served_tool("garden", "Garden"), served_tool("seeds", "Seeds")]), json!([home]), "e1"), // Nothing moved: no definitions asked. page(json!([]), 3, None), // The object moved: asked with the etag, and unchanged. page(json!([]), 4, None), Reply::new(304, Vec::new()), // The object moved again: Seeds is gone and Garden renamed. page(json!([]), 5, None), served(json!([served_tool("garden", "The garden")]), json!([home]), "e2"), ]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, &replica).taking_definitions(Arc::clone(&held)); // A tool this phone wrote itself, which the object never serves. replica .driver .run( "INSERT INTO cotton_tool_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at, _hlc) VALUES ('chores', ?, ?, 0, 0, ?, ?, '1760000000000:0000:device:phone')", &[ rusqlite::types::Value::Text(WORKSPACE.into()), rusqlite::types::Value::Text(served_tool("chores", "Chores").to_string()), rusqlite::types::Value::Text(NOW.into()), rusqlite::types::Value::Text(NOW.into()), ], ) .expect("the phone's own tool"); let report = run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pass"); assert!(report.tables.iter().any(|t| t == "cotton_tool_definitions"), "the fan is told: {:?}", report.tables); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "garden"), Some((served_tool("garden", "Garden"), 0))); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "seeds").map(|(d, _)| d["name"].clone()), Some(json!("Seeds"))); assert_eq!(definition_of(&replica, "cotton_tool_definitions", PACKAGE_TOOL), None, "the package's own tool is no tool the phone draws"); assert_eq!(definition_of(&replica, "cotton_board_definitions", "home"), Some((home.clone(), 0)), "Home lands as the object keeps it"); assert_eq!(exchange.nth(1).path, routes::DEFINITIONS); assert_eq!(exchange.nth(1).header("if-none-match"), None, "a launch asks for them whole"); assert_eq!(held.etag(), None, "held once the copy matches"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the second pass"); assert_eq!(held.etag().as_deref(), Some("e1")); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a poll"); assert_eq!(exchange.calls(), 5, "a pass that moved nothing asks for no definitions"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass that moved"); assert_eq!(exchange.nth(6).header("if-none-match"), Some("\"e1\"")); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the object changed its tools"); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "garden").map(|(d, _)| d["name"].clone()), Some(json!("The garden"))); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "seeds"), None, "a tool the object no longer serves leaves"); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "chores"), None, "the object never served the phone's own tool: it leaves too"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(exchange.calls(), 9); } /// RULE: a fresh copy's first pass is the whole catch-up, and the fan draws the object's tools from its first page, not its last. #[test] fn a_launchs_first_page_brings_the_tools_before_the_catch_up_ends() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([todo("t-1", "One", 4)]), 0, Some("page-two")), served(json!([served_tool("garden", "Garden")]), json!([]), "e1"), page(json!([todo("t-2", "Two", 4)]), 0, Some("page-three")), served(json!([served_tool("garden", "Garden")]), json!([]), "e1"), page(json!([]), 4, None), Reply::new(304, Vec::new()), ]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, &replica).taking_definitions(Arc::clone(&held)); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the catch-up"); assert_eq!(exchange.nth(1).path, routes::DEFINITIONS, "asked with the first page"); assert!(definition_of(&replica, "cotton_tool_definitions", "garden").is_some()); assert_eq!(exchange.nth(5).header("if-none-match"), Some("\"e1\""), "and once more at the end of the pass that moved the object"); assert_eq!(exchange.calls(), 6); assert_eq!(held.etag().as_deref(), Some("e1")); } /// RULE: a served tool this build's read of tools would refuse is left on the object — one unreadable row would refuse every tool the fan draws — and the rest land. #[test] fn a_served_tool_this_build_cannot_read_is_left_out_and_the_rest_land() { let (_dir, _layout, replica) = open_test_replica(); let unreadable = json!({"id": "broken", "name": "Broken", "tables": "todo"}); let exchange = ScriptedExchange::new([page(json!([]), 3, None), served(json!([served_tool("garden", "Garden"), unreadable]), json!([]), "e1")]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert!(definition_of(&replica, "cotton_tool_definitions", "garden").is_some()); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "broken"), None); } /// An invented data-only table as the object serves it. fn served_table(id: &str, plural: &str) -> Value { json!({ "id": id, "name": "Bed", "plural": plural, "picture": null, "builtin": false, "engine": null, "columns": [{"key": "label", "name": "Label", "type": "text", "required": true}], "title": "label", "date": null, "project": null, "order": null, "slip": {"title": "label", "subtitle": null, "trailing": null, "photo": null, "toggle": null}, "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["label"]}], "instructions": "Invented for a test.", }) } fn served_with_tables(tables: Value, etag: &str) -> Reply { Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": tables, "flavour": {}, "boards": [], "etag": etag}).to_string()) } fn holds_table(replica: &crate::Replica, name: &str) -> bool { replica.driver.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(name.into())]).expect("a read").is_some() } /// RULE: the owner the object names lands on a copy whose own workspace row holds no receipt (a row written into the file before its receipts were, as on the owner's copy, 27 Oct 2026): the served change says what the row holds and is minted as its create, so the row stays with everything under it and holds the owner — a bare change of a row with no create is not live, and the fold would take the row, and every row under it, away. #[test] fn the_served_owner_lands_on_a_workspace_row_that_holds_no_receipt() { let (_dir, _layout, replica) = open_test_replica(); let receipts = |replica: &crate::Replica| { replica.driver.get("SELECT COUNT(*) AS n FROM _writes WHERE tbl = 'cotton_workspaces'", &[]).expect("a read").and_then(|row| row.int("n")).unwrap_or_default() }; assert_eq!(receipts(&replica), 0, "the copy's workspace row holds no receipt"); let person = json!({ "table": "person", "id": "person-me", "version": 3, "owner": null, "data": {"full_name": "Invented Owner"}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }); let definitions = json!({"business": {"kind": "personal", "owner_person_id": "person-me"}, "tools": [], "tables": [], "flavour": {}, "boards": [], "etag": "e1"}); let exchange = ScriptedExchange::new([page(json!([todo("t-1", "Ring the bank", 4), person]), 4, None), Reply::ok(&definitions.to_string())]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let parked = replica.driver.all("SELECT tbl, reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); let row = replica .driver .get("SELECT name, owner_user_id, owner_person_id FROM cotton_workspaces WHERE id = ?", &[rusqlite::types::Value::Text(WORKSPACE.into())]) .expect("a read") .expect("the workspace row stays"); assert_eq!(row.text("owner_person_id"), Some("person-me")); assert_eq!((row.text("name"), row.text("owner_user_id")), (Some("A synthetic workspace"), Some(crate::test_support::OWNER)), "the row keeps what it held"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Ring the bank"), "a row under the workspace stays"); assert!(receipts(&replica) > 0, "the row now holds its receipts"); } /// RULE: the object's tables reach the copy from `/v1/definitions` as its tools do — each one this build reads lands as the object's (and the copy makes its table), one it cannot read is left on the object, one at an id this build keeps under an engine lands only naming that engine, and a table the object no longer serves leaves. #[test] fn the_objects_tables_are_the_copys_and_one_this_build_cannot_read_stays_on_the_object() { let (_dir, _layout, replica) = open_test_replica(); let unreadable = json!({"id": "broken", "name": "Broken", "columns": []}); let mut engineless_todo = served_table("todo", "Todos"); engineless_todo["name"] = json!("Todo"); let exchange = ScriptedExchange::new([ page(json!([]), 3, None), served_with_tables(json!([served_table("garden_bed", "Beds"), served_table("seed_tray", "Trays"), unreadable.clone(), engineless_todo.clone()]), "e1"), page(json!([]), 3, None), served_with_tables(json!([served_table("garden_bed", "Beds"), served_table("seed_tray", "Trays"), unreadable.clone(), engineless_todo.clone()]), "e1"), // The object moved: Trays is gone and Beds renamed. page(json!([]), 4, None), served_with_tables(json!([served_table("garden_bed", "Raised beds"), unreadable, engineless_todo]), "e2"), ]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, &replica).taking_definitions(Arc::clone(&held)); let report = run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pass"); assert!(report.tables.iter().any(|t| t == "cotton_table_definitions"), "the decks are told: {:?}", report.tables); assert_eq!(definition_of(&replica, "cotton_table_definitions", "garden_bed"), Some((served_table("garden_bed", "Beds"), 0))); assert_eq!(definition_of(&replica, "cotton_table_definitions", "seed_tray").map(|(d, _)| d["plural"].clone()), Some(json!("Trays"))); assert!(holds_table(&replica, "cotton_garden_bed"), "the copy makes the served table's own table"); assert_eq!(definition_of(&replica, "cotton_table_definitions", "broken"), None, "a table this build cannot read is left on the object"); assert_eq!(definition_of(&replica, "cotton_table_definitions", "todo"), None, "the unserved definition leaves even though its engine storage stays"); assert!(holds_table(&replica, "cotton_todos"), "compiled storage stays"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass that finds the copy matching"); assert_eq!(held.etag().as_deref(), Some("e1"), "what was left out does not keep the copy from matching"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the object changed its tables"); assert_eq!(definition_of(&replica, "cotton_table_definitions", "garden_bed").map(|(d, _)| d["plural"].clone()), Some(json!("Raised beds"))); assert_eq!(definition_of(&replica, "cotton_table_definitions", "seed_tray"), None, "a table the object no longer serves leaves"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(exchange.calls(), 6); } /// A row of an invented made table, as a sync page carries it. fn bed(id: &str, label: &str, version: i64) -> Value { json!({ "table": "garden_bed", "id": id, "version": version, "owner": null, "data": {"label": label}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }) } fn label_in(replica: &crate::Replica, table: &str, id: &str) -> Option { replica .driver .get(&format!("SELECT label FROM {table} WHERE id = ?"), &[rusqlite::types::Value::Text(id.into())]) .expect("a read") .and_then(|row| row.text("label").map(str::to_string)) } /// RULE (owner, 26 Oct 2026): the rows of every table the object serves come /// down — a made table's (Quotas, Machines, Work) land in the table its /// definition makes, from the page its definition comes with, and a write to /// one goes to the object; a table with no face this build keeps in a table /// of its own is written as a definition too (walk, 27 Oct 2026: a chat's /// contact link is titled by it), and a table made on the object since the /// launch is asked for when its rows first arrive. #[test] fn a_made_tables_rows_land_with_its_definition_and_its_writes_go_to_the_object() { let (_dir, _layout, replica) = open_test_replica(); let participant = json!({ "format_version": 1, "id": "email_participant", "name": "Email participant", "plural": "Email participants", "visibility": "owner", "columns": [{"key": "thread_id", "type": "text"}, {"key": "email", "type": "text"}, {"key": "role", "type": "text"}], }); let tray = json!({"table": "seed_tray", "id": "s-1", "version": 4, "owner": null, "data": {"label": "Tomatoes"}, "created_at": NOW, "updated_at": NOW}); let exchange = ScriptedExchange::new([ page(json!([bed("b-1", "North bed", 2)]), 2, None), served_with_tables(json!([served_table("garden_bed", "Beds"), participant.clone()]), "e1"), // A write here: posted to the object as the made table's create. Reply::ok(r#"{"version": 3, "changed": []}"#), page(json!([]), 2, None), served_with_tables(json!([served_table("garden_bed", "Beds"), participant.clone()]), "e1"), // A table made on the object since: its rows ask for the definitions first. page(json!([tray]), 4, None), served_with_tables(json!([served_table("garden_bed", "Beds"), served_table("seed_tray", "Trays"), participant]), "e2"), ]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, &replica).taking_definitions(Arc::clone(&held)); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pass"); assert_eq!(label_in(&replica, "cotton_garden_bed", "b-1").as_deref(), Some("North bed"), "a made table's row lands with its definition"); assert!(definition_of(&replica, "cotton_table_definitions", "email_participant").is_some(), "a faceless table kept in a compiled table is written: links into it are titled by it"); // A write to the made table, as a deck makes one. let mut patch = serde_json::Map::new(); patch.insert("workspace_id".into(), WORKSPACE.into()); patch.insert("label".into(), "South bed".into()); patch.insert("created_at".into(), NOW.into()); patch.insert("updated_at".into(), NOW.into()); let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(7))); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "add_bed".into(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::create("cotton_garden_bed", "b-2", patch)], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_760_000_000_000, &mut ids).expect("the replica's clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("a queued change"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass that posts it"); let act = body(&exchange.nth(2)); assert_eq!(act["act"], "create"); assert_eq!(act["args"]["table"], "garden_bed"); assert_eq!(act["args"]["id"], "b-2"); assert_eq!(act["args"]["data"], json!({"label": "South bed"})); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass with a new table's rows"); assert_eq!(exchange.nth(6).path, routes::DEFINITIONS, "its rows asked for the definitions"); assert_eq!(label_in(&replica, "cotton_seed_tray", "s-1").as_deref(), Some("Tomatoes"), "a table made since lands with its rows"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(exchange.calls(), 7); } fn passed_record(replica: &crate::Replica) -> Option { cotton_store::cursors::read_cursors(&replica.driver).expect("the cursors").get(PASSED_KEY).cloned() } fn subscription(id: &str, name: &str, version: i64) -> Value { json!({ "table": "subscription", "id": id, "version": version, "owner": null, "data": {"name": name, "provider": "Invented", "amount": 49900, "currency": "INR", "cycle": "monthly", "next_renewal": "2026-10-09", "status": "active"}, "created_at": "2026-10-11T00:38:41.596Z", "updated_at": "2026-10-11T01:09:33.156Z", }) } fn served_subscription() -> Value { json!({ "id": "subscription", "name": "Subscription", "plural": "Subscriptions", "picture": null, "builtin": true, "engine": null, "columns": [ {"key": "name", "name": "Name", "type": "text", "required": true}, {"key": "provider", "name": "Provider", "type": "text"}, {"key": "amount", "name": "Amount", "type": "amount"}, {"key": "currency", "name": "Currency", "type": "text"}, {"key": "cycle", "name": "Cycle", "type": "text"}, {"key": "next_renewal", "name": "Next renewal", "type": "date"}, {"key": "status", "name": "Status", "type": "text"}, ], "title": "name", "date": "next_renewal", "project": null, "order": null, "slip": {"title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null}, "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["name"]}], "instructions": "Invented for a test.", }) } fn subscription_name(replica: &crate::Replica, id: &str) -> Option { replica .driver .get("SELECT name FROM cotton_subscription WHERE id = ?", &[rusqlite::types::Value::Text(id.into())]) .expect("a read") .and_then(|row| row.text("name").map(str::to_string)) } /// RULE (walk, 26 Oct 2026): a copy whose cursor went past a table's rows /// under a build that kept them nowhere pulls again from the start once a /// build places that table — Subscriptions, Work and Machines stood empty on /// a phone pulled before 12dbd60b0 while the object held their rows, because /// the cursor had moved past every row older than the upgrade. The cursor /// still only moves forward, and a pass that places nothing new asks from /// where it stands. #[test] fn a_copy_that_passed_a_tables_rows_by_pulls_them_again_once_a_build_places_it() { let (_dir, _layout, replica) = open_test_replica(); // The earlier build: it took no definitions, so the subscription rows on // its page had nowhere to land and its cursor went past them. let earlier = ScriptedExchange::new([page(json!([todo("t-1", "Ring the bank", 3), subscription("s-1", "Invented Pro", 4)]), 5, None)]); let mut object = transport(&earlier, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the earlier build's pass"); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000005")); assert!(!holds_table(&replica, "cotton_subscription") || subscription_name(&replica, "s-1").is_none(), "the earlier build kept no subscription"); let record = passed_record(&replica).expect("the pass records what its cursor went past"); assert_eq!(record, "h0000.000000.m03:subscription", "the record names the table passed by"); // This build places the object's subscription table: its first page asks // where the copy stands, takes the definitions that place the table, and // asks again for that table whole and the rest since the cursor (21 Nov // 2026: never the whole object again), the cursor's pull count unchanged. let now = ScriptedExchange::new([ page(json!([]), 5, None), served_with_tables(json!([served_subscription()]), "e1"), again_page(json!([subscription("s-1", "Invented Pro", 4)]), 6, &["subscription"]), page(json!([]), 6, None), served_with_tables(json!([served_subscription()]), "e1"), ]); let held = HeldDefinitions::new(); let mut object = transport(&now, &replica).taking_definitions(Arc::clone(&held)); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("this build's first pass"); assert_eq!(now.nth(0).path, "/v1/sync?since=5&limit=5000&window=message:90"); assert_eq!(now.nth(1).path, routes::DEFINITIONS); assert_eq!(now.nth(2).path, "/v1/sync?since=5&limit=5000&window=message:90&again=subscription", "the passed table comes whole, the rest since the cursor"); assert_eq!(subscription_name(&replica, "s-1").as_deref(), Some("Invented Pro"), "the row the cursor went past came down"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Ring the bank")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000006")); assert_eq!(passed_record(&replica).as_deref(), Some("h0000.000001.m03:"), "the record lets the table go once it came"); // The next pass places nothing new: it asks from where the copy stands. run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the next pass"); assert_eq!(now.nth(3).path, "/v1/sync?since=6&limit=5000&window=message:90"); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000006")); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(now.calls(), 5); } /// A copy a build without the record pulled (every copy before this one) /// cannot say which tables it holds whole: its first pass under this build /// pulls again from the start, once. #[test] fn a_copy_with_no_record_of_what_it_passed_by_pulls_again_from_the_start_once() { let (_dir, _layout, replica) = open_test_replica(); let at = "2026-10-25T09:00:00.000Z"; cotton_store::cursors::advance_cursor(&replica.driver, CURSOR_KEY, "v0000000000010703", at).expect("an earlier build's cursor"); let exchange = ScriptedExchange::new([ page(json!([todo("t-1", "Ring the bank", 9)]), 10704, None), page(json!([]), 10704, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass"); assert_eq!(exchange.nth(0).path, "/v1/sync?since=0&limit=5000&window=message:90", "nothing to ask from: the copy pulls again"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Ring the bank")); assert_eq!(cursor(&replica).as_deref(), Some("w0001v0000000000010704")); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the next pass"); assert_eq!(exchange.nth(1).path, "/v1/sync?since=10704&limit=5000&window=message:90"); } // ── the columns the object's definitions name ────────────────────────────── /// The object's money row definition, as the personal kit ships it: it names /// the running balance the object's engine writes on every row /// (`balance_before_minor`, `balance_after_minor`, `balance_state`), which /// this build's `cotton_money_transactions` lacks. fn served_transaction() -> Value { serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/transaction.json")).expect("the kit's transaction") } /// A money row as a sync page carries it: every column the store's table /// requires, and the balance the object's engine wrote on it. fn movement(id: &str, version: i64, before: i64, after: i64) -> Value { json!({ "table": "transaction", "id": id, "version": version, "owner": null, "data": { "occurred_on": "2026-10-20", "description": "Invented grocer", "amount_minor": before - after, "amount_known": true, "direction": "out", "currency": "INR", "for_period": "", "status": "actual", "repeat": "none", "between_us": false, "moves_money": true, "source": "manual", "balance_before_minor": before, "balance_after_minor": after, "balance_state": "ok", }, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }) } /// A news topic definition as the object served it before TABLE DROP 1 took /// the table out of the kit (the store still compiles `cotton_news_topics` /// for the retire machinery, so it stays the example of a compiled table): it /// names what the object's news engine wrote on each topic (`position`, /// `last_covered_at`, `meta`, each read only), which this build's /// `cotton_news_topics` lacks. The money tables are no such example: a copy /// keeps the kit's columns of the tables a money run is written on from its /// open ([`super::keep_run_columns`]). fn served_topic() -> Value { json!({ "format_version": 1, "id": "news_topic", "name": "Topic", "plural": "Topics", "builtin": true, "visibility": "owner", "title": "name", "engine": "news", "columns": [ {"key": "name", "type": "text", "required": true}, {"key": "brief", "type": "longtext"}, {"key": "exclusions", "type": "longtext"}, {"key": "kind", "type": "choice", "choices": ["search", "source"], "default": "search"}, {"key": "source_url", "type": "text"}, {"key": "active", "type": "bool", "default": true}, {"key": "paused_reason", "type": "text", "readonly": true}, {"key": "unopened_streak", "type": "number", "readonly": true}, {"key": "last_new_at", "type": "date", "readonly": true}, {"key": "sort_order", "type": "number", "readonly": true}, {"key": "trashed_at", "type": "date", "readonly": true}, {"key": "position", "type": "number", "readonly": true}, {"key": "pause_reason", "type": "longtext", "readonly": true}, {"key": "last_covered_at", "type": "date", "readonly": true}, {"key": "meta", "type": "text", "readonly": true} ] }) } /// A news topic as a sync page carries it: every column the store's table /// requires, and what the object's engine wrote on it. fn topic(id: &str, version: i64, position: i64, meta: &str) -> Value { json!({ "table": "news_topic", "id": id, "version": version, "owner": null, "data": { "name": "Invented rivers", "kind": "search", "active": true, "position": position, "last_covered_at": "2026-10-20", "meta": meta, }, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }) } fn coverage(replica: &crate::Replica, id: &str) -> Option<(Option, Option, Option)> { replica .driver .get( "SELECT position AS p, last_covered_at AS c, meta AS m FROM cotton_news_topics WHERE id = ?", &[rusqlite::types::Value::Text(id.into())], ) .expect("a read") .map(|row| (row.int("p"), row.text("c").map(str::to_string), row.text("m").map(str::to_string))) } /// The columns a copy keeps from its open on each table a money run is /// written on, by store name: the kit's columns the build's tables lack. fn kept_from_open() -> Vec<(String, Vec)> { let kit: Vec = cotton_core::rules::money::balances::RUN_TABLES .iter() .map(|id| serde_json::from_slice(cotton_core::kit::table_file(id).expect("a kit table")).expect("it reads")) .collect(); let map = ObjectTables::personal().with_defined(kit.iter()).expect("a map"); let mut kept: Vec<(String, Vec)> = cotton_core::rules::money::balances::RUN_TABLES .iter() .map(|id| { let table = map.object(id).expect("a run table"); (table.store.clone(), table.served.iter().map(|column| column.name.clone()).collect()) }) .collect(); // And the kit columns Cotton Chat and Cotton Days write on a copy before any definition reaches it (CHAT_KEPT_COLUMNS, DAYS_KEPT_COLUMNS). let personal = ObjectTables::personal(); for (id, columns) in super::CHAT_KEPT_COLUMNS.iter().chain(super::DAYS_KEPT_COLUMNS).chain(super::NOTES_KEPT_COLUMNS) { let table = personal.object(id).expect("a kept table"); kept.push((table.store.clone(), columns.iter().map(|column| column.to_string()).collect())); } kept } fn table_columns(replica: &crate::Replica, table: &str) -> Vec { replica .driver .all(&format!("SELECT name FROM pragma_table_info('{table}')"), &[]) .expect("a read") .iter() .filter_map(|row| row.text("name").map(str::to_string)) .collect() } /// RULE (owner, 27 Oct 2026): the copy does not drop a column it does not have — a column a served definition names on a table this build compiles, that the build's table lacks, is added to the copy's table (nullable, typed from the definition) before the table's rows fold, and the object's value lands in it; a second pass adds nothing, and the copy's own write still sends only the storage map's columns. #[test] fn a_column_the_objects_definition_names_is_added_to_the_copy_and_its_value_lands() { let (_dir, _layout, replica) = open_test_replica(); let replica = Arc::new(std::sync::Mutex::new(replica)); let copy = || replica.lock().expect("the copy"); let before = table_columns(©(), "cotton_news_topics"); assert!(!before.iter().any(|name| name == "position"), "this build's table lacks the position"); let exchange = ScriptedExchange::new([ page(json!([topic("n-1", 3, 4, "Invented coverage")]), 3, None), served_with_tables(json!([served_topic()]), "e1"), page(json!([]), 3, None), served_with_tables(json!([served_topic()]), "e1"), ]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, ©()).taking_definitions(Arc::clone(&held)); object.lend_file(Arc::clone(&replica) as Arc); run_cycle_paged(&replica, &mut object, WORKSPACE, NOW).expect("the first pass"); let after = table_columns(©(), "cotton_news_topics"); for column in ["position", "last_covered_at", "meta"] { assert!(after.iter().any(|name| name == column), "the copy's table gained {column}: {after:?}"); } assert_eq!(coverage(©(), "n-1"), Some((Some(4), Some("2026-10-20".into()), Some("Invented coverage".into()))), "the object's values landed"); let parked = copy().driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); run_cycle_paged(&replica, &mut object, WORKSPACE, NOW).expect("the second pass"); assert_eq!(table_columns(©(), "cotton_news_topics"), after, "a second pass adds nothing"); assert_eq!(held.etag().as_deref(), Some("e1")); assert_eq!(exchange.calls(), 4); // What the engine wrote is the object's to write: a write here sends the map's columns alone. let table = object.map(); let topics = table.object("news_topic").expect("topics come"); let file = rusqlite::Connection::open(©().path).expect("the copy"); let sent = row_now(&file, topics, "n-1").expect("a read").expect("the row"); assert!(sent.get("position").is_none() && sent.get("meta").is_none() && sent.get("name").is_some(), "{sent:?}"); } /// RULE: the copy takes the object's columns only through the copy the pass lent its transport, never a second open of the file: a pass lent none refuses, naming the table, and the copy's table is left as it was. #[test] fn a_pass_lent_no_copy_takes_no_column_and_says_which() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([]), 3, None), served_with_tables(json!([served_topic()]), "e1"), ]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); let refused = run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect_err("no copy was lent"); assert!(format!("{refused:?}").contains("news_topic"), "{refused:?}"); assert!(!table_columns(&replica, "cotton_news_topics").iter().any(|name| name == "position")); } /// RULE: a column the storage map already places is never added twice — not under the object's key, and not under the store's name it renames one to (a note's `project` kept in `project_id`) — nor one the build's table holds, nor a computed one; and a column of a type this build does not know refuses the map by name rather than being guessed or dropped. #[test] fn a_column_the_map_places_or_renames_is_not_added_and_an_unknown_type_is_refused() { let note: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/note.json")).expect("the kit's note"); assert!(note["columns"].as_array().expect("columns").iter().any(|c| c["key"] == "project_id"), "the note names the column the map renames project to"); let map = ObjectTables::personal().with_defined([¬e, &served_transaction()]).expect("a map"); let notes = map.object("note").expect("notes come"); let ours: Vec<&str> = notes.columns.iter().map(|(_, ours, _)| ours.as_str()).collect(); for column in ¬es.served { assert!(!ours.contains(&column.name.as_str()), "{} is already the store's column of the map", column.name); assert!(!["project", "project_id", "created_at", "updated_at", "id"].contains(&column.name.as_str()), "{}", column.name); } let money: Vec<&str> = map.object("transaction").expect("money rows").served.iter().map(|c| c.name.as_str()).collect(); for column in ["balance_before_minor", "balance_after_minor", "balance_state"] { assert!(money.contains(&column), "{column} in {money:?}"); } assert!(!money.contains(&"amount_minor"), "the map's own column is placed once"); // A second definition of the same table only adds. let again = map.with_defined([&served_transaction()]).expect("again"); assert_eq!(again.object("transaction").expect("money rows").served.len(), money.len()); let mut odd = served_transaction(); odd["columns"].as_array_mut().expect("columns").push(json!({"key": "mood", "name": "Mood", "type": "colour"})); let refused = ObjectTables::personal().with_defined([&odd]).expect_err("a type this build does not know"); assert!(refused.contains("mood") && refused.contains("colour"), "{refused}"); } /// RULE: every typed table the object fills holds exactly the columns its store spec names, so a column the copy adds for a definition is the only kind of column the spec does not know — and the fold learns those from the file. The definitions a copy keeps columns for before the object serves any are the kit's, on the tables a money run is written on (a local copy works its money run: owner, 1 Nov 2026), and Cotton Chat's thread columns (CHAT_KEPT_COLUMNS, Cotton works before sign-in). #[test] fn a_typed_table_holds_only_its_spec_columns_before_the_copy_adds_any() { let (_dir, _layout, replica) = open_test_replica(); let kept = kept_from_open(); for table in ObjectTables::personal().tables.iter() { let spec = cotton_store::schema::specs::spec_for(&table.store).expect("a compiled table"); let held: Vec = table_columns(&replica, &table.store).into_iter().filter(|name| !name.starts_with('_')).collect(); let mut named: Vec = spec.columns.iter().map(|(name, _)| name.to_string()).collect(); named.extend(kept.iter().filter(|(store, _)| *store == table.store).flat_map(|(_, columns)| columns.iter().cloned())); let unnamed: Vec<&String> = held.iter().filter(|name| !named.contains(name)).collect(); assert!(unnamed.is_empty(), "{} holds {unnamed:?}, which its spec does not name", table.store); } } /// RULE: a copy that held a table's rows without a column the object fills — an earlier build's pull, or a page that came before the definition naming it — pulls again from the start once it keeps that column, and the value lands on the rows it already held; a copy whose record named tables alone (`g`) pulls again once. #[test] fn a_copy_that_held_rows_without_a_column_pulls_them_again_once_it_keeps_it() { let (_dir, _layout, replica) = open_test_replica(); // The earlier pass: no definitions, so the balance had nowhere to land. let earlier = ScriptedExchange::new([page(json!([topic("n-1", 4, 2, "Invented coverage")]), 5, None)]); let mut object = transport(&earlier, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the earlier pass"); assert!(!table_columns(&replica, "cotton_news_topics").iter().any(|name| name == "position")); let record = passed_record(&replica).expect("the record"); assert!(record.starts_with("h0000.") && record.contains("news_topic.position"), "the record names the key passed by: {record}"); let now = ScriptedExchange::new([ page(json!([]), 5, None), served_with_tables(json!([served_topic()]), "e1"), again_page(json!([topic("n-1", 4, 2, "Invented coverage")]), 6, &["news_topic"]), ]); let held = HeldDefinitions::new(); let mut object = transport(&now, &replica).taking_definitions(Arc::clone(&held)); let replica = Arc::new(std::sync::Mutex::new(replica)); let copy = || replica.lock().expect("the copy"); object.lend_file(Arc::clone(&replica) as Arc); run_cycle_paged(&replica, &mut object, WORKSPACE, NOW).expect("this pass"); assert_eq!(now.nth(0).path, "/v1/sync?since=5&limit=5000&window=message:90"); assert_eq!(now.nth(2).path, "/v1/sync?since=5&limit=5000&window=message:90&again=news_topic", "the table whose column it now keeps comes whole, the rest since the cursor"); assert_eq!(coverage(©(), "n-1"), Some((Some(2), Some("2026-10-20".into()), Some("Invented coverage".into()))), "the same version lands what the engine wrote"); assert_eq!(cursor(©()).as_deref(), Some("v0000000000000006")); let parked = copy().driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); // A record an earlier build wrote names tables alone: the copy pulls again once. let (_dir, _layout, replica) = open_test_replica(); let at = "2026-10-25T09:00:00.000Z"; cotton_store::cursors::advance_cursor(&replica.driver, CURSOR_KEY, "w0001v0000000000000007", at).expect("a cursor"); cotton_store::cursors::advance_cursor(&replica.driver, PASSED_KEY, "g0001.000000:", at).expect("a g record"); let exchange = ScriptedExchange::new([page(json!([]), 7, None)]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass"); assert_eq!(exchange.nth(0).path, "/v1/sync?since=0&limit=5000&window=message:90"); assert_eq!(cursor(&replica).as_deref(), Some("w0002v0000000000000007")); assert_eq!(passed_record(&replica).as_deref(), Some("h0002.000000.m03:")); } fn todo_priority(replica: &crate::Replica, id: &str) -> Option<(String, i64)> { replica .driver .get("SELECT status, priority FROM cotton_todos WHERE id = ?", &[rusqlite::types::Value::Text(id.into())]) .expect("a read") .map(|row| (row.text("status").unwrap_or_default().to_string(), row.int("priority").unwrap_or(-1))) } /// RULE (walk, 27 Oct 2026): the object holds nothing in a column a create /// never named, and reads it as it reads a null. A column here that cannot /// hold null holds its declared default for that nothing — before, the row /// named null there and the fold refused it: a WhatsApp message the Mac /// imported naming no mentions never reached the phone while its thread's /// last line did, so the card said a line the chat never drew. #[test] fn a_row_the_object_holds_nothing_in_a_column_of_lands_with_the_columns_default() { let (_dir, _layout, replica) = open_test_replica(); let mut bare = todo("t-1", "Ring the bank", 3); bare["data"] = json!({"title": "Ring the bank"}); let mut cleared = todo("t-2", "Pay the rent", 4); cleared["data"]["priority"] = json!(2); let exchange = ScriptedExchange::new([ page(json!([bare, cleared]), 4, None), page(json!([{"table": "todo", "id": "t-2", "version": 5, "owner": null, "data": {"title": "Pay the rent", "status": "open", "priority": null}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-21T09:00:00.000Z"}]), 5, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(todo_priority(&replica, "t-1"), Some(("open".into(), 0)), "a column never written holds its default"); assert_eq!(todo_priority(&replica, "t-2"), Some(("open".into(), 2))); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the next pass"); assert_eq!(todo_priority(&replica, "t-2"), Some(("open".into(), 0)), "a column written null holds its default, not the value before"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); } /// A copy whose last pull from the start an earlier [`MINTING`] made — some of /// whose rows its fold refused, a message naming no mentions — pulls again /// from the start once under this build, and those rows come down. #[test] fn a_copy_an_earlier_minting_pulled_pulls_again_from_the_start_once() { let (_dir, _layout, replica) = open_test_replica(); let at = "2026-10-26T09:00:00.000Z"; cotton_store::cursors::advance_cursor(&replica.driver, CURSOR_KEY, "w0001v0000000000000005", at).expect("an earlier build's cursor"); cotton_store::cursors::advance_cursor(&replica.driver, PASSED_KEY, "h0001.000000:device,secret", at).expect("an earlier minting's record"); let mut bare = todo("t-1", "Ring the bank", 4); bare["data"] = json!({"title": "Ring the bank"}); let exchange = ScriptedExchange::new([ page(json!([bare]), 6, None), page(json!([]), 6, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass"); assert_eq!(exchange.nth(0).path, "/v1/sync?since=0&limit=5000&window=message:90", "an earlier minting's copy pulls again"); assert_eq!(todo_priority(&replica, "t-1"), Some(("open".into(), 0)), "the row an earlier minting refused came down"); assert_eq!(cursor(&replica).as_deref(), Some("w0002v0000000000000006")); assert_eq!(passed_record(&replica).as_deref(), Some("h0002.000000.m03:")); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the next pass"); assert_eq!(exchange.nth(1).path, "/v1/sync?since=6&limit=5000&window=message:90", "once"); } /// A receipt an earlier minting made of a row, naming null in a column that /// cannot hold it, which the fold kept but could not assemble a row from (a /// message held while its chat waited): the same version pulled again under /// [`MINTING`] 2 is another op, names the column's default, stands for the /// held receipt, and the row lands. #[test] fn a_receipt_an_earlier_minting_held_without_its_row_is_replaced_and_the_row_lands() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([page(json!([todo("t-0", "Ring the bank", 2)]), 2, None)]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass that knows the object's author"); let mut bare = todo("t-1", "Pay the rent", 3); bare["data"] = json!({"title": "Pay the rent"}); let ms = cotton_store::protocol::js::parse_date_ms("2026-10-20T09:00:00.000Z").expect("a date"); let stamp = format!("{ms:013}:0003:{OBJECT_AUTHOR}"); let mut fields = std::collections::BTreeMap::new(); for (column, value) in [("title", json!("Pay the rent")), ("status", Value::Null), ("priority", Value::Null), ("workspace_id", json!(WORKSPACE))] { fields.insert(column.to_string(), value); } let earlier = cotton_store::mint::served(op_id_of(ms, "todo", "t-1", 3, &[]), "cotton_todos", "t-1", &stamp, &object_actor(), cotton_store::mint::ServedRow::Live(fields), None).expect("an earlier minting's receipt"); let receipt = canonical::decode(earlier.receipt.as_bytes()).expect("decodes"); replica .driver .run( "INSERT INTO _writes (tbl, row_id, hlc, author, op_id, kind, actor, bytes) VALUES (?,?,?,?,?,?,?,?)", &[ SqlValue::Text("cotton_todos".into()), SqlValue::Text("t-1".into()), SqlValue::Text(stamp.clone()), SqlValue::Text(OBJECT_AUTHOR.into()), SqlValue::Text(earlier.op_id.clone()), SqlValue::Text("create".into()), SqlValue::Text(receipt.actor.clone()), SqlValue::Blob(earlier.receipt.as_bytes().to_vec()), ], ) .expect("held without its row"); assert_eq!(todo_priority(&replica, "t-1"), None); let again = ScriptedExchange::new([page(json!([bare]), 3, None)]); let mut object = transport(&again, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pull again"); assert_eq!(todo_priority(&replica, "t-1"), Some(("open".into(), 0)), "the row lands"); let held = replica.driver.all("SELECT op_id FROM _writes WHERE tbl = 'cotton_todos' AND row_id = 't-1'", &[]).expect("reads"); assert_eq!(held.len(), 1, "one receipt per stamp"); assert_ne!(held[0].text("op_id"), Some(earlier.op_id.as_str()), "the earlier minting's receipt is replaced"); } fn credential(id: &str, version: i64, revoked_at: Value) -> Value { json!({ "table": "code_credential", "id": id, "version": version, "owner": null, "data": {"device_id": "device-synthetic", "name": "A synthetic runner", "scope": "runner", "revoked_at": revoked_at, "read_only": 0}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }) } fn revoked_at(replica: &crate::Replica, id: &str) -> Option> { replica .driver .get("SELECT revoked_at FROM cotton_code_credentials WHERE id = ?", &[SqlValue::Text(id.into())]) .expect("a read") .map(|row| row.text("revoked_at").map(str::to_string)) } /// RULE (walk, 27 Oct 2026): a code credential the object never revoked lands /// on the copy, and one it revoked lands revoked — the object's row names no /// revocation it holds nothing in, so the fold's un-revocation fence has /// nothing to refuse. Before, every served credential named `revoked_at` /// null, sat parked as an un-revocation, and none reached the phone. #[test] fn a_code_credential_the_object_never_revoked_lands_and_one_it_revoked_lands_revoked() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([page(json!([credential("c-1", 2, Value::Null), credential("c-2", 3, json!("2026-10-21T09:00:00.000Z"))]), 3, None)]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let parked = replica.driver.all("SELECT tbl, reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(revoked_at(&replica, "c-1"), Some(None), "never revoked, and here"); assert_eq!(revoked_at(&replica, "c-2"), Some(Some("2026-10-21T09:00:00.000Z".into())), "revoked, and here revoked"); } /// The receipt an earlier [`MINTING`] made of a served credential, naming its /// revocation null, parked as an un-revocation; stamped by `author`. fn parked_as_an_earlier_minting_made_it(replica: &crate::Replica, id: &str, version: i64, author: &str) -> String { let ms = cotton_store::protocol::js::parse_date_ms("2026-10-20T09:00:00.000Z").expect("a date"); let stamp = format!("{ms:013}:{version:04}:{author}"); let mut fields = std::collections::BTreeMap::new(); for (column, value) in [("device_id", json!("device-synthetic")), ("name", json!("A synthetic runner")), ("scope", json!("runner")), ("revoked_at", Value::Null), ("read_only", json!(0)), ("workspace_id", json!(WORKSPACE)), ("created_at", json!("2026-10-20T09:00:00.000Z"))] { fields.insert(column.to_string(), value); } let receipt = cotton_store::canonical::Receipt { table: "cotton_code_credentials".into(), row_id: id.into(), kind: Kind::Create, stamp, author: author.into(), actor: object_actor().to_wire(), schema: cotton_store::schema::ddl::SCHEMA_VERSION, fields, restamps: None, erase: None, undo: None, }; let earlier = cotton_store::wire::from_receipt(op_id_of(ms, "code_credential", id, version, &[]), &receipt).expect("an earlier minting's receipt"); cotton_store::rejected::park(&replica.driver, &earlier, cotton_store::rejected::Direction::Pull, cotton_store::rejected::Class::Conflict, "a revoked row is not un-revoked by a patch", NOW).expect("parked"); earlier.op_id } /// A copy whose last pull from the start an earlier minting made. fn pulled_by_an_earlier_minting(replica: &crate::Replica) { let at = "2026-10-26T09:00:00.000Z"; cotton_store::cursors::advance_cursor(&replica.driver, CURSOR_KEY, "w0001v0000000000000005", at).expect("an earlier build's cursor"); cotton_store::cursors::advance_cursor(&replica.driver, PASSED_KEY, "h0001.000000.m02:", at).expect("an earlier minting's record"); } /// A copy an earlier [`MINTING`] pulled holds a credential's receipt parked /// as an un-revocation, under the object's old author name as on the phone /// (27 Oct 2026): it pulls again from the start once, the row comes down, and /// the park ends — the same version of the same row, said again by the object. #[test] fn a_credential_an_earlier_minting_parked_comes_down_with_the_pull_again() { let (_dir, _layout, replica) = open_test_replica(); let first = ScriptedExchange::new([page(json!([todo("t-0", "Ring the bank", 2)]), 2, None)]); run_cycle(&replica.driver, &mut transport(&first, &replica), WORKSPACE, NOW).expect("a pass that knows the object's author"); parked_as_an_earlier_minting_made_it(&replica, "c-1", 2, &format!("{}{OBJECT_AUTHOR}", cotton_store::rejected::RETIRED_AUTHOR_PREFIX)); pulled_by_an_earlier_minting(&replica); let again = ScriptedExchange::new([page(json!([credential("c-1", 2, Value::Null)]), 6, None)]); run_cycle(&replica.driver, &mut transport(&again, &replica), WORKSPACE, NOW).expect("the pull again"); assert_eq!(again.nth(0).path, "/v1/sync?since=0&limit=5000&window=message:90", "an earlier minting's copy pulls again"); assert_eq!(revoked_at(&replica, "c-1"), Some(None), "the row came down"); let parked = replica.driver.all("SELECT tbl, reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); } /// RULE (walk, 27 Oct 2026): every table the personal kit ships is one this /// copy takes as a definition — the faceless ones its chats link into (a /// chat's contact, a message's reactions) as much as those with a face — and /// placing them all on the build's map refuses nothing, so a link the deck /// titles always finds the definition it is titled by. #[test] fn every_table_the_kit_ships_is_a_definition_the_copy_takes() { let manifest = std::env::var("CARGO_MANIFEST_DIR").expect("cargo test names the manifest directory"); let dir = std::path::Path::new(&manifest).join("../cotton-core/kits/personal/tables"); let mut tables = Vec::new(); for entry in std::fs::read_dir(&dir).expect("the kit's tables") { let path = entry.expect("an entry").path(); if path.extension().and_then(|e| e.to_str()) != Some("json") { continue; } tables.push(serde_json::from_str::(&std::fs::read_to_string(&path).expect("reads")).expect("a definition")); } let served = Value::Array(tables.clone()); let drawable: Vec = drawable_tables(&served).into_iter().map(|(id, _)| id).collect(); for faceless in ["message_contact", "message_contact_handle", "message_reaction", "email_participant"] { assert!(drawable.iter().any(|id| id == faceless), "{faceless} is taken"); } let placed: Vec<&Value> = tables.iter().filter(|table| drawable.iter().any(|id| table["id"] == id.as_str())).collect(); ObjectTables::personal().with_defined(placed).expect("every kit table places on the build's map"); } fn served_row(table: &str, id: &str, data: Value) -> Value { json!({ "table": table, "id": id, "version": 2, "owner": null, "data": data, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }) } fn count_of(replica: &crate::Replica, sql: &str) -> i64 { replica.driver.get(sql, &[]).expect("a read").and_then(|row| row.int("n")).unwrap_or_default() } /// RULE (walk, 27 Oct 2026; schema 142): the object decides, so a row it /// serves is never refused by a rule only the copy kept — a document filed on /// the object names no `status_changed_at` (no engine there moves its /// state), a Google event no `collection_id` (the object keeps no /// calendars), a session's note a `managed_by` with no `external_id`, and a /// money account the object's `kind` (`bank`, where the copy said /// `asset`). Each landed parked before, and the phone never showed it. #[test] fn rows_the_object_serves_land_without_the_rules_only_the_copy_kept() { let (_dir, _layout, replica) = open_test_replica(); let rows = json!([ served_row("document", "d-1", json!({ "title": "A synthetic statement", "original_name": "statement.pdf", "mime": "application/pdf", "byte_size": 1024, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "storage_path": "synthetic/documents/statement.pdf", "source": "agent", "doc_type": "other", })), served_row("event", "e-1", json!({ "title": "A synthetic meeting", "starts_at": "2026-10-28T09:00:00.000Z", "ends_at": "2026-10-28T10:00:00.000Z", "all_day": false, "sync_state": "synced", "on_google": true, "organizer_is_self": true, "account": "someone@example.com", "gcal_id": "synthetic-gcal-id", })), served_row("note", "n-1", json!({ "kind": "note", "title": "A synthetic session's note", "body": "Nothing real.", "author_kind": "agent", "author_label": "A synthetic session", "managed_by": "A synthetic session", "pinned": false, })), served_row("money_account", "a-1", json!({ "kind": "bank", "subtype": "bank", "name": "A synthetic account", "currency": "INR", "is_default": false, })), ]); let exchange = ScriptedExchange::new([page(rows, 2, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass"); let parked = replica.driver.all("SELECT tbl, reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_documents WHERE id = 'd-1' AND status_changed_at IS NULL"), 1); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_events WHERE id = 'e-1' AND collection_id IS NULL"), 1); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_notes WHERE id = 'n-1' AND managed_by IS NOT NULL AND external_id IS NULL"), 1); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_money_accounts WHERE id = 'a-1' AND kind = 'bank'"), 1); } /// RULE (schema 145): a media-only message whose bytes were left behind comes from the object with an empty body and its mark, and lands in the copy's rebuilt message table, never parked by the CHECK that table no longer has. #[test] fn a_media_only_message_with_an_empty_body_lands_from_the_object() { let (_dir, _layout, replica) = open_test_replica(); let rows = json!([ served_row("thread", "t-1", json!({ "kind": "dm", "title": "A synthetic chat", "archived": 0 })), served_row("message", "m-1", json!({ "thread_id": "t-1", "direction": "in", "channel": "whatsapp", "origin": "imported", "body": "", "media": [], "meta": { "mediaOnly": "image" }, "external_id": "synthetic-1", "sent_at": "2026-11-02T09:00:00.000Z", })), ]); let exchange = ScriptedExchange::new([page(rows, 2, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass"); let parked = replica.driver.all("SELECT tbl, reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!( count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE id = 'm-1' AND body = '' AND json_array_length(media) = 0 AND json_extract(meta, '$.mediaOnly') = 'image'"), 1 ); } /// The kit's own definition of `id`, as the object serves it. fn kit_table(id: &str) -> Value { let manifest = std::env::var("CARGO_MANIFEST_DIR").expect("cargo test names the manifest directory"); let path = std::path::Path::new(&manifest).join(format!("../cotton-core/kits/personal/tables/{id}.json")); serde_json::from_str(&std::fs::read_to_string(path).expect("the kit's table")).expect("a definition") } /// RULE (walk, 27 Oct 2026; schema 142): a built-in's storage is the store's /// code, never a definition's, so a table this build keeps under its engine /// lands from the object whatever rise its storage is — the object served /// 141's (`status_changed_at TEXT NOT NULL`) to a phone at 142, which refused /// Documents, Calendar, Notes and Money whole as "imported shapes cannot carry /// SQL fragments", retracted the definitions it held, and drew "This app /// cannot show these records" over each; the definition now lands, reads /// without a diagnostic, and the copy's own table is the one its rows fill. #[test] fn a_built_in_the_object_serves_under_another_rises_storage_lands_and_reads() { let (_dir, _layout, replica) = open_test_replica(); let replica = Arc::new(std::sync::Mutex::new(replica)); let copy = || replica.lock().expect("the copy"); let mut document = kit_table("document"); let storage = document["tables"].as_array_mut().expect("the kit's storage").iter_mut().find(|table| table["name"] == "cotton_documents").expect("the documents table"); let columns = storage["columns"].as_array_mut().expect("its columns"); let changed = columns.iter_mut().find(|column| column["name"] == "status_changed_at").expect("the state time"); changed["declaration"] = json!("\n status_changed_at TEXT NOT NULL"); let exchange = ScriptedExchange::new([page(json!([]), 2, None), served_with_tables(json!([document.clone()]), "e1")]); let mut object = transport(&exchange, ©()).taking_definitions(HeldDefinitions::new()); object.lend_file(Arc::clone(&replica) as Arc); run_cycle_paged(&replica, &mut object, WORKSPACE, NOW).expect("a pass"); let copy = copy(); assert_eq!(definition_of(©, "cotton_table_definitions", "document"), Some((document, 0)), "the object's definition is the copy's"); let _ = cotton_tools::definitions::take_definition_diagnostics(); let definitions = cotton_tools::definitions::table_definitions_from_driver(©.driver, WORKSPACE).expect("the copy's tables read"); assert!(cotton_tools::definitions::take_definition_diagnostics().is_empty(), "no definition is refused"); assert!(definitions.refused.is_empty() && definitions.fell_back.is_empty(), "{:?} {:?}", definitions.refused, definitions.fell_back); let read = definitions.definitions.iter().find(|definition| definition.id == "document").expect("Documents is drawn"); assert!(read.has_engine(), "under this build's engine"); let parked = copy.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); } /// RULE (walk, 27 Oct 2026; schema 143): an event is the database's, never /// its calendar's. The object keeps no calendars, yet 151 of the 154 events /// it served a phone named the one the owner's old Mac filed them in; the /// copy's foreign key to `cotton_collections` made that an owning reference, /// so each landed as its receipts alone — dormant, never parked — and the /// Calendar drew none of them. A served event naming a calendar this copy /// never holds is in its table, keeps the id it names, and nothing parks. #[test] fn an_event_naming_a_calendar_the_copy_never_holds_lands() { let (_dir, _layout, replica) = open_test_replica(); let rows = json!([ served_row("event", "e-1", json!({ "collection_id": "a-calendar-the-object-never-served", "title": "A synthetic meeting", "starts_at": "2026-10-30T09:00:00.000Z", "ends_at": "2026-10-30T10:00:00.000Z", "all_day": false, "sync_state": "synced", "on_google": true, "organizer_is_self": true, "account": "someone@example.com", "gcal_id": "synthetic-gcal-id", })), ]); let exchange = ScriptedExchange::new([page(rows, 2, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass"); let parked = replica.driver.all("SELECT tbl, reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_collections"), 0, "the copy holds no calendar"); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_events WHERE id = 'e-1' AND collection_id = 'a-calendar-the-object-never-served'"), 1); } // ── the first paint ──────────────────────────────────────────────────────── /// A `/v1/definitions` answer: invented tools, tables and boards. fn answer_of(tools: Value, tables: Value, boards: Value, etag: &str) -> Value { json!({"business": {"kind": "personal", "owner_person_id": "person-me"}, "tools": tools, "tables": tables, "flavour": {}, "boards": boards, "etag": etag}) } fn stamps_of(replica: &crate::Replica, table: &str) -> Vec { replica .driver .all(&format!("SELECT id, _hlc FROM {table} ORDER BY id"), &[]) .expect("a read") .into_iter() .map(|row| format!("{} {}", row.text("id").unwrap_or_default(), row.text("_hlc").unwrap_or_default())) .collect() } /// RULE (28 Oct 2026, the first paint): the answer `personal.connect` already holds is laid into the fresh copy as the object's own — every tool, table and board it serves this build draws, the made table's own table, Home as the object keeps it over the shell's and the owner it names — so the fan draws whole before any page of `/v1/sync`; the first pass asks the definitions, finds the copy holding them, writes nothing on them and holds the etag. #[test] fn the_objects_answer_is_laid_into_a_fresh_copy_and_the_first_pass_finds_it_held() { let (_dir, _layout, replica) = open_test_replica(); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan", "empty": ["garden"]}]}); let package = json!({"format_version": 1, "id": PACKAGE_TOOL, "name": "Personal", "tables": ["todo"]}); let answer = answer_of(json!([served_tool("garden", "Garden"), package]), json!([served_table("garden_bed", "Beds")]), json!([home]), "e1"); let laid = lay_served_definitions(&replica.path, WORKSPACE, &answer, START_MS).expect("laid"); assert_eq!(laid, Laid { tools: 1, tables: 1, boards: 1, refused: Vec::new() }); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "garden"), Some((served_tool("garden", "Garden"), 0))); assert_eq!(definition_of(&replica, "cotton_tool_definitions", PACKAGE_TOOL), None, "the package's own tool is no tool the phone draws"); assert_eq!(definition_of(&replica, "cotton_table_definitions", "garden_bed"), Some((served_table("garden_bed", "Beds"), 0))); assert!(holds_table(&replica, "cotton_garden_bed"), "the made table's own table is there before its rows"); assert_eq!(definition_of(&replica, "cotton_board_definitions", "home"), Some((home.clone(), 0)), "Home as the object keeps it"); let owner = replica.driver.get("SELECT owner_person_id FROM cotton_workspaces WHERE id = ?", &[rusqlite::types::Value::Text(WORKSPACE.into())]).expect("a read").expect("the row"); assert_eq!(owner.text("owner_person_id"), Some("person-me")); assert!(stamps_of(&replica, "cotton_tool_definitions").iter().any(|stamp| stamp.starts_with("garden ") && stamp.ends_with(":object")), "laid as the object's"); let before = (stamps_of(&replica, "cotton_tool_definitions"), stamps_of(&replica, "cotton_table_definitions"), stamps_of(&replica, "cotton_board_definitions")); let exchange = ScriptedExchange::new([page(json!([]), 3, None), Reply::ok(&answer.to_string())]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, &replica).taking_definitions(Arc::clone(&held)); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pass"); assert_eq!(exchange.nth(1).path, routes::DEFINITIONS, "the first pass asks the definitions"); assert_eq!(held.etag().as_deref(), Some("e1"), "and finds the copy holding them"); let after = (stamps_of(&replica, "cotton_tool_definitions"), stamps_of(&replica, "cotton_table_definitions"), stamps_of(&replica, "cotton_board_definitions")); assert_eq!(after, before, "nothing laid is written again"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); } /// RULE: what the object moved between the sign-in and the first pass is taken by that pass, as on any pass — a renamed tool is the object's new one, and one it stopped serving leaves. #[test] fn the_first_pass_takes_what_the_object_moved_since_the_answer_was_laid() { let (_dir, _layout, replica) = open_test_replica(); let laid = answer_of(json!([served_tool("garden", "Garden"), served_tool("seeds", "Seeds")]), json!([]), json!([]), "e1"); lay_served_definitions(&replica.path, WORKSPACE, &laid, START_MS).expect("laid"); let moved = answer_of(json!([served_tool("garden", "The garden")]), json!([]), json!([]), "e2"); let exchange = ScriptedExchange::new([page(json!([]), 3, None), Reply::ok(&moved.to_string())]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pass"); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "garden").map(|(d, _)| d["name"].clone()), Some(json!("The garden"))); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "seeds"), None, "a tool the object no longer serves leaves"); } /// RULE: only a copy that holds none of the object's definitions is laid; one that holds any is the passes' to keep, and a second answer writes nothing over it. #[test] fn a_copy_that_holds_the_objects_definitions_is_never_laid_over() { let (_dir, _layout, replica) = open_test_replica(); lay_served_definitions(&replica.path, WORKSPACE, &answer_of(json!([served_tool("garden", "Garden")]), json!([]), json!([]), "e1"), START_MS).expect("laid"); let before = stamps_of(&replica, "cotton_tool_definitions"); let again = lay_served_definitions(&replica.path, WORKSPACE, &answer_of(json!([served_tool("garden", "Another garden"), served_tool("seeds", "Seeds")]), json!([]), json!([]), "e2"), START_MS + 1).expect("asked"); assert_eq!(again, Laid::default()); assert_eq!(stamps_of(&replica, "cotton_tool_definitions"), before); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "seeds"), None); } /// The kit's files under `dir` (each folder's `file`, when one is named), in name order. fn kit_files(dir: &str, file: Option<&str>) -> Vec { let manifest = std::env::var("CARGO_MANIFEST_DIR").expect("cargo test names the manifest directory"); let root = std::path::Path::new(&manifest).join("../cotton-core/kits").join(dir); let mut paths: Vec = std::fs::read_dir(&root) .expect("the kit's folder") .map(|entry| entry.expect("an entry").path()) .map(|path| match file { Some(file) => path.join(file), None => path, }) .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("json")) .collect(); paths.sort(); paths.iter().map(|path| serde_json::from_str(&std::fs::read_to_string(path).expect("reads")).expect("a definition")).collect() } /// RULE: a fresh personal object's whole answer — the kit's tools, its tables and the shell's boards (apps/business `provision`) — lays into a copy as `personal.connect` makes it, nothing refused and every kit tool on the fan before any page. #[test] fn a_fresh_objects_whole_kit_lays_into_a_new_copy_and_every_kit_tool_is_on_the_fan() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("client").join("db").join("replica.db"); make_copy(&path, WORKSPACE, "owner-1", "device:phone", NOW, &Default::default(), Default::default()).expect("a copy"); let tools = kit_files("personal/tools", Some("manifest.json")); let answer = answer_of(Value::Array(tools.clone()), Value::Array(kit_files("personal/tables", None)), Value::Array(kit_files("shell/boards", None)), "kit"); let laid = lay_served_definitions(&path, WORKSPACE, &answer, START_MS).expect("laid"); assert!(laid.refused.is_empty(), "{:?}", laid.refused); assert_eq!(laid.tools, tools.len(), "every kit tool is drawn"); let db = cotton_store::driver::Driver::open(&path).expect("the copy"); let held: Vec = db.all("SELECT id FROM cotton_tool_definitions", &[]).expect("a read").into_iter().filter_map(|row| row.text("id").map(str::to_string)).collect(); for tool in &tools { let id = tool["id"].as_str().expect("an id"); assert!(held.iter().any(|held| held == id), "{id} is the copy's: {held:?}"); } let parked = db.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); } /// The object's event definition, as the personal kit ships it: it names the /// kind the object's calendar engine fills and a person may choose, its /// picture, and its people, none of which this build's `cotton_events` has. fn served_event() -> Value { serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/event.json")).expect("the kit's event") } fn gym(id: &str, version: i64) -> Value { json!({ "table": "event", "id": id, "version": version, "owner": null, "data": { "title": "Invented gym at 7", "starts_at": "2026-11-02T07:00:00.000Z", "all_day": false, "organizer_is_self": true, "kind": "gym", "people": ["p-asha"] }, "created_at": "2026-10-29T09:00:00.000Z", "updated_at": "2026-10-29T09:00:00.000Z", }) } /// RULE (owner, 29 Oct 2026): a served column the object's definition leaves the person (an event's kind, chosen on the fan) lands as the object wrote it and goes back with the copy's write, as the copy holds it, so the object sees the person's choice; one the definition keeps read-only (the people the engine links) never goes back. #[test] fn a_served_column_the_person_writes_lands_and_is_sent_with_the_row() { let (_dir, _layout, replica) = open_test_replica(); let replica = Arc::new(std::sync::Mutex::new(replica)); let copy = || replica.lock().expect("the copy"); let exchange = ScriptedExchange::new([page(json!([gym("e-1", 3)]), 3, None), served_with_tables(json!([served_event()]), "e1")]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, ©()).taking_definitions(Arc::clone(&held)); object.lend_file(Arc::clone(&replica) as Arc); run_cycle_paged(&replica, &mut object, WORKSPACE, NOW).expect("the pass"); let columns = table_columns(©(), "cotton_events"); for column in ["kind", "picture", "picture_photo_id", "people"] { assert!(columns.iter().any(|name| name == column), "the copy's events gained {column}: {columns:?}"); } let kind = || copy().driver.get("SELECT kind FROM cotton_events WHERE id = 'e-1'", &[]).expect("a read").and_then(|row| row.text("kind").map(str::to_string)); assert_eq!(kind().as_deref(), Some("gym"), "the object's kind landed"); copy().driver.run("UPDATE cotton_events SET kind = 'dinner' WHERE id = 'e-1'", &[]).expect("the person's choice"); let table = object.map(); let events = table.object("event").expect("events come"); let file = rusqlite::Connection::open(©().path).expect("the copy"); let sent = row_now(&file, events, "e-1").expect("a read").expect("the row"); assert_eq!(sent.get("kind"), Some(&json!("dinner")), "{sent:?}"); assert!(sent.contains_key("picture"), "the picture is the person's too: {sent:?}"); assert!(sent.get("people").is_none() && sent.get("title").is_some(), "the engine's people stay the object's: {sent:?}"); } /// The mood table as the object serves it: its emotions hold several values. fn served_project() -> Value { serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/project.json")).expect("the kit's project table") } fn project(id: &str, repos: Value, version: i64) -> Value { json!({ "table": "project", "id": id, "version": version, "owner": null, "data": {"slug": id, "name": "Invented project", "repos": repos}, "created_at": "2026-10-12T09:03:00.000Z", "updated_at": "2026-10-12T09:03:00.000Z", }) } fn repos_in(replica: &crate::Replica, id: &str) -> Option { replica .driver .get("SELECT repos FROM cotton_memory_projects WHERE id = ?", &[rusqlite::types::Value::Text(id.into())]) .expect("a read") .and_then(|row| row.text("repos").map(str::to_string)) } /// RULE: a column the object's definition holds several values in (a project's repos, `multiple`) that this build keeps as text lands as the list's JSON text, and goes back to the object as the list — the object's own shape, which its MCP demands (dev Worker, 29 Oct 2026: one seeded mood's `["calm"]` failed every pass at version 0, and nothing the object held reached a fresh phone). #[test] fn a_list_the_object_holds_lands_in_a_column_kept_as_text_and_goes_back_as_the_list() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([project("p-1", json!(["garden", "kiln"]), 3), todo("t-1", "Seen past the project", 4)]), 4, None), served_with_tables(json!([served_project()]), "e1"), Reply::ok(r#"{"version": 5, "changed": []}"#), page(json!([]), 5, None), served_with_tables(json!([served_project()]), "e1"), ]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, &replica).taking_definitions(Arc::clone(&held)); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass lays the page"); assert_eq!(repos_in(&replica, "p-1").as_deref(), Some(r#"["garden","kiln"]"#), "a list lands as its JSON text"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Seen past the project"), "the rest of the page lands with it"); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000004"), "the cursor moves past the page"); // An edit here goes to the object as the list. let mut patch = serde_json::Map::new(); patch.insert("repos".into(), json!(["kiln", "pottery"])); patch.insert("updated_at".into(), NOW.into()); let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(7))); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "name_repos".into(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::update("cotton_memory_projects", "p-1", patch)], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_760_000_000_000, &mut ids).expect("the replica's clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("a queued change"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass that posts it"); let act = body(&exchange.nth(2)); assert_eq!(act["args"]["table"], "project"); assert_eq!(act["args"]["data"]["repos"], json!(["kiln", "pottery"]), "the object is sent the list: {act}"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); } /// RULE: a row this copy cannot read at all (a value its column cannot hold) never stops the pass: it is parked with its sentence, as a row its table refuses is, the rest of the page lands and the cursor moves past it (dev Worker, 29 Oct 2026: one row this build could not read held a fresh phone at version 0 for good). #[test] fn a_row_this_copy_cannot_read_is_parked_and_the_rest_of_the_page_lands() { let (_dir, _layout, replica) = open_test_replica(); let mut unreadable = todo("t-0", "Never mind", 2); unreadable["data"]["title"] = json!({"words": "a title the column cannot hold"}); let exchange = ScriptedExchange::new([page(json!([unreadable, todo("t-1", "Lands anyway", 3)]), 4, None)]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass goes on"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Lands anyway"), "the rest of the page lands"); assert_eq!(todo_title(&replica, "t-0"), None); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000004"), "the cursor moves past the page"); let parked = replica.driver.all("SELECT tbl, row_id, direction, reason FROM _parked", &[]).expect("the parked rows"); assert_eq!(parked.len(), 1, "{parked:?}"); assert_eq!(parked[0].text("row_id"), Some("t-0")); assert_eq!(parked[0].text("direction"), Some("pull")); assert!(parked[0].text("reason").is_some_and(|reason| reason.contains("cotton_todos.title is not a value after its codec")), "parked with the fold's own sentence: {parked:?}"); } /// RULE: cutover-imported definitions have no object author, but the object /// still decides what a copy draws. The build's builtin shell stays; /// retraction never drops compiled storage. #[test] fn imported_definitions_not_served_leave_without_dropping_engine_columns() { let (_dir, _layout, replica) = open_test_replica(); let before = table_columns(&replica, "cotton_photos"); assert!(before.iter().any(|column| column == "caption")); for (store, id, definition) in [ ("cotton_table_definitions", "media", json!({"id":"media", "engine":"media", "columns":[], "card":{"face":"photo.print"}})), ("cotton_table_definitions", "photo", json!({"id":"photo", "engine":"media", "columns":[]})), ("cotton_tool_definitions", "imported_tool", served_tool("imported_tool", "Imported")), ("cotton_board_definitions", "imported_board", json!({"id":"imported_board", "parts":[]})), ] { replica.driver.run( &format!("INSERT OR REPLACE INTO {store} (id, workspace_id, definition, builtin, created_at, updated_at, _hlc) VALUES (?, ?, ?, 0, ?, ?, '1999999999999:0000:device:import')"), &[SqlValue::Text(id.into()), SqlValue::Text(WORKSPACE.into()), SqlValue::Text(definition.to_string()), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into())], ).expect("an imported definition newer than the object's clock"); } // The shell's tables as its kit names them, never listed here. let shell: Vec<&str> = cotton_core::kit::shell::SHELL_KIT_TABLES.iter().map(|(id, _)| *id).collect(); for &id in &shell { replica.driver.run( "INSERT OR REPLACE INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at, _hlc) VALUES (?, ?, ?, 1, ?, ?, '1999999999999:0000:device:build')", &[SqlValue::Text(id.into()), SqlValue::Text(WORKSPACE.into()), SqlValue::Text(json!({"id":id,"builtin":true,"columns":[]}).to_string()), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into())], ).expect("the build's builtin shell"); } let builtin_before: Vec<_> = shell.iter().map(|id| definition_of(&replica, "cotton_table_definitions", id)).collect(); let answer = answer_of(json!([]), json!([]), json!([]), "no-definitions"); lay_served_definitions(&replica.path, WORKSPACE, &answer, START_MS).expect("the object retracts every non-builtin unserved definition"); for (id, before) in shell.iter().zip(builtin_before) { assert_eq!(definition_of(&replica, "cotton_table_definitions", id), before, "the builtin {id} stays"); } for (store, id) in [("cotton_table_definitions", "media"), ("cotton_table_definitions", "photo"), ("cotton_tool_definitions", "imported_tool"), ("cotton_board_definitions", "imported_board")] { assert_eq!(definition_of(&replica, store, id), None, "{store}/{id}"); } assert_eq!(table_columns(&replica, "cotton_photos"), before, "compiled engine columns survive the drawn definition"); let again = lay_served_definitions(&replica.path, WORKSPACE, &answer, START_MS).expect("idempotent"); assert_eq!(again.tables + again.tools + again.boards, 0); } fn queue_definition(replica: &crate::Replica, table: &str, definition: Value) { let mut patch = serde_json::Map::new(); for (key, value) in [("workspace_id", json!(WORKSPACE)), ("definition", definition.clone()), ("builtin", json!(false)), ("created_at", json!(NOW)), ("updated_at", json!(NOW))] { patch.insert(key.into(), value); } let mut ids = crate::test_support::fresh_ids(); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").unwrap()), verb: "definition_test".into(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::create(table, definition["id"].as_str().unwrap(), patch)], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_790_000_000_000, &mut ids).unwrap(), &mut ids, cotton_store::mint::Held::Replica, ).expect("queued a definition"); } #[test] fn every_definition_table_posts_its_current_whole_and_a_retract_posts_remove() { let (_dir, _layout, replica) = open_test_replica(); for (table, kind) in DEFINITION_TABLES.iter().zip(["tool", "table", "board", "theme"]) { let definition = json!({"id": format!("synthetic_{kind}"), "name": "Synthetic"}); queue_definition(&replica, table, definition.clone()); let receipts = crate::unsent::receipts(&replica.driver).unwrap(); let op = &receipts.iter().find(|(op, _)| op.table == *table).unwrap().0; let exchange = ScriptedExchange::new([Reply::ok("{}"), Reply::ok("{}")]); let object = transport(&exchange, &replica); object.send_op(replica.driver.connection(), &ObjectTables::personal(), op, &[op]).unwrap().unwrap(); assert_eq!(body(&exchange.nth(0)), json!({"act":"definition", "args":{"kind":kind, "definition":definition, "base":null}})); let mut receipt = canonical::decode(op.receipt.as_bytes()).unwrap(); receipt.kind = Kind::Retract; receipt.fields.clear(); let retract = cotton_store::wire::from_receipt("synthetic-retract".into(), &receipt).unwrap(); object.send_op(replica.driver.connection(), &ObjectTables::personal(), &retract, &[&retract]).unwrap().unwrap(); assert_eq!(body(&exchange.nth(1)), json!({"act":"definition", "args":{"kind":kind, "remove":definition["id"], "base":null}})); } } #[test] fn a_definition_refused_for_good_is_written_down_once_and_never_resent() { let (_dir, layout, replica) = open_test_replica(); queue_definition(&replica, "cotton_tool_definitions", served_tool("synthetic_refused", "Synthetic")); let exchange = ScriptedExchange::new([ Reply::new(400, br#"{"code":"definition_refused","message":"the kit keeps this tool"}"#.to_vec()), page(json!([]), 3, None), page(json!([]), 3, None), ]); let mut object = transport(&exchange, &replica).discarding_to(layout.clone(), WORKSPACE.into()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("refused once"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("no second send"); assert_eq!(exchange.nth(1).method, "GET"); assert_eq!(exchange.nth(2).method, "GET"); let discarded = crate::unsent::discarded(&layout, WORKSPACE); assert_eq!(discarded.len(), 1); assert_eq!(discarded[0].changes.len(), 1); // The refusal's code only, never the object's words, which could quote a value (UNSENT HEAL 2 review, follow-up 2). assert_eq!(discarded[0].reasons.values().next().unwrap(), "definition_refused"); assert!(crate::unsent::receipts(&replica.driver).unwrap().is_empty()); } /// RULE: a definition the object cannot take just now (a 503) stalls /// nothing: its receipt stays queued, the pass goes on to pull, the pull /// leaves the copy's edit as it holds it (never the object's older one), /// and the next pass posts that whole edit again. #[test] fn a_definition_the_object_cannot_take_now_waits_while_the_pass_goes_on() { let (_dir, _layout, replica) = open_test_replica(); let definition = served_tool("synthetic_retry", "Synthetic"); queue_definition(&replica, "cotton_tool_definitions", definition.clone()); let older = served_tool("synthetic_retry", "Synthetic before"); let exchange = ScriptedExchange::new([ Reply::new(503, br#"{"code":"try_later","message":"try again"}"#.to_vec()), page(json!([]), 3, None), Reply::ok(&answer_of(json!([older]), json!([]), json!([]), "older").to_string()), Reply::ok("{}"), page(json!([]), 4, None), Reply::ok(&answer_of(json!([definition.clone()]), json!([]), json!([]), "taken").to_string()), ]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass goes on past a definition the object cannot take now"); assert_eq!(exchange.nth(1).method, "GET", "the rows are pulled"); assert_eq!(crate::unsent::receipts(&replica.driver).unwrap().iter().filter(|(op, _)| op.table == "cotton_tool_definitions").count(), 1); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "synthetic_retry").unwrap().0, definition, "the copy's edit stands"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("posted again"); assert_eq!(exchange.nth(3).method, "POST"); assert_eq!(body(&exchange.nth(0)), body(&exchange.nth(3))); assert!(crate::unsent::receipts(&replica.driver).unwrap().is_empty()); } #[test] fn a_definition_keeps_its_whole_edit_for_retry_after_a_401() { let (_dir, _layout, replica) = open_test_replica(); let definition = served_tool("synthetic_retry", "Synthetic"); queue_definition(&replica, "cotton_tool_definitions", definition.clone()); let exchange = ScriptedExchange::new([ Reply::new(401, br#"{"code":"try_later","message":"try again"}"#.to_vec()), Reply::ok("{}"), page(json!([]), 3, None), Reply::ok(&answer_of(json!([definition.clone()]), json!([]), json!([]), "retry").to_string()), ]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); assert!(run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).is_err()); assert_eq!(crate::unsent::receipts(&replica.driver).unwrap().iter().filter(|(op, _)| op.table == "cotton_tool_definitions").count(), 1); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "synthetic_retry").unwrap().0, definition); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("retried before any definitions pull"); assert_eq!(body(&exchange.nth(0)), body(&exchange.nth(1))); assert_eq!(exchange.nth(1).method, "POST"); assert!(crate::unsent::receipts(&replica.driver).unwrap().is_empty()); } #[test] fn adopt_posts_definitions_after_rows_even_when_the_definition_was_made_first() { let (_dir, layout, replica) = open_test_replica(); queue_definition(&replica, "cotton_tool_definitions", served_tool("synthetic_adopt", "Synthetic")); queue_one_change(&replica, "Synthetic-row"); let exchange = ScriptedExchange::new([Reply::ok("{}"), Reply::ok("{}")]); let object = transport(&exchange, &replica); let rekey = Rekey::default(); let into = AdoptInto { layout: &layout, object_id: WORKSPACE, served_tables: &[], rekey: &rekey, sends: &|table, _| table != "cotton_authors", at: NOW }; let sent = object.adopt_writes(&into, &mut |_, _| true).unwrap(); assert_eq!(sent.refused, 0); assert_eq!(body(&exchange.nth(0))["act"], "create"); assert_eq!(body(&exchange.nth(1))["act"], "definition"); assert!(AdoptLog::beside(&replica.path).read().in_flight.is_none()); } /// RULE (launch-story walk, 22 Nov 2026): a row made before sign-in that names a row made after it here (a scene and /// the place chosen for it later) is not lost at the backup. The object refuses its link while the row it names is /// still to come (`bad_link`); the row waits for the rest of the queue and is posted again after it, and nothing is /// written down as discarded. #[test] fn adopt_posts_a_row_again_after_the_row_it_names() { let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "Scene"); queue_one_change(&replica, "Place"); let exchange = ScriptedExchange::new([ Reply::new(400, br#"{"code":"bad_link","message":"story_scene.place names no story_place"}"#.to_vec()), Reply::ok("{}"), Reply::ok("{}"), ]); let object = transport(&exchange, &replica); let rekey = Rekey::default(); let into = AdoptInto { layout: &layout, object_id: WORKSPACE, served_tables: &[], rekey: &rekey, sends: &|table, _| table != "cotton_authors", at: NOW }; let sent = object.adopt_writes(&into, &mut |_, _| true).unwrap(); assert_eq!(sent.refused, 0, "nothing refused for good"); assert_eq!(sent.delivered, 2); // Whichever went first was refused its link: it is posted again, last, after the other. let first = body(&exchange.nth(0))["args"]["id"].clone(); assert_ne!(body(&exchange.nth(1))["args"]["id"], first); assert_eq!(body(&exchange.nth(2))["act"], "create"); assert_eq!(body(&exchange.nth(2))["args"]["id"], first, "the refused row is posted again after the row it names"); assert!(crate::unsent::discarded(&layout, WORKSPACE).is_empty()); assert!(crate::unsent::receipts(&replica.driver).unwrap().iter().all(|(op, _)| op.table != "cotton_todos"), "every write of the rows is let go"); } /// A link the object still refuses once nothing more lands is written down, once, the row kept on this phone, and the adopt ends. #[test] fn adopt_writes_down_a_link_still_missing_when_nothing_more_lands() { let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "Orphan"); let refused = || Reply::new(400, br#"{"code":"bad_link","message":"story_line.scene names no story_scene"}"#.to_vec()); let exchange = ScriptedExchange::new([refused(), refused()]); let object = transport(&exchange, &replica); let rekey = Rekey::default(); let into = AdoptInto { layout: &layout, object_id: WORKSPACE, served_tables: &[], rekey: &rekey, sends: &|table, _| table != "cotton_authors", at: NOW }; let sent = object.adopt_writes(&into, &mut |_, _| true).unwrap(); assert_eq!(sent.refused, 1); assert_eq!(crate::unsent::discarded(&layout, WORKSPACE).len(), 1); assert!(crate::unsent::receipts(&replica.driver).unwrap().iter().all(|(op, _)| op.table != "cotton_todos"), "every write of the rows is let go"); // Still refused after it was posted again: the row is kept on this phone as it stood, never thrown away. let kept = crate::unsent::kept_rows(&layout, WORKSPACE); assert_eq!(kept.len(), 1, "{kept:?}"); assert_eq!(kept[0].row_id, "todo-Orphan"); assert_eq!(kept[0].data["title"], "Orphan"); assert_eq!(kept[0].why, "story_line.scene names no story_scene"); } /// RULE (coordinator, 22 Nov 2026): a row a backup kept is not lost by staying out of sight. A launch's first pass /// posts it again, and so does a pass that moved anything (the row it names may have come); still refused, it stays; /// once the object takes it, it leaves the file. #[test] fn a_kept_row_lands_once_the_row_it_names_has_come() { let (_dir, layout, replica) = open_test_replica(); crate::unsent::keep_row(&layout, WORKSPACE, crate::unsent::KeptRow { table: "todo".into(), row_id: "todo-kept".into(), data: json!({"title": "Kept", "status": "open"}), why: "todo.project names no project".into(), at: NOW.into(), }).unwrap(); let exchange = ScriptedExchange::new([ page(json!([]), 3, None), Reply::new(400, br#"{"code":"bad_link","message":"todo.project names no project"}"#.to_vec()), page(json!([person("person-new", "Invented Arrival", 4)]), 4, None), Reply::ok("{}"), ]); let mut object = transport(&exchange, &replica).discarding_to(layout.clone(), WORKSPACE.into()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pass"); assert_eq!(body(&exchange.nth(1))["act"], "create", "a launch's first pass posts the kept row again"); assert_eq!(body(&exchange.nth(1))["args"]["id"], "todo-kept"); assert_eq!(crate::unsent::kept_rows(&layout, WORKSPACE).len(), 1, "still refused: kept"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass that brings a row"); assert_eq!(body(&exchange.nth(3))["act"], "create", "posted again after a pass that moved something"); assert_eq!(body(&exchange.nth(3))["args"]["data"]["title"], "Kept"); assert!(crate::unsent::kept_rows(&layout, WORKSPACE).is_empty(), "taken: it leaves the file"); } /// RULE: a row the backup kept because the object already holds its own version is never posted again: the object's /// version stands, and the phone's stays in the file as it was written. #[test] fn a_kept_row_the_object_holds_is_never_posted_over_its_version() { let (_dir, layout, replica) = open_test_replica(); crate::unsent::keep_row(&layout, WORKSPACE, crate::unsent::KeptRow { table: "todo".into(), row_id: "todo-held".into(), data: json!({"title": "The phone's version", "status": "open"}), why: OBJECT_STANDS.into(), at: NOW.into(), }).unwrap(); let exchange = ScriptedExchange::new([page(json!([]), 3, None)]); let mut object = transport(&exchange, &replica).discarding_to(layout.clone(), WORKSPACE.into()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pass"); assert!(exchange.seen().iter().all(|seen| !["create", "update"].contains(&serde_json::from_slice::(&seen.body).unwrap_or(Value::Null)["act"].as_str().unwrap_or_default())), "nothing is posted over the object's version"); let kept = crate::unsent::kept_rows(&layout, WORKSPACE); assert_eq!(kept.len(), 1, "it stays on this phone: {kept:?}"); assert_eq!(kept[0].data["title"], "The phone's version"); } #[test] fn a_conflicted_definition_is_replaced_by_the_objects_next_definitions_pass() { let (_dir, _layout, replica) = open_test_replica(); let base = served_tool("synthetic_conflict", "Before"); lay_served_definitions(&replica.path, WORKSPACE, &answer_of(json!([base.clone()]), json!([]), json!([]), "base"), START_MS).unwrap(); queue_definition(&replica, "cotton_tool_definitions", served_tool("synthetic_conflict", "Phone")); let authority = served_tool("synthetic_conflict", "Object"); let exchange = ScriptedExchange::new([ Reply::ok(&json!({"conflict":true,"definition":authority}).to_string()), page(json!([]), 9, None), Reply::ok(&answer_of(json!([authority.clone()]), json!([]), json!([]), "object").to_string()), ]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).unwrap(); assert_eq!(body(&exchange.nth(0))["args"]["base"], base); assert_eq!(definition_of(&replica, "cotton_tool_definitions", "synthetic_conflict").map(|(value, _)| value), Some(authority)); } #[test] fn themes_are_laid_at_sign_in_and_follow_the_objects_next_definitions() { let (_dir, _layout, replica) = open_test_replica(); let mut first = answer_of(json!([]), json!([]), json!([]), "theme_one"); first["themes"] = json!([{"id":"synthetic_theme", "family":"paper"}]); lay_served_definitions(&replica.path, WORKSPACE, &first, START_MS).unwrap(); assert_eq!(definition_of(&replica, "cotton_theme_definitions", "synthetic_theme").unwrap().0, first["themes"][0]); let mut next = first.clone(); next["themes"][0]["family"] = json!("ink"); next["etag"] = json!("theme_two"); let exchange = ScriptedExchange::new([page(json!([]), 4, None), Reply::ok(&next.to_string())]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).unwrap(); assert_eq!(definition_of(&replica, "cotton_theme_definitions", "synthetic_theme").unwrap().0, next["themes"][0]); } // ── a first pull carries its small tables first ──────────────────────────── /// A page token as the object makes one (`apps/business/src/business.ts` /// `writeCursor`): base64url of the pass's JSON, here naming the small tables /// a pass from nothing carries first — about a hundred on the owner's object, /// so a token of a couple of kilobytes. fn object_token(pass: Value) -> String { use base64::Engine as _; base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(pass.to_string()) } fn person(id: &str, name: &str, version: i64) -> Value { json!({ "table": "person", "id": id, "version": version, "owner": null, "data": {"full_name": name}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }) } fn person_name(replica: &crate::Replica, id: &str) -> Option { replica .driver .get("SELECT full_name FROM cotton_people WHERE id = ?", &[rusqlite::types::Value::Text(id.into())]) .expect("a read") .and_then(|row| row.text("full_name").map(str::to_string)) } fn sync_figures(progress: &SyncProgress) -> (Value, Value, Value) { let columns = progress.state().columns(); (columns["sync_rows_total"].clone(), columns["sync_rows_done"].clone(), columns["caught_up"].clone()) } /// RULE (owner, 2 Nov 2026): a fresh install holds the small tables whole in its first minutes, then the big ones. The object orders the pass; the phone holds its token as it came, resumes from it after a failed page and a relaunch, and its row's figures say what each answer said across the two runs, rows of later versions landing before earlier ones. #[test] fn a_first_pull_small_tables_first_holds_the_objects_token_resumes_from_it_and_counts_across_the_runs() { let (_dir, _layout, replica) = open_test_replica(); let small: Vec = (0..100).map(|i| format!("synthetic_small_table_{i:03}")).chain(["person".to_string()]).collect(); let figures = json!({"total": 5, "pass": 5, "passLive": 5, "sent": 2, "sentLive": 2}); let first_token = object_token(json!({"since": 0, "upto": 901, "limit": 5000, "windows": [], "small": small, "floor": null, "after": {"version": 901, "table": "person", "id": "p-2"}, "figures": figures})); let second_token = object_token(json!({"since": 0, "upto": 901, "limit": 5000, "windows": [], "small": small, "floor": null, "after": {"version": 4, "table": "todo", "id": "t-2"}, "figures": figures})); assert!(first_token.len() > 2_000, "a token of the owner's size: {}", first_token.len()); // The first page: the small run, people written late (versions 900 and 901). let exchange = ScriptedExchange::new([ standing(json!([person("p-1", "Asha", 900), person("p-2", "Bela", 901)]), 0, Some(&first_token), json!(null), 5, 3), Reply::json(500, r#"{"code": "internal", "message": "the object failed"}"#), ]); let progress = progress_at(&Arc::new(Mutex::new(START_MS))); assert!(run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).is_err(), "the second page fails"); assert_eq!(person_name(&replica, "p-1").as_deref(), Some("Asha"), "the small run's rows landed with their page"); assert_eq!(cursor(&replica), Some(page_cursor(0, 0, 1, &first_token)), "the copy holds the object's token as it came"); assert_eq!(exchange.nth(1).path, format!("/v1/sync?cursor={first_token}")); assert_eq!(sync_figures(&progress), (json!(5), json!(2), json!(false))); // A relaunch: a new transport and progress go on from the held token, into the big run (earlier versions). let exchange = ScriptedExchange::new([ standing(json!([todo("t-1", "One", 3), todo("t-2", "Two", 4)]), 0, Some(&second_token), json!(null), 5, 1), standing(json!([todo("t-3", "Three", 5)]), 901, None, json!(null), 5, 0), ]); let progress = progress_at(&Arc::new(Mutex::new(START_MS))); run_cycle(&replica.driver, &mut reporting(&exchange, &replica, &progress), WORKSPACE, NOW).expect("the pass ends"); assert_eq!(exchange.nth(0).path, format!("/v1/sync?cursor={first_token}"), "the pass goes on from the page it held"); assert_eq!(exchange.nth(1).path, format!("/v1/sync?cursor={second_token}")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000901"), "the pass ends on the object's version"); for (id, title) in [("t-1", "One"), ("t-2", "Two"), ("t-3", "Three")] { assert_eq!(todo_title(&replica, id).as_deref(), Some(title)); } assert_eq!(person_name(&replica, "p-2").as_deref(), Some("Bela")); assert_eq!(sync_figures(&progress), (json!(5), json!(5), json!(true))); } /// RULE (owner, 2 Nov 2026): a copy mid-pull on a token the object made before small tables came first sends it as it holds it, and the pass the object goes on with from there ends where it would have. #[test] fn a_copy_mid_pull_on_an_old_token_sends_it_as_held_and_the_pass_ends() { let (_dir, _layout, replica) = open_test_replica(); let old = object_token(json!({"since": 0, "upto": 12, "limit": 5000, "windows": [], "after": {"version": 3, "table": "todo", "id": "t-1"}, "figures": {"total": 3, "pass": 3, "passLive": 3, "sent": 1, "sentLive": 1}})); assert!(cotton_store::cursors::advance_cursor(&replica.driver, CURSOR_KEY, &page_cursor(0, 0, 4, &old), NOW).expect("the cursor")); let exchange = ScriptedExchange::new([page(json!([person("p-1", "Asha", 12), todo("t-2", "Two", 5)]), 12, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("the pass ends"); assert_eq!(exchange.only().path, format!("/v1/sync?cursor={old}")); assert_eq!(person_name(&replica, "p-1").as_deref(), Some("Asha")); assert_eq!(todo_title(&replica, "t-2").as_deref(), Some("Two")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000012")); } // ── children served before their parents ─────────────────────────────────── /// A money row naming account `account`, as a sync page carries it. fn movement_of(id: &str, account: &str, version: i64) -> Value { let mut row = movement(id, version, 120_000, 95_000); row["data"]["account_id"] = json!(account); row } /// MEASURE (ignored): `n` money rows served in pages of 5,000 BEFORE the /// `accounts` they name (the order the owner's copy filled in on 3 Nov 2026), /// then the page of accounts; each pass is one page, timed. The copy holds /// the balance columns, so the money engine runs as on a phone. fn time_children_before_parents(n: usize, accounts: usize) -> (Vec, std::time::Duration, usize) { let (_dir, _layout, replica) = open_test_replica(); hold_defined_columns(&replica.driver, [&served_transaction()]).expect("the balance columns"); let rows: Vec = (0..n).map(|i| movement_of(&format!("m-{i:06}"), &format!("a-{:04}", i % accounts), 3)).collect(); let mut times = Vec::new(); for chunk in rows.chunks(5_000) { let exchange = ScriptedExchange::new([page(json!(chunk), 3, None)]); let started = std::time::Instant::now(); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass"); times.push(started.elapsed()); } assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM _parked WHERE direction = 'pull'") as usize, n, "every money row waits for its account"); let parents: Vec = (0..accounts) .map(|i| served_row("money_account", &format!("a-{i:04}"), json!({"kind": "bank", "subtype": "bank", "name": format!("Invented account {i}"), "currency": "INR", "is_default": false}))) .collect(); let exchange = ScriptedExchange::new([page(json!(parents), 4, None)]); let tally = cotton_store::held::tally(); let started = std::time::Instant::now(); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("the accounts' pass"); let healed = started.elapsed(); let folds = tally.done().folds; assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM _parked"), 0, "every money row landed with its account"); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_money_transactions") as usize, n); (times, healed, folds) } #[test] #[ignore = "a measurement: cargo test -p cotton-client measure_children_before_parents -- --ignored --nocapture"] fn measure_children_before_parents() { for n in [1_000, 5_000, 10_000] { let (pages, healed, _) = time_children_before_parents(n, 20); eprintln!( "N={n}: refusing pages {:?}; the accounts' page {:.2}s", pages.iter().map(|t| format!("{:.2}s", t.as_secs_f64())).collect::>(), healed.as_secs_f64() ); } } /// RULE (3 Nov 2026): money rows served before their accounts park, and the /// page that brings the accounts lands all of them in seconds — one fold for /// the lot, so the money engine works the book out once, never once per row. /// Measured on a Mac (debug): 2,000 rows healed in about a second; folded one /// by one they took 9.8 s at 1,000 and 230 s at 5,000. The budget was ten /// 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: /// 12.4 s there, and the same 6 s at 1,000 for this code as for e1c470e52's. /// So the healing page is held to its own pass's other page, timed on the /// same machine in the same run: the page that served the rows. Linear, the /// two cost about the same (1.0 to 1.4 times on the box); folded per row, the /// heal is tens of times the page. And it is folded in two: the page, then /// every row it unblocked. #[test] fn money_rows_served_before_their_accounts_land_with_them_in_seconds() { let (pages, healed, folds) = time_children_before_parents(2_000, 20); eprintln!("2,000 money rows: served in {:?}, healed in {healed:?} in {folds} fold(s)", pages[0]); assert_eq!(folds, 2, "the accounts' page, then every money row it unblocked in one fold"); assert!(healed < pages[0] * 4, "the accounts' page took {healed:?}, the page that served the rows {:?}", pages[0]); } /// One synthetic row of each of ten tables, by its index. fn row_of_ten(i: usize) -> Value { let id = format!("r-{i:06}"); match i % 10 { 0 => todo(&id, "An invented chore", 2), 1 => served_row("note", &id, json!({"kind": "note", "title": "An invented note", "body": "Nothing real.", "pinned": false})), 2 => served_row("event", &id, json!({"title": "An invented meeting", "starts_at": "2026-10-28T09:00:00.000Z", "ends_at": "2026-10-28T10:00:00.000Z", "all_day": false})), 3 => served_row("document", &id, json!({ "title": "An invented statement", "original_name": "statement.pdf", "mime": "application/pdf", "byte_size": 1024, "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "storage_path": "synthetic/documents/statement.pdf", "source": "agent", "doc_type": "other", })), 4 => served_row("money_account", &id, json!({"kind": "bank", "subtype": "bank", "name": "An invented account", "currency": "INR", "is_default": false})), 5 => movement_of(&id, &format!("r-{:06}", i - 1), 2), 6 => served_row("person", &id, json!({"full_name": "An Invented Person"})), 7 => served_row("location", &id, json!({"name": "An invented place"})), 8 => served_row("goal", &id, json!({"title": "An invented goal"})), _ => served_row("mood", &id, json!({"at": "2026-10-20T09:00:00.000Z", "local_day": "2026-10-20"})), } } /// Commits and wall clock across `work`, on this thread. fn commits_in(work: impl FnOnce() -> T) -> (T, u64, std::time::Duration) { let (before, started) = (cotton_store::Driver::thread_commits(), std::time::Instant::now()); let made = work(); (made, cotton_store::Driver::thread_commits() - before, started.elapsed()) } /// An app manifest born with every kit tool, the way Cotton's is: built here /// rather than read from apps/, so the crate's tests stay within the crate /// (rust-crate-local-reads) and measure the core under a whole genesis set, /// not one app's shipped file. /// /// People first, as Cotton's own manifest puts it: Birthdays, Ahead and the /// other tools that read a person install after the table they read, and a /// tool installed before it is refused ("Install its tool first"). fn whole_kit_manifest() -> Value { let mut tools = cotton_core::kit::ids(); tools.sort_by_key(|id| *id != "people"); json!({ "genesis": "personal", "tools": tools }) } /// MEASURE (ignored): commits and time of a fresh copy, of one page of 200 /// and of 2,000 rows, and of a catch-up of 5,000 rows across ten tables in /// one page, on this machine (connect-commits, 7 Nov 2026). #[test] #[ignore = "a measurement: cargo test -p cotton-client measure_commits_per_page -- --ignored --nocapture"] fn measure_commits_per_page() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("client").join("db").join("replica.db"); let ((), commits, took) = commits_in(|| make_copy(&path, WORKSPACE, "owner-1", "device:phone", NOW, &Default::default(), Default::default()).expect("a copy")); eprintln!("make_copy (no genesis tools): {commits} commits in {took:?}"); let manifest = whole_kit_manifest(); let tools = cotton_core::genesis::GenesisTools::of(Some(&manifest)).expect("Cotton's genesis set"); eprintln!("Cotton's genesis set: {} packages", tools.packages().len()); let with = dir.path().join("with").join("replica.db"); let ((), commits, took) = commits_in(|| make_copy(&with, WORKSPACE, "owner-1", "device:phone", NOW, &tools, Default::default()).expect("a copy")); eprintln!("make_copy (Cotton's genesis tools): {commits} commits in {took:?}"); for n in [200usize, 2_000] { let (_dir, _layout, replica) = open_test_replica(); let rows: Vec = (0..n).map(|i| todo(&format!("t-{i:06}"), "An invented chore", 2)).collect(); let exchange = ScriptedExchange::new([page(json!(rows), 2, None)]); let (_, commits, took) = commits_in(|| run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass")); eprintln!("one page of {n} todos: {commits} commits in {took:?}"); } let (_dir, _layout, replica) = open_test_replica(); hold_defined_columns(&replica.driver, [&served_transaction()]).expect("the balance columns"); let rows: Vec = (0..5_000).map(row_of_ten).collect(); let exchange = ScriptedExchange::new([page(json!(rows), 2, None)]); let (_, commits, took) = commits_in(|| run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass")); eprintln!("5,000 rows across ten tables: {commits} commits in {took:?}; parked {}", count_of(&replica, "SELECT COUNT(*) AS n FROM _parked")); } /// MEASURE (ignored): each step of a fresh copy, timed, with the share spent /// inside SQLite. #[test] #[ignore = "a measurement: cargo test -p cotton-client measure_make_copy_steps -- --ignored --nocapture"] fn measure_make_copy_steps() { // MEASURE_ROW_BY_ROW=1: the same copy with no batch, for a before/after. if std::env::var("MEASURE_ROW_BY_ROW").is_ok() { eprintln!("row by row"); return cotton_store::fold::row_by_row_for_tests(make_copy_steps); } make_copy_steps() } fn make_copy_steps() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("replica.db"); let at = chrono::DateTime::parse_from_rfc3339(NOW).expect("an instant").with_timezone(&chrono::Utc); let started = std::time::Instant::now(); let shipped = cotton_core::toolkits::shipped_kit_tools().len(); eprintln!("shipped_kit_tools ({shipped}): {:?}", started.elapsed()); let started = std::time::Instant::now(); let _ = cotton_core::kit::package("people"); eprintln!("kit::package(people): {:?}", started.elapsed()); let started = std::time::Instant::now(); let db = cotton_store::driver::Driver::open(&path).expect("a file"); // Written with no syncs and sealed once at the end, as make_copy writes. db.exec("PRAGMA synchronous = OFF").expect("unsynced"); let step = |name: &str, started: &mut std::time::Instant, db: &cotton_store::driver::Driver| { eprintln!("{name}: {:?} (inside SQLite {:?} so far)", started.elapsed(), db.time_inside()); for (span, took, count) in cotton_store::spans::take().into_iter().filter(|(_, took, _)| took.as_millis() >= 20) { eprintln!(" span {span}: {took:?} over {count}"); } *started = std::time::Instant::now(); }; let mut started = started; step("open", &mut started, &db); let meta = cotton_store::meta::Meta { workspace_id: WORKSPACE.into(), owner_id: "owner-1".into(), device_id: "device:phone".into(), last_server_seq: 0, last_hlc: None }; cotton_store::create::create_workspace(&db, &meta).expect("a schema"); step("create_workspace", &mut started, &db); let seed = cotton_store::birth::WorkspaceSeed { workspace_id: WORKSPACE, owner_id: "owner-1", name: None, kind: "personal", relay: None }; let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SystemRandom)); cotton_store::birth::seed_workspace_row(&db, NOW, at.timestamp_millis(), &seed, &mut ids, cotton_store::mint::Held::Served).expect("a seed"); step("seed_workspace_row", &mut started, &db); db.watch_statements(); cotton_tools::presentation::write_shell(&db, at, Arc::new(cotton_tools::random::SystemRandom), cotton_store::mint::Held::Served).expect("the shell"); step(&format!("write_shell ({} statements)", db.statements_seen().len()), &mut started, &db); for (took, sql) in db.times_by_statement().into_iter().take(12) { eprintln!(" {took:?} {}", sql.chars().take(140).collect::()); } // MEASURE_COUNTS=1: write_shell's statements by how often each ran. if std::env::var("MEASURE_COUNTS").is_ok() { let mut counts: std::collections::BTreeMap = Default::default(); for sql in db.statements_seen() { *counts.entry(sql).or_default() += 1; } let mut counts: Vec<_> = counts.into_iter().collect(); counts.sort_by(|a, b| b.1.cmp(&a.1)); for (sql, n) in counts.into_iter().take(45) { eprintln!(" x{n} {}", sql.chars().take(150).collect::()); } } let manifest = whole_kit_manifest(); let tools = cotton_core::genesis::GenesisTools::of(Some(&manifest)).expect("Cotton's genesis set"); db.watch_statements(); // The whole set in one call, as make_copy installs it: each tool its own // add and commit, the computed index worked out once after the last. cotton_tools::kit::install_genesis_tools(&db, at, Arc::new(cotton_tools::random::SystemRandom), cotton_store::mint::Held::Served, &tools).expect("the genesis set"); step(&format!("{} genesis tools ({} statements)", tools.packages().len(), db.statements_seen().len()), &mut started, &db); super::seal_birth(&db).expect("sealed"); step("seal_birth", &mut started, &db); for (took, sql) in db.times_by_statement().into_iter().take(8) { eprintln!(" {took:?} {}", sql.chars().take(140).collect::()); } } /// Every row of a fresh copy as text, table by table, rows sorted: what two /// copies are compared by. `fresh_decode` installs each genesis package from /// its compiled files decoded on the spot, as add_tool did before the kit was /// decoded once per process; otherwise through add_tool as make_copy does. /// Ids and keys come from seeded generators, so two makes write the same rows. fn copy_rows(fresh_decode: bool) -> String { copy_rows_signed(fresh_decode, false) } /// [`copy_rows`], `signed` by a device key as the phone's own birth /// (`start::make_file`) signs every receipt it mints (Ed25519: the same bytes /// sign the same way). fn copy_rows_signed(fresh_decode: bool, signed: bool) -> String { let dir = tempfile::tempdir().expect("a folder"); let mut db = cotton_store::driver::Driver::open(dir.path().join("replica.db")).expect("a file"); if signed { db = db.sharing_signer(cotton_store::signed::SignerSlot::filled(Arc::new(cotton_store::signed::KeySigner::of_seed(5)))); } let at = chrono::DateTime::parse_from_rfc3339(NOW).expect("an instant").with_timezone(&chrono::Utc); let meta = cotton_store::meta::Meta { workspace_id: WORKSPACE.into(), owner_id: "owner-1".into(), device_id: "device:phone".into(), last_server_seq: 0, last_hlc: None }; cotton_store::create::create_workspace(&db, &meta).expect("a schema"); let seed = cotton_store::birth::WorkspaceSeed { workspace_id: WORKSPACE, owner_id: "owner-1", name: None, kind: "personal", relay: None }; let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(7))); let held = cotton_store::mint::Held::Served; cotton_store::birth::seed_workspace_row(&db, NOW, at.timestamp_millis(), &seed, &mut ids, held).expect("a seed"); let random: Arc = Arc::new(cotton_tools::synthetic::SeededRandom::new(11)); cotton_tools::presentation::write_shell(&db, at, random.clone(), held).expect("the shell"); let manifest = whole_kit_manifest(); let tools = cotton_core::genesis::GenesisTools::of(Some(&manifest)).expect("Cotton's genesis set"); if fresh_decode { let file = cotton_store::file_identity::read_file_identity(&db).expect("a read").expect("an identity"); let services = cotton_tools::mcp::dispatch::ToolServices::none(); let audit = |_: &str, _: &str| {}; for id in tools.packages() { let actor = cotton_store::mint::Actor::DeviceJob(cotton_store::mint::JobName::named("kit").expect("a job")); let mut ctx = cotton_tools::mcp::dispatch::Ctx::for_worker(&db, &file, "owner-1", actor, "kit", at, random.clone(), &services, &audit).held_as(held); let bytes = cotton_core::kit::archive(id).expect("a kit tool").expect("its archive"); let package = cotton_core::definitions::package::decode_package(&bytes).expect("it decodes"); cotton_tools::mcp::handlers::tool_packages::install_package(&mut ctx, &package.package, cotton_tools::mcp::handlers::tool_packages::Door::Import, false).expect("installed"); ctx.commit().expect("committed"); } } else { cotton_tools::kit::install_genesis_tools(&db, at, random, held, &tools).expect("the genesis set"); } let tables = db.all("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", &[]).expect("the tables"); let mut out = String::new(); for table in tables.iter().filter_map(|row| row.text("name")) { let mut rows: Vec = db.all(&format!("SELECT * FROM \"{table}\""), &[]).expect("the rows") .iter().map(|row| format!("{:?}", row.columns())).collect(); rows.sort(); out.push_str(&format!("== {table} ({})\n", rows.len())); for row in rows { out.push_str(&row); out.push('\n'); } } out } /// RULE (copy-installer-cpu, 7 Nov 2026): the kit is decoded once per process /// and shared, and a copy made over the shared shapes is the copy the compiled /// files make decoded afresh, row for row: definitions, the shell's rows, every /// table. A second make in the same process (the caches warm) is the same too. #[test] fn a_copy_made_over_the_shared_kit_is_the_copy_a_fresh_decode_makes() { let shared = copy_rows(false); assert!(shared.contains("== cotton_tool_definitions"), "the copy holds its tools"); let fresh = copy_rows(true); let again = copy_rows(false); let first_difference = |a: &str, b: &str| a.lines().zip(b.lines()).find(|(x, y)| x != y).map(|(x, y)| format!("{x}\n vs\n{y}")); assert!(shared == fresh, "shared vs fresh decode: {:?}", first_difference(&shared, &fresh)); assert!(shared == again, "a second make: {:?}", first_difference(&shared, &again)); } /// RULE (copy-installer-fold, 8 Nov 2026): the shell's lines and the genesis /// set land as one batch of rows (`cotton_store::fold::as_one_batch`), and a /// copy born so is the copy born row by row, byte for byte, every table. #[test] fn a_copy_born_by_batch_is_the_copy_born_row_by_row() { let first_difference = |a: &str, b: &str| a.lines().zip(b.lines()).find(|(x, y)| x != y).map(|(x, y)| format!("{x}\n vs\n{y}")); for signed in [false, true] { let batched = copy_rows_signed(false, signed); let row_by_row = cotton_store::fold::row_by_row_for_tests(|| copy_rows_signed(false, signed)); assert!(batched.contains("== cotton_lines"), "the copy holds its lines"); assert!(batched == row_by_row, "batch vs row by row (signed {signed}): {:?}", first_difference(&batched, &row_by_row)); } } /// A copy's rows written to `COPY_ROWS_TO`, to diff a copy one build makes /// against another's (the before/after of copy-installer-cpu). #[test] #[ignore = "a comparison: COPY_ROWS_TO= cargo test -p cotton-client write_copy_rows -- --ignored"] fn write_copy_rows() { let to = std::env::var("COPY_ROWS_TO").expect("COPY_ROWS_TO names the file"); std::fs::write(to, copy_rows(false)).expect("written"); } /// RULE (connect-commits, 7 Nov 2026): a pulled page lands whole or not at /// all, and the cursor never runs ahead of its rows: its rows, its parks and /// the cursor move are one transaction. A write that fails at the page's last /// step (the cursor's, aborted here by a trigger) leaves none of its 200 rows /// and the cursor where it was; the next pass takes the same page whole. #[test] fn a_page_that_fails_part_way_leaves_none_of_its_rows_and_the_cursor_where_it_was() { let (_dir, _layout, replica) = open_test_replica(); let rows: Vec = (0..200).map(|i| todo(&format!("t-{i:06}"), "An invented chore", 2)).collect(); replica .driver .exec("CREATE TRIGGER invented_cut BEFORE INSERT ON _cursors BEGIN SELECT RAISE(ABORT, 'the line dropped'); END") .expect("the cut"); let exchange = ScriptedExchange::new([page(json!(rows.clone()), 2, None)]); assert!(run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).is_err(), "the page did not land"); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id LIKE 't-%'"), 0, "none of the page's rows"); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM _parked"), 0, "and none of its parks"); assert_eq!(cursor(&replica), None, "the cursor is where it was"); replica.driver.exec("DROP TRIGGER invented_cut").expect("the line back"); let exchange = ScriptedExchange::new([page(json!(rows), 2, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass"); assert_eq!(count_of(&replica, "SELECT COUNT(*) AS n FROM cotton_todos WHERE id LIKE 't-%'"), 200, "the page whole"); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000002")); } /// A made table declaring its own `created_at` beside the dates a passkey keeps, as the kit's passkey does. fn served_dated() -> Value { json!({ "id": "dated_key", "name": "Dated key", "plural": "Dated keys", "picture": null, "builtin": false, "engine": null, "columns": [ {"key": "label", "name": "Label", "type": "text", "required": true}, {"key": "sign_count", "name": "Sign count", "type": "number"}, {"key": "created_at", "name": "Made", "type": "date"}, {"key": "last_used_at", "name": "Last used", "type": "date"}, {"key": "uses", "name": "Uses", "type": "number"}, ], "title": "label", "date": "created_at", "project": null, "order": null, "slip": {"title": "label", "subtitle": null, "trailing": null, "photo": null, "toggle": null}, "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["label"]}], "instructions": "Invented for a test.", }) } const MADE: &str = "2025-01-01T09:00:00.000Z"; const USED: &str = "2025-06-01T09:00:00.000Z"; /// RULE (8 Nov 2026): a row whose table declares its own `created_at` (a passkey's MADE) goes to the object with every date and count as written — an adoption's push. Walk keys-walk-vault: MADE 1 Jan 2025 became the adoption moment. #[test] fn a_rows_own_created_at_and_counts_go_up_as_written() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([ page(json!([]), 2, None), served_with_tables(json!([served_dated()]), "e1"), Reply::ok(r#"{"version": 3, "changed": []}"#), page(json!([]), 3, None), served_with_tables(json!([served_dated()]), "e1"), ]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass that makes the table"); let mut patch = serde_json::Map::new(); patch.insert("workspace_id".into(), WORKSPACE.into()); patch.insert("label".into(), "example.com".into()); patch.insert("sign_count".into(), 7.into()); patch.insert("created_at".into(), MADE.into()); patch.insert("last_used_at".into(), USED.into()); patch.insert("uses".into(), 4.into()); patch.insert("updated_at".into(), NOW.into()); let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(7))); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "add_key".into(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::create("cotton_dated_key", "k-1", patch)], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_760_000_000_000, &mut ids).expect("the replica's clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("a queued change"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass that posts it"); let act = body(&exchange.nth(2)); assert_eq!(act["act"], "create"); let sent = &act["args"]["data"]; assert_eq!( (sent["created_at"].clone(), sent["last_used_at"].clone(), sent["uses"].clone(), sent["sign_count"].clone()), (json!(MADE), json!(USED), json!(4), json!(7)), "every date and count goes up as written: {sent}" ); } /// RULE (8 Nov 2026): a fresh copy (an adoption's, or any phone's first pull) keeps a row's own declared `created_at` over the object's frame time — the moment the object took the row, which for an adopted passkey is the adoption. Cause of keys-walk-vault's moved MADE: the fold laid the frame's `created_at` over the column the definition declares. #[test] fn a_fresh_copy_keeps_a_rows_own_created_at_over_the_objects_frame_time() { let (_dir, _layout, replica) = open_test_replica(); let row = json!({ "table": "dated_key", "id": "k-1", "version": 3, "owner": null, "data": {"label": "example.com", "sign_count": 7, "created_at": MADE, "last_used_at": USED, "uses": 4}, "created_at": NOW, "updated_at": NOW, }); let exchange = ScriptedExchange::new([page(json!([row]), 3, None), served_with_tables(json!([served_dated()]), "e1")]); let mut object = transport(&exchange, &replica).taking_definitions(HeldDefinitions::new()); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the first pull"); let held = replica .driver .get("SELECT label, created_at, last_used_at, uses, sign_count FROM cotton_dated_key WHERE id = 'k-1'", &[]) .expect("a read") .expect("the row lands"); assert_eq!(held.text("label"), Some("example.com")); assert_eq!(held.text("created_at"), Some(MADE), "the row's own MADE, not the object's frame time"); assert_eq!(held.text("last_used_at"), Some(USED)); assert_eq!((held.int("uses"), held.int("sign_count")), (Some(4), Some(7))); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(parked.is_empty(), "{parked:?}"); } // ── film-progress-flood: one post per row, and the pull every pass ───────── /// Queued writes of todos, each its own op at its own instant: a create of /// each id in `made`, then `edits` edits of `edited`'s title, as a player's /// progress writes are. fn queue(replica: &crate::Replica, made: &[&str], edited: Option<&str>, edits: usize) { let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(7))); let mut at = 1_760_000_000_000i64; let mut mint = |change: cotton_store::mint::Change| { at += 1_000; let clock = cotton_store::mint::clock::writer_clock(&replica.driver, at, &mut ids).expect("the replica's clock"); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "queue_todo".to_string(), history: cotton_store::mint::History::None, changes: vec![change], }, &clock, &mut ids, cotton_store::mint::Held::Replica, ) .expect("a queued write"); }; for id in made { let mut patch = serde_json::Map::new(); patch.insert("workspace_id".to_string(), WORKSPACE.into()); patch.insert("title".to_string(), format!("Synthetic {id}").into()); patch.insert("status".to_string(), "open".into()); patch.insert("created_at".to_string(), "2026-09-08T10:00:00.000Z".into()); patch.insert("updated_at".to_string(), "2026-09-08T10:00:00.000Z".into()); mint(cotton_store::mint::Change::create("cotton_todos", id, patch)); } if let Some(id) = edited { for n in 0..edits { let mut patch = serde_json::Map::new(); patch.insert("title".to_string(), format!("Synthetic edit {n}").into()); mint(cotton_store::mint::Change::update("cotton_todos", id, patch)); } } } fn acts(exchange: &Arc) -> Vec { exchange.seen().iter().filter(|seen| seen.path == "/v1/act").map(body).collect() } fn pending(replica: &crate::Replica) -> i64 { cotton_store::outbox::pending_count(&replica.driver).expect("the outbox") } #[test] fn many_queued_edits_of_one_row_are_one_post_of_the_row_now() { let (_dir, _layout, replica) = open_test_replica(); queue(&replica, &["todo-film", "todo-other"], Some("todo-film"), 300); assert!(pending(&replica) >= 302); let exchange = ScriptedExchange::new([ Reply::ok(r#"{"version": 8, "changed": []}"#), Reply::ok(r#"{"version": 9, "changed": []}"#), page(json!([]), 9, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let posted = acts(&exchange); assert_eq!(posted.len(), 2, "one post per row: {posted:?}"); assert_eq!((posted[0]["act"].as_str(), posted[0]["args"]["id"].as_str()), (Some("create"), Some("todo-film"))); assert_eq!(posted[0]["args"]["data"]["title"], "Synthetic edit 299", "the row as it stands now"); assert_eq!(posted[1]["args"]["id"], "todo-other"); assert_eq!(pending(&replica), 0, "every op the posts carried is taken"); } #[test] fn a_row_the_object_refuses_is_posted_once_and_its_later_ops_carry_the_refusal() { let (_dir, _layout, replica) = open_test_replica(); queue(&replica, &["todo-refused"], Some("todo-refused"), 5); let exchange = ScriptedExchange::new([ Reply::json(400, r#"{"code": "missing_required", "message": "todo needs title"}"#), page(json!([]), 9, None), ]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(acts(&exchange).len(), 1, "never posted again in the same pass"); let parked = replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parked ops"); assert!(!parked.is_empty() && parked.iter().all(|row| row.text("reason") == Some("todo needs title")), "{parked:?}"); assert_eq!(pending(&replica), 0, "settled with the refusal, not held"); } #[test] fn a_long_queue_posts_at_most_its_pass_of_rows_and_the_pull_lands_before_the_rest() { let (_dir, _layout, replica) = open_test_replica(); let total = POSTS_PER_PASS + 10; let made: Vec = (0..total).map(|n| format!("todo-{n:03}")).collect(); queue(&replica, &made.iter().map(String::as_str).collect::>(), None, 0); let mut replies: Vec = (0..POSTS_PER_PASS).map(|_| Reply::ok(r#"{"version": 8, "changed": []}"#)).collect(); replies.push(page(json!([todo("arrived", "From the object", 9)]), 9, None)); replies.extend((0..10).map(|_| Reply::ok(r#"{"version": 10, "changed": []}"#))); replies.push(page(json!([]), 10, None)); let exchange = ScriptedExchange::new(replies); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let paths: Vec = exchange.seen().iter().map(|seen| seen.path.clone()).collect(); let first_pull = paths.iter().position(|path| path.starts_with("/v1/sync")).expect("a pull"); assert_eq!(first_pull, POSTS_PER_PASS, "the pull comes after one pass of posts: {paths:?}"); assert_eq!(todo_title(&replica, "arrived").as_deref(), Some("From the object"), "the object's row landed"); assert_eq!(acts(&exchange).len(), total, "the rest went with the next exchange"); assert_eq!(pending(&replica), 0); } /// RULE (launch-fast, 20 Nov 2026): a copy is on its first pull from the object until a pass ends on it — no cursor yet, or between the pages of a pull from nothing; a pass that ended, and a copy pulling again from the start over the rows it holds, are not. #[test] fn a_copy_is_on_its_first_pull_until_a_pass_ends_on_it() { let at = |held: Option| first_pull_underway(&held.into_iter().map(|held| (CURSOR_KEY.to_string(), held)).collect()); assert!(at(None), "no cursor: nothing has come yet"); assert!(at(Some(page_cursor(0, 0, 3, "token"))), "between the first pull's pages"); assert!(!at(Some(version_cursor(0, 120))), "a pass ended"); assert!(!at(Some(version_cursor(0, 0))), "a pass ended on an object holding nothing"); assert!(!at(Some(page_cursor(1, 0, 2, "token"))), "pulling again from the start over rows it holds"); } /// RULE (incident, 21 Nov 2026: Account's Last error read "the business did not answer"): a refusal is told as the object not answering — said in the log, never on a screen — by its code (offline, internal_error, unanswered) or, in words alone, by the status the core writes into them (0, 429, 5xx); a refusal a person can act on, a table's name or a count that is not a status, is not one. #[test] fn an_object_that_did_not_answer_is_told_from_a_refusal() { for (code, words) in [ ("internal_error", "the business did not answer"), ("offline", "the object could not be reached"), (UNANSWERED, "the object refused"), ("copy_kept", "this phone's copy holds rows the object may lack, and they could not be sent (the business did not answer, status 500 internal_error); it is kept until they are"), ("", "the object stopped answering, status 503 unavailable"), ("", "a page failed, status 0 offline"), ("", "too busy, status 429"), ] { assert!(names_an_unanswered_object(code, words), "{code}: {words}"); } for (code, words) in [ ("credential_revoked", "this sign-in was ended; sign in again"), ("copy_kept", "this phone's copy holds rows in a table this build has no name for: garden_bed (3 rows)"), ("", "the object refused it, status 422 invented_refusal"), ("", "status 5000 rows"), ("", "seal_key_missing: no key for the data key"), ] { assert!(!names_an_unanswered_object(code, words), "{code}: {words}"); } } /// Probe (not a rule): what a pulled row costs in a phone's copy, table by /// table — its own table and indexes beside its receipt in `_writes`. /// Run: pnpm box:cargo test -p cotton-client --lib what_a_pulled_row_costs -- --ignored --nocapture #[test] #[ignore = "a measurement, run by hand"] fn what_a_pulled_row_costs() { let (_dir, _layout, replica) = open_test_replica(); let size = |db: &cotton_store::driver::Driver| -> Vec<(String, i64)> { db.all("SELECT name, SUM(pgsize) AS b FROM dbstat GROUP BY name ORDER BY b DESC", &[]) .expect("dbstat") .iter() .map(|row| (row.text("name").unwrap_or_default().to_string(), row.int("b").unwrap_or(0))) .collect() }; let before: std::collections::HashMap = size(&replica.driver).into_iter().collect(); let n: usize = std::env::var("PROBE_ROWS").ok().and_then(|n| n.parse().ok()).unwrap_or(20_000) / 2000 * 2000; let words = "Running a little late, will be there by seven; keep a seat for me please"; let mut pages = Vec::new(); let threads: Vec = (0..300) .map(|t| json!({"table": "thread", "id": format!("thread-{t:04}"), "version": 5, "owner": null, "data": {"channel": "whatsapp", "title": format!("Invented chat {t}")}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"})) .collect(); pages.push(page(json!(threads), 9, None)); for chunk in 0..(n / 2000) { let mut rows = Vec::new(); for i in chunk * 2000..(chunk + 1) * 2000 { if std::env::var("PROBE_KIND").as_deref() == Ok("days") { // Days: events, todos and photos, as a Days copy holds them. rows.push(match i % 3 { 0 => json!({"table": "event", "id": format!("message-{i:08}"), "version": 10 + i as i64, "owner": null, "data": {"title": &words[..(20 + i % 30)], "starts_at": "2026-10-20T09:00:00.000Z", "ends_at": "2026-10-20T10:00:00.000Z", "location": "Invented place"}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"}), 1 => json!({"table": "todo", "id": format!("message-{i:08}"), "version": 10 + i as i64, "owner": null, "data": {"title": &words[..(20 + i % 40)], "status": "open", "priority": 0}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"}), _ => json!({"table": "photo", "id": format!("message-{i:08}"), "version": 10 + i as i64, "owner": null, "data": {"key": format!("11111111-1111-4111-8111-111111111111/photos/{i:064}.jpg"), "sha256": format!("{i:064}"), "content_type": "image/jpeg", "size_bytes": 2_400_000, "width": 4032, "height": 3024, "taken_at": "2026-10-20T09:00:00.000Z"}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"}), }); continue; } rows.push(json!({ "table": "message", "id": format!("message-{i:08}"), "version": 10 + i as i64, "owner": null, "data": {"thread_id": format!("thread-{:04}", i % 300), "channel": "whatsapp", "sent_at": "2026-10-20T09:00:00.000Z", "external_id": format!("wa-{i:012}-ABCDEF0123456789"), "origin": "imported", "sender_name": "Invented Friend", "body": &words[..(20 + i % 50)], "direction": if i % 2 == 0 { "in" } else { "out" }, "media": []}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", })); } pages.push(page(json!(rows), 10 + ((chunk + 1) * 2000) as i64, None)); } let exchange = ScriptedExchange::new(pages); let mut object = ObjectTransport::new( ObjectAddress::named("https://cotton.example.com", "asha").expect("an address"), Arc::clone(&exchange) as Arc, "synthetic-credential".into(), Arc::new(ObjectTables::personal().opening(&["message", "thread", "event", "todo", "photo"])), replica.path.clone(), vec![], ); let started = std::time::Instant::now(); for _ in 0..=(n / 2000) { run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); } let took = started.elapsed(); let held = replica.driver.get("SELECT COUNT(*) AS n FROM _writes WHERE row_id LIKE 'message-%'", &[]).unwrap().unwrap().int("n").unwrap().max(1); for row in replica.driver.all("SELECT tbl, COUNT(*) AS n FROM _writes GROUP BY tbl ORDER BY n DESC LIMIT 3", &[]).unwrap() { println!("PROBE receipts {:?} {:?}", row.text("tbl"), row.int("n")); } println!("PROBE {held} messages folded in {took:?}"); for row in replica.driver.all("SELECT * FROM _parked LIMIT 1", &[]).unwrap() { println!("PROBE parked {:?}", row); } let mut total = 0; for (name, bytes) in size(&replica.driver) { let grew = bytes - before.get(&name).copied().unwrap_or(0); total += grew; if grew > 50_000 { println!("PROBE {:>10} bytes {:>6} per row {name}", grew, grew / held); } } println!("PROBE total grew {total} bytes, {} per row", total / held); // Before and after, on disk: the copy as a build before 151 kept it (every receipt whole, compacted), // then trimmed in place step by step and compacted once, as a phone after this build does. let file_size = |db: &cotton_store::driver::Driver| -> i64 { let page = db.get("PRAGMA page_size", &[]).unwrap().unwrap().int("page_size").unwrap(); let pages = db.get("PRAGMA page_count", &[]).unwrap().unwrap().int("page_count").unwrap(); let free = db.get("PRAGMA freelist_count", &[]).unwrap().unwrap().int("freelist_count").unwrap(); (pages - free) * page }; let ids: Vec<(String, String)> = replica.driver.all("SELECT tbl, row_id FROM _writes WHERE implied IS NOT NULL", &[]).unwrap().iter().map(|r| (r.text("tbl").unwrap().to_string(), r.text("row_id").unwrap().to_string())).collect(); replica.driver.transaction(|db| { for (t, id) in &ids { cotton_store::receipts::implied::materialize_row(db, t, id)?; } Ok(()) }).unwrap(); replica.driver.exec("DELETE FROM _trim; VACUUM").unwrap(); // Nothing lost: every row of every table, and every receipt as a reader gets it, the same after. let digest = |db: &cotton_store::Driver| -> (u64, usize, usize) { use std::hash::{Hash, Hasher}; let mut hasher = std::collections::hash_map::DefaultHasher::new(); let tables: Vec = db.all("SELECT DISTINCT tbl FROM _writes ORDER BY tbl", &[]).unwrap().iter().map(|r| r.text("tbl").unwrap().to_string()).collect(); let (mut rows, mut receipts) = (0, 0); for table in &tables { for row in db.all(&format!("SELECT * FROM \"{table}\" ORDER BY id"), &[]).unwrap() { format!("{row:?}").hash(&mut hasher); rows += 1; } let ids: Vec = db.all("SELECT DISTINCT row_id FROM _writes WHERE tbl = ? ORDER BY row_id", &[rusqlite::types::Value::Text(table.clone())]).unwrap().iter().map(|r| r.text("row_id").unwrap().to_string()).collect(); for id in ids { for stored in cotton_store::receipts::of_row(db, table, &id).unwrap() { (stored.op_id.as_str(), stored.hlc.as_str(), stored.author.as_str(), format!("{:?}", stored.bytes)).hash(&mut hasher); receipts += 1; } } } (hasher.finish(), rows, receipts) }; let whole = digest(&replica.driver); let before = file_size(&replica.driver); println!("PROBE before (every receipt whole): {:.1} MB, {} per row", before as f64 / 1e6, before / held); let started = std::time::Instant::now(); let (mut steps, mut slowest) = (0, std::time::Duration::ZERO); loop { let at = std::time::Instant::now(); let (_, done) = cotton_store::receipts::implied::carry(&replica.driver, 1).unwrap(); slowest = slowest.max(at.elapsed()); steps += 1; if done { break; } } println!("PROBE trimmed in place: {steps} steps in {:?}, slowest step {slowest:?}", started.elapsed()); let at = std::time::Instant::now(); replica.driver.exec("PRAGMA auto_vacuum = INCREMENTAL; VACUUM").unwrap(); let after = file_size(&replica.driver); println!("PROBE after (trimmed, compacted in {:?}): {:.1} MB, {} per row, {:.0}% smaller", at.elapsed(), after as f64 / 1e6, after / held, 100.0 - 100.0 * after as f64 / before as f64); let trimmed = digest(&replica.driver); let implied = replica.driver.get("SELECT COUNT(*) AS n FROM _writes WHERE implied IS NOT NULL", &[]).unwrap().unwrap().int("n").unwrap(); println!("PROBE nothing lost: {} rows and {} receipts read the same after the trim ({implied} receipts implied): {}", whole.1, whole.2, whole == trimmed); assert_eq!(whole, trimmed, "every row and every receipt reads the same after the trim"); } /// RULE (24 Nov 2026): every launch's connect reads the account's switches before it opens the copy, so the read /// never makes a missing copy (a first sign-in's, which connect would then find on disk), and it reads beside the /// phone's own handle holding the write lock without waiting on it. #[test] fn reading_the_account_switches_makes_no_copy_and_waits_on_no_writer() { let (dir, layout, replica) = open_test_replica(); let missing = dir.path().join("a-first-sign-in.db"); assert!(account_features(&missing).is_empty()); assert!(!missing.exists(), "reading the switches made a copy"); replica .driver .exec(&format!("INSERT OR REPLACE INTO _cursors (author_device_id, hlc_seen, updated_at) VALUES ('{FEATURES_KEY}', 'f2026-11-24T00:00:00Z|mail_all', '2026-11-24T00:00:00Z')")) .unwrap(); // The phone's own handle holds the write lock, as a fold or a sweep does at launch. replica.driver.exec("BEGIN IMMEDIATE").unwrap(); let at = std::time::Instant::now(); let read = account_features(&layout.replica(WORKSPACE)); let took = at.elapsed(); replica.driver.exec("ROLLBACK").unwrap(); assert_eq!(read, ["mail_all"]); assert!(took < std::time::Duration::from_secs(2), "the read waited {took:?} on the writer"); } /// RULE (review of GENESIS KITS, 26 Nov 2026: an old client): a build that keeps no table of a kit's (one made before /// Sites' `site` was laid on phones) meeting that table's rows in a page passes them by: the rows of tables it knows /// land, the cursor moves on, and its own queue still goes — nothing stalls on a table it lacks. #[test] fn a_build_without_a_table_passes_its_rows_by_and_its_queue_still_goes() { let (_dir, _layout, replica) = open_test_replica(); let theirs = json!({ "table": "a_table_this_build_lacks", "id": "s-1", "version": 2, "owner": null, "data": {"label": "Invented club", "home": "club.example"}, "created_at": "2026-11-26T09:00:00.000Z", "updated_at": "2026-11-26T09:00:00.000Z", }); let exchange = ScriptedExchange::new([page(json!([theirs, todo("t-1", "Known", 3)]), 3, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass over a table it lacks"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Known"), "the rows it knows land"); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000003"), "the cursor moves past them"); queue_one_change(&replica, "Written after"); let exchange = ScriptedExchange::new([page(json!([]), 3, None), act_taken(), page(json!([]), 99, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("the next pass"); assert!((0..exchange.calls()).any(|n| exchange.nth(n).path == "/v1/act"), "its own change went"); } /// RULE (re-review of SITES SYNC, 26 Nov 2026: an old client meeting SEALED rows): the same, with Sites' rows as the /// object serves them, sealed (the clear key, then `sealed_enc`, `dek_enc` and `seal_v`, which this build cannot open /// and never tries to): they are passed by, the known rows land, the cursor moves, and its own queue still goes. #[test] fn a_build_without_the_site_table_passes_sealed_site_rows_by_and_its_queue_still_goes() { let (_dir, _layout, replica) = open_test_replica(); let sealed = |id: &str, v: u64| json!({ "table": "site", "id": id, "version": v, "owner": null, "data": {"key": id, "sealed_enc": "c2VhbGVkLCBuZXZlciBvcGVuZWQgaGVyZQ", "dek_enc": "ZGVrLCBuZXZlciBvcGVuZWQ", "seal_v": 1}, "created_at": "2026-11-26T09:00:00.000Z", "updated_at": "2026-11-26T09:00:00.000Z", }); let exchange = ScriptedExchange::new([page(json!([sealed("6b1f4c1e-2f0a-4d6e-9a1b-0c2d3e4f5a6b", 1), todo("t-1", "Known", 2), sealed("0c2d3e4f-5a6b-4c1e-8f0a-6b1f4c1e2f0a", 3)]), 3, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass over sealed rows of a table it lacks"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Known")); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000003")); queue_one_change(&replica, "Written after"); let exchange = ScriptedExchange::new([page(json!([]), 3, None), act_taken(), page(json!([]), 99, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("the next pass"); assert!((0..exchange.calls()).any(|n| exchange.nth(n).path == "/v1/act"), "its own change went"); } /// RULE (FIRST SYNC FAST, 26 Nov 2026: during a first pull the device row stood still, and slow and stuck looked the /// same): a long pull says this device's state on its row every REPORT_EVERY_PAGES pages, not only on its last page. #[test] fn a_long_pull_says_the_devices_state_every_few_pages() { let (_dir, _layout, replica) = open_test_replica(); let pages = super::REPORT_EVERY_PAGES as usize + 2; let mut replies = Vec::new(); for n in 1..=pages { let next = (n < pages).then(|| format!("page-{}", n + 1)); replies.push(standing(json!([todo(&format!("t-{n}"), "Invented", 4)]), 0, next.as_deref(), json!("dev-1"), pages as i64, (pages - n) as i64)); replies.push(act_taken()); } let exchange = ScriptedExchange::new(replies); // Each page five seconds and more after the last, so each says its bytes and writes the row. let clock = Arc::new(Mutex::new(START_MS)); let ticking = Arc::clone(&clock); let progress = Arc::new(SyncProgress::new(move || { let mut now = ticking.lock().expect("the clock"); *now += 6_000; *now })); // A cycle takes some pages; the pull goes on in the next, as a long first pull does. for _ in 0..pages { if exchange.calls() >= 2 * pages { break; } run_cycle(&replica.driver, &mut reporting_state(&exchange, &replica, &progress, json!({"build":"330","sha":"synthetic330","schema":150})), WORKSPACE, NOW).expect("a long pass"); } let said: Vec = (0..pages).map(|n| row_update(&exchange.nth(2 * n + 1)).1.get("reported_state").is_some()).collect(); let every = super::REPORT_EVERY_PAGES as usize; for (n, says) in said.iter().enumerate() { let page = n + 1; assert_eq!(*says, page % every == 0 || page == pages, "page {page} of {pages}: {said:?}"); } } /// RULE (FIRST SYNC FAST): a sync page is asked gzipped and read inflated, as the object's front sends it. #[test] fn a_gzipped_page_is_read_inflated() { let (_dir, _layout, replica) = open_test_replica(); let body = json!({"version": 4, "rows": [todo("t-1", "Ring the bank", 4)], "server_time": NOW}).to_string(); let zipped = Reply::new(200, crate::transport::scripted::gzip(body.as_bytes())).with_header("content-encoding", "gzip"); let exchange = ScriptedExchange::new([zipped]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("a pass"); let asked = exchange.nth(0); assert!(asked.headers.iter().any(|(name, value)| name.eq_ignore_ascii_case("accept-encoding") && value == "gzip"), "{:?}", asked.headers); let held: i64 = replica.driver.connection().query_row("SELECT COUNT(*) FROM _writes", [], |r| r.get(0)).unwrap(); assert!(held > 0, "the inflated page folded"); } /// RULE (FIRST SYNC FAST): a page asked ahead is taken by the ask of that same page, never by another's; and an /// exchange that answers in the order it was written (the scripted one) is never asked ahead. #[test] fn a_page_asked_ahead_answers_only_its_own_ask() { let (_dir, _layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([page(json!([]), 1, None)]); assert!(!exchange.concurrent(), "the scripted exchange is never asked two at once"); assert!(crate::transport::SocketExchange.concurrent()); let t = transport(&exchange, &replica); let ahead = |path: &str, version: i64| { let (send, answer) = std::sync::mpsc::channel(); send.send(Ok((json!({"version": version, "rows": []}), 7))).unwrap(); *super::AHEAD.lock().unwrap() = Some(super::Ahead { key: t.ahead_key(path), answer }); }; ahead("/v1/sync?cursor=two", 2); let (answer, _) = t.ask_page("/v1/sync?cursor=two").expect("the page asked ahead"); assert_eq!((answer["version"].as_i64(), exchange.calls()), (Some(2), 0), "taken from the ask ahead, nothing sent"); ahead("/v1/sync?cursor=three", 3); let (answer, _) = t.ask_page("/v1/sync?cursor=other").expect("asked now"); assert_eq!((answer["version"].as_i64(), exchange.calls()), (Some(1), 1), "another page's ask lets it go and asks"); assert!(super::AHEAD.lock().unwrap().is_none()); } /// RULE (QUEUE BAD OP, coordinator, 26 Nov 2026: one queued op that did not decode stopped every pass of the copy for /// good, and nothing said why): it is set aside as a refused push under the code `undecodable`, leaves the queue and /// is counted; the pass sends the rest; the stuck list names it by its code, and Let go writes it down and ends it. #[test] fn a_queued_op_that_does_not_read_is_set_aside_and_the_pass_goes_on() { let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "Buy milk"); replica .driver .run( "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, sig) \ SELECT 'bad-op', kind, author, tbl, 'todo-damaged', '0000000000001:0000:x', schema_version, '2026-09-08T09:00:00.000Z', X'00FF', NULL \ FROM _outbox WHERE tbl = 'cotton_todos' LIMIT 1", &[], ) .expect("a damaged queued op"); let exchange = ScriptedExchange::new([Reply::ok(r#"{"version": 8, "changed": []}"#), page(json!([]), 8, None), page(json!([]), 8, None), page(json!([]), 8, None)]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass goes on"); let sent = body(&exchange.nth(0)); assert_eq!((sent["act"].as_str(), sent["args"]["id"].as_str()), (Some("create"), Some("todo-Buy milk")), "the good change went"); let queued = replica.driver.get("SELECT COUNT(*) AS n FROM _outbox WHERE op_id = 'bad-op'", &[]).expect("a read").and_then(|row| row.int("n")); assert_eq!(queued, Some(0), "out of the queue"); let parked = replica.driver.get("SELECT direction, reason, tbl, row_id FROM _parked WHERE op_id = 'bad-op'", &[]).expect("a read").expect("set aside"); assert_eq!((parked.text("direction"), parked.text("tbl"), parked.text("row_id")), (Some("push"), Some("cotton_todos"), Some("todo-damaged"))); assert!(parked.text("reason").is_some_and(|reason| reason.starts_with("undecodable: "))); assert_eq!(cotton_store::outbox::waiting(&replica.driver).expect("waiting").by_code.get("undecodable"), Some(&1), "counted by its code"); // A second pass before Let go trips on nothing, and the op is still set aside once, still counted. run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a second pass"); assert_eq!(cotton_store::rejected::undecodable_count(&replica.driver).expect("a count"), 1); let now_ms = cotton_store::protocol::js::parse_date_ms(NOW).expect("a time"); // Send again never ends it, and says this build cannot send it (QUEUE BAD OP 2). let again = crate::unsent_heal::send_again(&replica.driver, &layout, WORKSPACE, &["bad-op".to_string()], NOW).expect("send again"); assert_eq!(again, (0, 0, 1)); assert_eq!(cotton_store::rejected::undecodable_count(&replica.driver).expect("a count"), 1, "still there for Let go"); let stuck = crate::unsent_heal::stuck(&replica.driver, now_ms).expect("the stuck list"); let bad: Vec<_> = stuck.iter().filter(|stuck| stuck.op_id == "bad-op").collect(); assert_eq!(bad.len(), 1, "{stuck:?}"); assert_eq!((bad[0].code.as_str(), bad[0].parked), ("undecodable", true)); let gone = crate::unsent_heal::let_go(&replica.driver, &layout, WORKSPACE, &["bad-op".to_string()], NOW).expect("let go"); assert_eq!(gone, 1); assert!(crate::unsent_heal::stuck(&replica.driver, now_ms).expect("the stuck list").iter().all(|stuck| stuck.op_id != "bad-op")); assert_eq!(cotton_store::rejected::undecodable_count(&replica.driver).expect("a count"), 0); let written = crate::unsent::discarded(&layout, WORKSPACE); assert!(written.iter().any(|entry| entry.changes.iter().any(|change| change.op_id == "bad-op")), "written down before it went"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the next pass"); } /// RULE (QUEUE BAD OP 2): a queued op that does not read, of the same row as a good one, is set aside alone: the /// good write of that row goes, and the unsent list (sign-out, a remake) reads past the bad one. #[test] fn a_queued_op_that_does_not_read_beside_a_good_one_of_its_row_is_set_aside_alone() { let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "Buy milk"); replica .driver .run( "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, sig) \ SELECT 'bad-op', kind, author, tbl, row_id, '0000000000001:0000:x', schema_version, queued_at, X'00FF', NULL \ FROM _outbox WHERE tbl = 'cotton_todos' LIMIT 1", &[], ) .expect("a damaged op of the same row"); let exchange = ScriptedExchange::new([Reply::ok(r#"{"version": 8, "changed": []}"#), page(json!([]), 8, None), page(json!([]), 8, None)]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the pass goes on"); let sent = body(&exchange.nth(0)); assert_eq!((sent["act"].as_str(), sent["args"]["id"].as_str()), (Some("create"), Some("todo-Buy milk")), "the row's good write went"); let parked = replica.driver.get("SELECT row_id FROM _parked WHERE op_id = 'bad-op'", &[]).expect("a read").expect("set aside"); assert_eq!(parked.text("row_id"), Some("todo-Buy milk")); let read = crate::unsent::receipts(&replica.driver).expect("the unsent list reads past it"); assert!(read.iter().all(|(op, _)| op.op_id != "bad-op")); } /// RULE (QUEUE BAD OP 4: nothing is carried out of a copy any more): the send before a rebuild answers which changes /// the object took; a set-aside change is not among them, so `copy_keep::retire` keeps the copy whole aside with it. #[test] fn a_rebuild_keeps_a_copy_holding_a_set_aside_change_whole_aside() { let (_dir, layout, replica) = open_test_replica(); cotton_store::rejected::set_aside_undecodable(&replica.driver, "bad-op", Some(&[0, 255]), None, "cotton_todos", "todo-damaged", "it does not read", NOW).expect("set aside"); let exchange = ScriptedExchange::new([page(json!([]), 8, None)]); let object = transport(&exchange, &replica); let path = replica.path.clone(); let sent = object.send_before_remake(&layout, WORKSPACE, NOW).expect("before the rebuild"); assert!(!sent.acknowledged.contains(&"bad-op".to_string())); assert!(!super::carried_path(&path).exists(), "nothing carried out of the copy"); let retired = crate::copy_keep::retire(&layout, WORKSPACE, &path, crate::copy_keep::Ending::keep_beyond("a rebuild", &sent.acknowledged)).expect("retired"); assert!(matches!(retired, crate::copy_keep::Retired::Kept(_)), "{retired:?}"); assert!(!path.exists(), "the place is free for the new copy"); let kept = crate::copy_keep::kept_changes(&layout, WORKSPACE); assert!(kept.iter().any(|change| change.op_id == "bad-op" && change.bytes == vec![0u8, 255]), "{kept:?}"); } /// RULE (MAIL PREDICATE phase 2; review of the rules, 6): a row's `landed_at`, the object's own clock, lands in /// `cotton_emails.landed_at` for mail, and a table without the column (any other, or a copy of a build before /// schema 157) takes the row as before and ignores the field. #[test] fn a_rows_landing_time_lands_for_mail_and_is_ignored_elsewhere() { let (_dir, _layout, replica) = open_test_replica(); let mut with_landing = todo("t-1", "Ring the bank", 4); with_landing["landed_at"] = json!("2026-10-20T09:00:02.000Z"); let mail = json!({ "table": "email", "id": "e-1", "version": 4, "owner": null, "data": {"thread_id": "th-1", "external_id": "", "subject": "The lake", "from_email": "ada@invented.example", "sent_at": "2026-10-20T08:59:00.000Z"}, "created_at": "2001-01-01T00:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", "landed_at": "2026-10-20T09:00:03.000Z", }); let thread = json!({ "table": "email_thread", "id": "th-1", "version": 3, "owner": null, "data": {"external_key": "invented:th-1", "subject": "The lake", "email_count": 1}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z", }); let exchange = ScriptedExchange::new([page(json!([with_landing, thread, mail]), 4, None)]); let mut object = ObjectTransport::new( ObjectAddress::named("https://cotton.example.com", "asha").expect("an address"), Arc::clone(&exchange) as Arc, "synthetic-credential".into(), // Both sealed (e2e rulings R3); written here as open tables. Arc::new(ObjectTables::personal().opening(&["todo", "email", "email_thread"])), replica.path.clone(), vec![("message".into(), 90)], ); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Ring the bank"), "the field is ignored where there is no column"); let landed = replica.driver.get("SELECT landed_at FROM cotton_emails WHERE id = 'e-1'", &[]).expect("a read").and_then(|row| row.text("landed_at").map(str::to_string)); assert_eq!(landed.as_deref(), Some("2026-10-20T09:00:03.000Z"), "{:?} {:?} {:?}", replica.driver.all("SELECT tbl, reason FROM _parked", &[]).unwrap(), replica.driver.all("SELECT id, subject, created_at, landed_at FROM cotton_emails", &[]).unwrap(), replica.driver.all("SELECT name FROM pragma_table_info('cotton_emails') WHERE name = 'landed_at'", &[]).unwrap()); } /// One change minted here to a table the object holds as retired (the thoughts' `cotton_inbox_items`, TABLE DROP 1). fn queue_retired_change(replica: &crate::Replica, id: &str) { let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(77))); let mut patch = serde_json::Map::new(); patch.insert("workspace_id".to_string(), WORKSPACE.into()); patch.insert("raw_text".to_string(), "An invented thought".into()); patch.insert("captured_at".to_string(), "2026-09-08T10:00:00.000Z".into()); patch.insert("created_at".to_string(), "2026-09-08T10:00:00.000Z".into()); patch.insert("updated_at".to_string(), "2026-09-08T10:00:00.000Z".into()); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "queue_thought".to_string(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::create("cotton_inbox_items", id, patch)], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_760_000_000_000, &mut ids).expect("the replica's clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("minted"); } fn rows_of(replica: &crate::Replica, store: &str) -> i64 { replica.driver.get(&format!("SELECT count(*) AS n FROM {store}"), &[]).expect("a count").and_then(|row| row.int("n")).unwrap_or(0) } /// RULE (TABLE DROP 1, owner, 27 Nov 2026): a change this phone made to a table the object holds as retired is never /// sent and never lost: it leaves the queue parked with its patch, a place the copy-keeping rule counts, and the /// changes beside it go as before. #[test] fn a_change_to_a_retired_table_is_parked_with_its_patch_and_never_sent() { let (_dir, _layout, replica) = open_test_replica(); queue_retired_change(&replica, "thought-1"); queue_one_change(&replica, "Buy milk"); let exchange = ScriptedExchange::new([Reply::ok(r#"{"version": 8, "changed": []}"#), page(json!([]), 8, None), page(json!([]), 8, None)]); let mut object = transport(&exchange, &replica); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); let acts: Vec = exchange.seen().iter().filter(|seen| seen.path == "/v1/act").map(body).collect(); assert_eq!(acts.len(), 1, "only the todo went: {acts:?}"); assert_eq!(acts[0]["args"]["table"], "todo"); assert_eq!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"), 0, "nothing left queued"); let parked = replica.driver.all("SELECT tbl, reason FROM _parked WHERE direction = 'push'", &[]).expect("the parks"); assert!(parked.iter().any(|row| row.text("tbl") == Some("cotton_inbox_items") && row.text("reason").is_some_and(|reason| reason.starts_with("table_gone"))), "{parked:?}"); assert!(matches!(crate::copy_keep::unsent_in(&replica.path), crate::copy_keep::Unsent::Holds(n) if n >= 1), "the copy-keeping rule keeps a copy holding it"); } /// RULE (UNKNOWN FIELD, coordinator, 28 Nov 2026): a change naming a field the object's definition lacks (a kit column on /// main before the Worker's deploy) is refused `unknown_field` and never lost: it waits in the queue (never parked, so /// never "refused for good"), is not posted again while the object's definitions stand as they were, goes again once /// they move, and is said to the person only after it has waited a day. The changes beside it go as before. #[test] fn a_change_naming_a_field_the_object_lacks_waits_for_the_definitions_to_move_and_goes_again() { let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "Newer kit"); let exchange = ScriptedExchange::new([ Reply::json(400, r#"{"code": "unknown_field", "message": "todo has no field \"colour\""}"#), page(json!([]), 8, None), Reply::new(304, Vec::new()), page(json!([]), 8, None), Reply::ok(r#"{"version": 9, "changed": []}"#), page(json!([]), 9, None), Reply::new(304, Vec::new()), ]); let held = HeldDefinitions::new(); held.hold(Some("e1".into())); let mut object = transport(&exchange, &replica).taking_definitions(Arc::clone(&held)); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass"); assert_eq!(acts(&exchange).len(), 1); assert_eq!(pending(&replica), 1, "held in the queue"); assert!(replica.driver.all("SELECT reason FROM _parked", &[]).expect("the parks").is_empty(), "never parked"); let code = replica.driver.get("SELECT last_error FROM _outbox", &[]).expect("a read").and_then(|row| row.text("last_error").map(str::to_string)); assert!(code.as_deref().is_some_and(|code| code.starts_with("unknown_field")), "{code:?}"); assert_eq!(crate::unsent_heal::heal_of("unknown_field"), crate::unsent_heal::Heal::Slowly, "said only after a day"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass with the definitions as they were"); assert_eq!(acts(&exchange).len(), 1, "not posted again: {:?}", exchange.seen().iter().map(|s| s.path.clone()).collect::>()); assert_eq!(pending(&replica), 1); held.hold(Some("e2".into())); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a pass after the definitions moved"); assert_eq!(acts(&exchange).len(), 2, "posted again: {:?}", exchange.seen().iter().map(|s| s.path.clone()).collect::>()); assert_eq!(pending(&replica), 0, "it went"); } /// RULE (TABLE DROP 1): a signed-in copy lets a retired table's rows go at its open once nothing of the person's waits /// in them, and touches no other table; a copy that never pulled (a database made before sign-in) keeps them all. #[test] fn a_retired_tables_rows_leave_a_signed_in_copy_once_nothing_waits_in_them() { let (_dir, _layout, replica) = open_test_replica(); queue_retired_change(&replica, "thought-1"); queue_one_change(&replica, "Buy milk"); assert_eq!(rows_of(&replica, "cotton_inbox_items"), 1); assert!(drop_gone_rows(&replica.driver).expect("asked").is_empty(), "a copy that never pulled keeps every row"); assert_eq!(rows_of(&replica, "cotton_inbox_items"), 1); replica.driver.run("INSERT INTO _cursors (author_device_id, hlc_seen, updated_at) VALUES (?, ?, ?)", &[rusqlite::types::Value::Text(PASSED_KEY.into()), rusqlite::types::Value::Text("h0001.000000:".into()), rusqlite::types::Value::Text(NOW.into())]).expect("signed in"); assert!(drop_gone_rows(&replica.driver).expect("asked").is_empty(), "a change of it still queued keeps the rows"); assert_eq!(rows_of(&replica, "cotton_inbox_items"), 1); // The push parked it (above): nothing waits in the table now. replica.driver.run("DELETE FROM _outbox WHERE tbl = 'cotton_inbox_items'", &[]).expect("parked"); assert_eq!(drop_gone_rows(&replica.driver).expect("asked"), vec![("thought".to_string(), 1)]); assert_eq!(rows_of(&replica, "cotton_inbox_items"), 0); assert_eq!(rows_of(&replica, "cotton_todos"), 1, "no other table is touched"); } /// The thread table as the object serves it (sealed, as on every object). fn served_thread() -> Value { serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/thread.json")).expect("the kit's thread") } /// The thread table opened, for a pull these tests script in plain rows (the seal is orthogonal to which columns land: /// the opened row is the same map). fn served_thread_open() -> Value { let mut thread = served_thread(); thread.as_object_mut().expect("a table").remove("seal"); thread } fn group_thread(id: &str, version: i64, data: Value) -> Value { let mut row = json!({ "table": "thread", "id": id, "version": version, "owner": null, "data": { "kind": "group", "external_key": "cotton:group:g-invented", "title": "Invented group" }, "created_at": "2026-11-22T09:00:00.000Z", "updated_at": "2026-11-22T09:00:00.000Z", }); for (key, value) in data.as_object().expect("columns") { row["data"][key] = value.clone(); } row } /// A change this phone makes to thread `id`, as Cotton Chat's own writes are made: minted, queued, recorded. fn chat_writes(replica: &crate::Replica, id: &str, columns: Value) { let mut patch = serde_json::Map::new(); for (key, value) in columns.as_object().expect("columns") { patch.insert(key.clone(), value.clone()); } patch.insert("updated_at".into(), NOW.into()); let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(11))); cotton_store::mint::mint( &replica.driver, &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "chat_group".into(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::update("cotton_msg_threads", id, patch)], }, &cotton_store::mint::clock::writer_clock(&replica.driver, 1_760_000_000_000, &mut ids).expect("the replica's clock"), &mut ids, cotton_store::mint::Held::Replica, ) .expect("a queued change"); } /// RULE (owner's bug, 28 Nov 2026: every Cotton group said "This chat isn't a Cotton group." once his phone's copy was /// filled from the object again): the columns Cotton Chat keeps on a thread (its group's log, its pinned messages, the /// changes waiting to be told) are the phone's own writes and go with the row, sealed with it, though the kit keeps /// them readonly for people and tools. A copy filled from the object then has them. #[test] fn the_columns_chat_keeps_on_a_thread_go_with_the_row() { let (_dir, _layout, replica) = open_test_replica(); let map = ObjectTables::personal().with_defined([served_thread()].iter()).expect("a map"); let threads = map.object("thread").expect("threads come"); assert!(threads.seal.is_some(), "the thread is sealed, as on every object"); replica .driver .run( "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, group_log, pinned_messages, changes_waiting, created_at, updated_at) \ VALUES ('t-g', ?, 'group', 'cotton:group:g-invented', 'Invented group', '{\"group\":\"g-invented\"}', '[\"m-1\"]', '[]', ?, ?)", &[rusqlite::types::Value::Text(WORKSPACE.into()), rusqlite::types::Value::Text(NOW.into()), rusqlite::types::Value::Text(NOW.into())], ) .expect("a group thread"); let file = rusqlite::Connection::open(&replica.path).expect("the copy"); let sent = row_now(&file, threads, "t-g").expect("a read").expect("the row"); assert_eq!(sent.get("group_log"), Some(&json!("{\"group\":\"g-invented\"}")), "the group's log goes with the row: {sent:?}"); assert_eq!(sent.get("pinned_messages"), Some(&json!("[\"m-1\"]")), "{sent:?}"); assert!(sent.contains_key("changes_waiting"), "{sent:?}"); // Readonly still means no person's edit: a readonly column the person never writes stays the object's. let events = map.object("event"); assert!(events.is_none_or(|events| !events.written.iter().any(|column| column == "guest_responses"))); } /// RULE: a thread from the object that says nothing of the log (a writer that never had it: an older build, the Mac) /// leaves the copy's log as this phone wrote it; only a value the object holds replaces it. #[test] fn a_thread_from_the_object_that_says_nothing_of_the_log_leaves_the_copys_log() { let (_dir, _layout, replica) = open_test_replica(); let replica = Arc::new(std::sync::Mutex::new(replica)); let copy = || replica.lock().expect("the copy"); let exchange = ScriptedExchange::new([ page(json!([group_thread("t-g", 3, json!({}))]), 3, None), served_with_tables(json!([served_thread_open()]), "e1"), page(json!([group_thread("t-g", 5, json!({"title": "Invented group, renamed"}))]), 5, None), served_with_tables(json!([served_thread_open()]), "e1"), ]); let held = HeldDefinitions::new(); let mut object = transport(&exchange, ©()).taking_definitions(Arc::clone(&held)); object.lend_file(Arc::clone(&replica) as Arc); run_cycle_paged(&replica, &mut object, WORKSPACE, NOW).expect("the first pass"); chat_writes(©(), "t-g", json!({"group_log": "{\"group\":\"g-invented\"}"})); run_cycle_paged(&replica, &mut object, WORKSPACE, NOW).expect("the second pass"); let row = copy().driver.get("SELECT title, group_log FROM cotton_msg_threads WHERE id = 't-g'", &[]).expect("a read").expect("the row"); assert_eq!(row.text("title"), Some("Invented group, renamed"), "the object's change landed"); assert_eq!(row.text("group_log"), Some("{\"group\":\"g-invented\"}"), "the copy's log stands"); } /// RULE (Cotton Data, DECISIONS question 3; ANDROID READY 1 core fault 3): Keep everything's room guard stops only the /// fill. While it gives a reason, this phone's writes still go up, the pass does not fail (the app said "Cotton not /// reached yet" for as long as the phone was short of room), and a fill stopped part way waits where it stood. Once /// the copy has reached the object's end, a pull since its cursor is the sync itself, and goes on short of room. #[test] fn the_room_guard_stops_only_the_fill_never_the_writes_or_the_sync_after_it() { let (_dir, _layout, replica) = open_test_replica(); // How many of the fill's pulls there is room for: none, some, or any (-1). let room = Arc::new(std::sync::atomic::AtomicI64::new(0)); let guard = { let room = Arc::clone(&room); Arc::new(move || { let left = room.load(std::sync::atomic::Ordering::SeqCst); if left > 0 { room.store(left - 1, std::sync::atomic::Ordering::SeqCst); } (left == 0).then(|| "room_guard: 1.2 GB free, Keep everything leaves 2 GB free".to_string()) }) as Arc Option + Send + Sync> }; let set = |n: i64| room.store(n, std::sync::atomic::Ordering::SeqCst); queue_one_change(&replica, "Written short of room"); let exchange = ScriptedExchange::new([ // Short of room, a fresh copy: the write goes up, no page is asked. Reply::ok(r#"{"version": 2, "changed": []}"#), // Room for one page: the fill's first, then it stops before its second. page(json!([todo("t-1", "One", 3)]), 0, Some("page-two")), // Room again: the fill goes on from the page it stopped at, and ends. page(json!([todo("t-2", "Two", 4)]), 4, None), // Short of room after the fill: the pull since the cursor goes on. page(json!([todo("t-3", "Three", 5)]), 5, None), ]); let mut object = transport(&exchange, &replica).stopping_for(Some(guard)); let paths = |exchange: &Arc| exchange.seen().iter().map(|s| s.path.clone()).collect::>(); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("short of room, the pass still ends well"); assert_eq!(paths(&exchange), vec!["/v1/act".to_string()], "the write went up and no page was asked"); assert_eq!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"), 0, "nothing waits"); assert_eq!(cursor(&replica), None, "the fill has not begun"); set(1); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("a fill stopped part way is no failure"); assert_eq!(exchange.calls(), 2, "{:?}", paths(&exchange)); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("One")); let held = cursor(&replica); assert!(held.as_deref().is_some_and(|held| held.ends_with(".page-two")), "{held:?}"); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("still short of room"); assert_eq!(exchange.calls(), 2, "the stopped fill asks nothing: {:?}", paths(&exchange)); assert_eq!(cursor(&replica), held, "it waits where it stood"); set(-1); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the fill goes on"); assert_eq!(exchange.nth(2).path, "/v1/sync?cursor=page-two"); assert_eq!(cursor(&replica).as_deref(), Some("v0000000000000004")); set(0); run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).expect("the sync after the fill"); assert_eq!(exchange.nth(3).path, "/v1/sync?since=4&limit=5000&window=message:90"); assert_eq!(todo_title(&replica, "t-3").as_deref(), Some("Three"), "short of room, the sync still brings what changed"); } /// RULE (owner, 28 Nov 2026): every column a phone keeps on a copy that the object cannot rebuild (every list in /// `PHONE_KEPT_COLUMNS`) travels with its row, sealed: on a sealed table it is among the columns the phone sends, and /// a kept column on a table that is not sealed fails here, since it would go in the clear or not at all. A new kept /// column that does not travel fails this test. #[test] fn every_column_a_phone_keeps_travels_sealed_with_its_row() { for list in super::PHONE_KEPT_COLUMNS { for (table, columns) in list.iter() { let definition: Value = serde_json::from_slice(cotton_core::kit::table_file(table).expect("a kit table")).expect("it reads"); let map = ObjectTables::personal().with_defined([&definition]).expect("a map"); let held = map.object(table).expect("the table maps"); assert!(held.seal.is_some(), "{table} keeps {columns:?} on the phone: it must be sealed for them to travel"); for column in columns.iter() { let defined = definition["columns"].as_array().into_iter().flatten().any(|c| c["key"] == json!(column)); assert!(defined, "{table}.{column} is kept on the phone but no kit column"); let sent = held.written.iter().any(|w| w == column) || held.columns.iter().any(|(object, _, _)| object == column); assert!(sent, "{table}.{column} is kept only on the phone: it must travel sealed with its row"); } } } } // ── RESTORE 2: the server's generation ─────────────────────────────────────────────────────────────────────────── const G1: &str = "AAAAAAAAAAAAAAAAAAAAAA"; const G2: &str = "BBBBBBBBBBBBBBBBBBBBBB"; const RESTORED_TO: &str = "2026-11-20T08:00:00.000Z"; fn generation_page(rows: Value, version: i64, generation: &str, restored_to: Option<&str>) -> Reply { let mut body = json!({"version": version, "rows": rows, "server_time": NOW, "generation": generation}); if let Some(at) = restored_to { body["restored_to"] = json!(at); } Reply::ok(&body.to_string()) } fn held_generation(replica: &crate::Replica) -> Option { cotton_store::cursors::read_cursors(&replica.driver).expect("the cursors").get(GENERATION_KEY).cloned() } /// A copy that has pulled once under `G1`. fn under_g1() -> (tempfile::TempDir, crate::layout::Layout, crate::Replica) { let (dir, layout, replica) = open_test_replica(); let exchange = ScriptedExchange::new([generation_page(json!([todo("t-1", "Ring the bank", 3)]), 3, G1, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("the first pass"); (dir, layout, replica) } /// RULE (RESTORE 2, phone 1): a copy holding no generation keeps the first one answered beside its cursor; the same /// one answered again goes on; every act it posts carries it. #[test] fn a_copy_keeps_the_first_generation_answered_and_posts_under_it() { let (_dir, _layout, replica) = under_g1(); assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Ring the bank")); assert_eq!(held_generation(&replica), Some(format!("g{G1}"))); queue_one_change(&replica, "Buy milk"); let exchange = ScriptedExchange::new([act_taken(), generation_page(json!([todo("t-2", "Water the plants", 4)]), 4, G1, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica), WORKSPACE, NOW).expect("the same generation goes on"); let act = exchange.nth(0); assert_eq!(act.path, "/v1/act"); assert_eq!(act.header(GENERATION_HEADER), Some(G1)); assert_eq!(todo_title(&replica, "t-2").as_deref(), Some("Water the plants")); assert_eq!(held_generation(&replica), Some(format!("g{G1}"))); // A server that says none (one from before it) says nothing, and a copy holding none posts none. let (_dir, _layout, bare) = open_test_replica(); queue_one_change(&bare, "Buy milk"); let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 4, None)]); run_cycle(&bare.driver, &mut transport(&exchange, &bare), WORKSPACE, NOW).expect("a pass"); assert_eq!(exchange.nth(0).header(GENERATION_HEADER), None); assert_eq!(held_generation(&bare), None); } /// RULE (RESTORE 2, phone 2): an answer under a new generation folds nothing: the pass stops before reading it, the /// cursor and the generation stay as they were, nothing is written on the row, and the passes are told what the /// answer said of the restore (never counted as a copy stuck). #[test] fn a_new_generation_folds_nothing_and_says_the_server_was_put_back() { let (_dir, _layout, replica) = under_g1(); let before = cursor(&replica); let exchange = ScriptedExchange::new((0..=STUCK_PASSES).map(|_| generation_page(json!([todo("t-1", "What the restore undid", 5), todo("t-9", "A row from the restore", 5)]), 5, G2, Some(RESTORED_TO))).collect::>()); let progress = SyncProgress::system(); let mut object = transport(&exchange, &replica).reporting_to(Arc::clone(&progress)); for _ in 0..STUCK_PASSES + 1 { assert!(run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).is_err(), "the pass stops"); } assert_eq!(todo_title(&replica, "t-1").as_deref(), Some("Ring the bank"), "nothing folded"); assert_eq!(todo_title(&replica, "t-9"), None, "nothing folded"); assert_eq!(cursor(&replica), before, "the cursor stands"); assert_eq!(held_generation(&replica), Some(format!("g{G1}")), "the generation stands"); assert_eq!(progress.restore_seen(), Some(ServerRestored { generation: Some(G2.to_string()), restored_to: Some(RESTORED_TO.to_string()) })); assert_eq!(progress.stuck(), None, "a restore is not a copy stuck"); assert!(exchange.seen().iter().all(|seen| seen.path != "/v1/act"), "nothing written on the row"); } /// RULE (RESTORE 2): a post refused `generation_moved` stops the pass there: the change and every one behind it stay /// queued as they are, never parked, retried or rewritten, nothing is pulled, and the passes are told. #[test] fn a_post_refused_generation_moved_stops_the_pass_and_keeps_every_change_queued() { let (_dir, _layout, replica) = under_g1(); queue_one_change(&replica, "Buy milk"); queue_one_change(&replica, "Ring the vet"); let queued = cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"); let exchange = ScriptedExchange::new([Reply::json(409, &json!({"code": GENERATION_MOVED, "message": "the server was put back", "generation": G2, "restored_to": RESTORED_TO}).to_string())]); let progress = SyncProgress::system(); let mut object = transport(&exchange, &replica).reporting_to(Arc::clone(&progress)); assert!(run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).is_err()); assert_eq!(exchange.calls(), 1, "one post, no other, no pull: {:?}", exchange.seen().iter().map(|s| s.path.clone()).collect::>()); assert_eq!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"), queued, "every change still queued"); assert!(replica.driver.all("SELECT op_id FROM _parked", &[]).expect("the parked").is_empty(), "nothing parked"); assert!(progress.restore_seen().is_some()); } /// RULE (RESTORE 2): an account held still (`503 account_frozen`) waits like any 5xx: the change stays queued, nothing /// is parked, the pass goes on to its pull, and the passes say it was held still until a pass meets it no more. #[test] fn an_account_held_still_keeps_its_changes_queued_and_says_so_until_it_answers() { let (_dir, _layout, replica) = under_g1(); queue_one_change(&replica, "Buy milk"); let frozen = || Reply::json(503, &json!({"code": ACCOUNT_FROZEN, "message": "the account is held still for a moment", "retry_after_s": 30}).to_string()).with_header("retry-after", "30"); let exchange = ScriptedExchange::new([frozen(), generation_page(json!([]), 3, G1, None)]); let progress = SyncProgress::system(); let _ = run_cycle(&replica.driver, &mut transport(&exchange, &replica).reporting_to(Arc::clone(&progress)), WORKSPACE, NOW); assert!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox") > 0, "still queued"); assert!(replica.driver.all("SELECT op_id FROM _parked", &[]).expect("the parked").is_empty(), "nothing parked"); assert!(progress.state().frozen, "said on the Sync page"); // A pull held still too: the pass fails quietly, never a copy stuck. let exchange = ScriptedExchange::new((0..2 * (STUCK_PASSES + 1)).map(|_| frozen()).collect::>()); let mut object = transport(&exchange, &replica).reporting_to(Arc::clone(&progress)); for _ in 0..STUCK_PASSES + 1 { assert!(run_cycle(&replica.driver, &mut object, WORKSPACE, NOW).is_err()); } assert!(progress.state().frozen); assert_eq!(progress.stuck(), None); // It answers again: the change goes, and the line goes. let exchange = ScriptedExchange::new([act_taken(), generation_page(json!([]), 3, G1, None)]); run_cycle(&replica.driver, &mut transport(&exchange, &replica).reporting_to(Arc::clone(&progress)), WORKSPACE, NOW).expect("a pass"); assert_eq!(cotton_store::outbox::pending_count(&replica.driver).expect("the outbox"), 0); assert!(!progress.state().frozen); }