//! The two names, over a real replica. //! //! The FOLD's own cases live in `cotton_store::rejected`. What is held here is //! the boundary: the names are in the tables the app reads, the list is a //! projection rather than a row, and the retry actually moves the file. use serde_json::{json, Value}; use cotton_store::actor::{Actor, JobName}; use cotton_store::mint::{Change, Kind}; use cotton_store::protocol::types::CottonOp; use cotton_store::rejected::{park, Class, Direction}; use crate::shell::client::phone_tests::attached; use crate::shell::client::ClientController; use super::{over, METHODS}; const PEER: &str = "device:peer"; const WHEN: &str = "2026-09-08T09:00:00.000Z"; fn hlc(ms: i64) -> String { format!("{ms:013}:0000:{PEER}") } thread_local! { /// A file at this build's schema, for the receipts the cases build: a /// receipt is made against the table's own columns and codecs. static SCHEMA: cotton_store::driver::Driver = { let db = cotton_store::driver::Driver::open_in_memory().expect("opens"); cotton_store::migrate::migrate_store(&db).expect("migrates"); db }; } /// The peer's op, with its receipt as `mint` would make it. fn peer_op(op_id: &str, kind: Kind, patch: Value, ms: i64) -> CottonOp { let change = Change { kind, table: "cotton_todos".to_string(), row_id: "t1".to_string(), patch: patch.as_object().cloned(), delete: (kind == Kind::Retract).then_some(cotton_store::mint::Delete::Retract), }; let actor = Actor::device_job(JobName::named("test").expect("a job name")); SCHEMA .with(|db| cotton_store::wire::op_of_change(db, &change, &hlc(ms), PEER, &actor, op_id.to_string())) .expect("the receipt") } /// The op that CREATES the todo, and the one that only AMENDS it — the second /// cannot stand alone, which is the whole of the case. fn birth(title: &str, ms: i64) -> CottonOp { peer_op( "op-birth", Kind::Create, json!({ "id": "t1", "title": title, "workspace_id": crate::fixture::WORKSPACE, "created_at": WHEN, "updated_at": WHEN, }), ms, ) } fn amendment(title: &str, ms: i64) -> CottonOp { peer_op("op-amend", Kind::Change, json!({ "title": title }), ms) } /// Park an op in this phone's replica, the way an exchange would. fn parked(client: &ClientController, op: &CottonOp, direction: Direction, class: Class, reason: &str) { client .with_writer(|file| { park(file.driver, op, direction, class, reason, WHEN).map_err(|error| error.to_string()) }) .expect("a park"); } fn title(client: &ClientController) -> Option { client .with_writer(|file| { Ok(file .driver .get("SELECT title FROM cotton_todos WHERE id = 't1'", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.text("title").map(str::to_string))) }) .expect("a read") } #[test] fn both_names_are_on_every_build_and_in_the_method_tables() { for method in METHODS { assert!( crate::methods::CLIENT_METHODS.contains(&method), "{method} is a client verb" ); assert!( crate::methods::ALL_METHODS.contains(&method), "{method} is not in ALL_METHODS, so the partition test cannot see it" ); assert!( crate::methods::methods().iter().any(|name| name == method), "{method} is named but this build does not answer it" ); } } #[test] fn the_list_projects_the_row_and_never_hands_over_the_patch() { let (_dir, client) = attached(); parked( &client, &amendment("Renamed", 1_787_394_600_001), Direction::Pull, Class::Conflict, "NOT NULL constraint failed: cotton_todos.created_at", ); let answer = over(&client, "sync.rejected", &json!({})).expect("a list"); assert_eq!(answer["count"], json!(1)); let row = &answer["rejected"][0]; assert_eq!(row["opId"], json!("op-amend")); assert_eq!(row["table"], json!("cotton_todos")); assert_eq!(row["rowId"], json!("t1")); assert_eq!(row["direction"], json!("pull")); assert_eq!(row["at"], json!(WHEN)); assert_eq!(row["retriedAt"], Value::Null); assert_eq!(row["author"], json!(PEER)); assert_eq!(row["retryable"], json!(true)); assert!( row.get("patch").is_none(), "the patch is a row of somebody's database in whatever shape the table \ has — a screen that drew it would be drawing columns nothing designed" ); } #[test] fn a_write_the_peer_refused_is_listed_and_marked_unretryable() { let (_dir, client) = attached(); parked( &client, &birth("Ours", 1_787_394_600_000), Direction::Push, Class::Conflict, "UNIQUE constraint failed", ); let answer = over(&client, "sync.rejected", &json!({})).expect("a list"); assert_eq!(answer["rejected"][0]["direction"], json!("push")); assert_eq!( answer["rejected"][0]["retryable"], json!(false), "no local fold can change the PEER's verdict, and a button that does \ nothing is worse than no button" ); } #[test] fn the_retry_folds_the_parked_write_once_its_row_is_there() { let (_dir, client) = attached(); parked( &client, &amendment("Renamed", 1_787_394_600_001), Direction::Pull, Class::Conflict, "NOT NULL constraint failed: cotton_todos.created_at", ); // The creation arrives by the ordinary road. client .with_writer(|file| { cotton_store::fold::fold_ops(file.driver, &[birth("Original", 1_787_394_600_000)]) .map_err(|error| error.to_string()) }) .expect("the creation"); let answer = over(&client, "sync.retryRejected", &json!({})).expect("a retry"); assert_eq!(answer["folded"], json!(["op-amend"])); assert_eq!(answer["stillRejected"], json!([])); assert_eq!(title(&client).as_deref(), Some("Renamed")); assert_eq!( over(&client, "sync.rejected", &json!({})) .expect("a list")["count"], json!(0) ); } #[test] fn a_retry_that_fails_again_answers_the_reason_rather_than_a_refusal() { let (_dir, client) = attached(); // A create under a workspace this file has never held. (An amendment alone // is no longer a wall: a change to a row nothing created arrives dormant // and waits for its create, so it folds.) let orphan = peer_op( "op-orphan", Kind::Create, json!({ "id": "t1", "title": "Orphaned", "workspace_id": "99999999-9999-4999-8999-999999999999", "created_at": WHEN, "updated_at": WHEN, }), 1_787_394_600_001, ); parked( &client, &orphan, Direction::Pull, Class::Conflict, "FOREIGN KEY constraint failed", ); // Nothing put the workspace there, so the fold meets the same wall. The // METHOD still succeeds: "it did not land, and here is why" is an answer, // and a refusal would lose the reason. let answer = over( &client, "sync.retryRejected", &json!({ "ids": ["op-orphan"] }), ) .expect("a retry"); assert_eq!(answer["folded"], json!([])); assert_eq!(answer["stillRejected"][0]["opId"], json!("op-orphan")); assert!( answer["stillRejected"][0]["reason"] .as_str() .is_some_and(|reason| reason.contains("FOREIGN KEY")), "{answer}" ); assert_eq!(title(&client), None); } /// Every line the bus replays to a subscriber, collected through the `ctx` /// pointer, which is a `Mutex>` the test owns. extern "C" fn collect(ctx: *mut std::ffi::c_void, line: *const std::ffi::c_char) { let seen = unsafe { &*(ctx as *const std::sync::Mutex>) }; let text = unsafe { std::ffi::CStr::from_ptr(line) }.to_string_lossy().to_string(); seen.lock().expect("the record").push(text); } // RULE: a retry that folds a parked write says which tables moved — the same `data` event a pull's fold sends — so a list showing that row reads it again (architect 1805: after a write, the list and its counts are read again). #[test] fn a_retry_that_folds_says_which_tables_moved() { let (_dir, client) = attached(); parked( &client, &amendment("Renamed", 1_787_394_600_001), Direction::Pull, Class::Conflict, "NOT NULL constraint failed: cotton_todos.created_at", ); client .with_writer(|file| { cotton_store::fold::fold_ops(file.driver, &[birth("Original", 1_787_394_600_000)]) .map_err(|error| error.to_string()) }) .expect("the creation"); over(&client, "sync.retryRejected", &json!({})).expect("a retry"); // No subscriber yet, so the bus buffered everything; subscribing replays it. let seen = Box::new(std::sync::Mutex::new(Vec::::new())); let bus = client.events_for_tests(); bus.subscribe(&*seen as *const _ as *mut std::ffi::c_void, Some(collect)); bus.subscribe(std::ptr::null_mut(), None); let events: Vec = seen .lock() .expect("the record") .iter() .map(|line| serde_json::from_str(line).expect("json")) .collect(); assert!( events.iter().any(|event| event["kind"] == "data" && event["payload"]["tables"].as_array().is_some_and(|tables| tables.contains(&json!("cotton_todos")))), "no data event names cotton_todos after the retry folded it: {events:?}" ); }