//! UNSENT HEAL: what waits and will not go by itself is said, and the person sends it again or lets it go; a write//! let go is written down first. Synthetic rows only.use rusqlite::types::ValueasSqlValue;usesuper::*;usecrate::test_support::{open_test_replica, queue_one_change, WORKSPACE};const NOW: &str = "2026-11-26T10:00:00.000Z";fn now_ms() -> i64 { cotton_store::protocol::js::parse_date_ms(NOW).unwrap()}/// The one queued write that is not bookkeeping.fn the_write(db: &Driver) -> String { db.get("SELECT op_id FROM _outbox WHERE tbl <> 'cotton_authors'", &[]).unwrap().and_then(|row| row.text("op_id").map(str::to_string)).expect("a queued write")}/// The write refused under `error` (its code first), as a settle writes it, noted at `at`.fn refused_as(db: &Driver, op_id: &str, error: &str, at: &str) { db.run("UPDATE _outbox SET last_error = ?, queued_at = ? WHERE op_id = ?", &[SqlValue::Text(error.into()), SqlValue::Text("2026-11-01T10:00:00.000Z".into()), SqlValue::Text(op_id.into())]).unwrap();let code = error.split_once(':').map(|(code, _)| code); cotton_store::outbox::forget_refused(db, &[op_id.to_string()]).unwrap(); cotton_store::outbox::note_refused(db, op_id, code, at).unwrap();}const DAY_AGO: &str = "2026-11-25T09:00:00.000Z";/// The write moved from the queue to a park, as a pass's settle parks a push the server refused for good.fn parked_by_the_server(db: &Driver, op_id: &str) {let row = db.get("SELECT op_id, bytes, sig FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id.into())]).unwrap().expect("queued");let op = cotton_store::stored::outbox_row(&row).expect("a receipt"); cotton_store::rejected::park(db, &op, cotton_store::rejected::Direction::Push, cotton_store::rejected::Class::Conflict, "bad_column: the object has no column `pinned`", NOW).unwrap(); db.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op_id.into())]).unwrap();}/// RULE: each refusal class says whether it heals by itself.#[test]fn each_refusal_says_whether_it_heals() {for code in cotton_store::outbox::PASSING_CODES { assert_eq!(heal_of(code), Heal::Itself, "{code}"); }for code in ["seal_key_missing", "other", "bad_shape"] { assert_eq!(heal_of(code), Heal::Slowly, "{code}"); }for code in NEVER_HEALS { assert_eq!(heal_of(code), Heal::Never, "{code}"); }}/// RULE: a write that never heals is said at once; one that may never heal (no key) after a day; one on its way or/// moved never.#[test]fn what_cannot_heal_is_said_and_what_heals_is_not() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "an invented to-do");let db = &replica.driver;let op = the_write(db); assert!(stuck(db, now_ms()).unwrap().is_empty(), "a write on its way is not stuck"); refused_as(db, &op, "seal_column_clash: the row already carries sealed_enc", NOW);let said = stuck(db, now_ms()).unwrap(); assert_eq!((said.len(), said[0].code.as_str(), said[0].parked), (1, "seal_column_clash", false)); refused_as(db, &op, "seal_key_missing: no key for the data key", NOW); assert!(stuck(db, now_ms()).unwrap().is_empty(), "a key may still come, though the write was queued weeks ago"); assert_eq!(stuck(db, now_ms() + KEY_SAID_AFTER_MS).unwrap().len(), 1, "a day after its first lasting refusal it is said");}/// RULE (UNSENT HEAL 2, review item 3): a refusal that passes never counts, however old the write: a change queued/// weeks ago that meets a 503, a 429, a server older than the build or a moved row is not "can't be sent".#[test]fn a_passing_refusal_never_counts_however_old_the_write() {let (_dir, _layout, replica) = open_test_replica(); queue_one_change(&replica, "an invented to-do");let db = &replica.driver;let op = the_write(db);for code in cotton_store::outbox::PASSING_CODES { refused_as(db, &op, &format!("{code}: it passes"), "2026-11-01T10:00:00.000Z"); assert!(stuck(db, now_ms()).unwrap().is_empty(), "{code}"); assert_eq!(cotton_store::outbox::refused_since(db, &op).unwrap(), None, "{code} is never noted"); }}/// RULE (UNSENT HEAL 2, review item 5): the acts apply the same age rule: a key-missing change minutes old is not/// let go or sent again, even named.#[test]fn the_acts_never_reach_a_change_that_may_still_heal() {let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "an invented to-do");let db = &replica.driver;let op = the_write(db); refused_as(db, &op, "seal_key_missing: no key yet", NOW); assert_eq!(let_go(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), 0); assert_eq!(send_again(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), (0, 0, 0)); assert!(db.get("SELECT 1 AS here FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().is_some()); refused_as(db, &op, "seal_key_missing: no key yet", DAY_AGO); assert_eq!(send_again(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), (1, 0, 0), "a day on, it is reached"); assert_eq!(cotton_store::outbox::refused_since(db, &op).unwrap(), None, "offered as new, its first refusal forgotten");}/// RULE: a push the server refused for good is said; Send again queues it again past the ceiling; Let go writes it/// down and ends the park; the row stays on this phone.#[test]fn a_refused_push_is_said_sent_again_and_let_go_written_down() {let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "an invented to-do");let db = &replica.driver;let op = the_write(db); parked_by_the_server(db, &op); db.run("UPDATE _parked SET tries = 9 WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap();let said = stuck(db, now_ms()).unwrap(); assert_eq!((said.len(), said[0].parked, said[0].code.as_str()), (1, true, "refused")); assert!(said[0].reason.contains("bad_column")); assert_eq!(send_again(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), (1, 0, 0)); assert!(db.get("SELECT 1 AS here FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().is_some(), "queued again past the ceiling"); assert!(stuck(db, now_ms()).unwrap().is_empty(), "queued again, it is on its way");// Refused again: parked as before. db.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap(); assert_eq!(stuck(db, now_ms()).unwrap().len(), 1); assert_eq!(let_go(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), 1); assert!(stuck(db, now_ms()).unwrap().is_empty()); assert!(db.get("SELECT 1 AS here FROM _parked WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().is_none(), "its park ended");let written = crate::unsent::discarded(&layout, WORKSPACE); assert_eq!(written.len(), 1); assert_eq!(written[0].changes[0].op_id, op); assert_eq!(written[0].reasons[&op], "bad_column", "the code only, never the server's words (review item 6)"); assert!(db.get("SELECT 1 AS here FROM cotton_todos WHERE title = 'an invented to-do'", &[]).unwrap().is_some(), "the row stays on this phone");}/// RULE: a queued write that cannot seal is let go only once written down; one never named stays queued.#[test]fn a_queued_write_let_go_is_written_down_and_leaves_the_queue() {let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "an invented to-do");let db = &replica.driver;let op = the_write(db); assert_eq!(let_go(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), 0, "a write on its way is never let go"); refused_as(db, &op, "seal_bad_input: a version of 0", NOW); assert_eq!(send_again(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), (1, 0, 0)); assert!(stuck(db, now_ms()).unwrap().is_empty(), "offered as new"); refused_as(db, &op, "seal_bad_input: a version of 0", NOW); assert_eq!(let_go(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), 1); assert!(db.get("SELECT 1 AS here FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().is_none()); assert_eq!(crate::unsent::discarded(&layout, WORKSPACE)[0].changes[0].op_id, op);}/// RULE (UNSENT HEAL 2, review item 4): Send again on a refused change whose row is gone from this phone would be/// taken without a request and its park cleared with nothing said: it is written down and let go instead.#[test]fn send_again_of_a_change_whose_row_is_gone_writes_it_down() {let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "an invented to-do");let db = &replica.driver;let op = the_write(db);let row = db.get("SELECT row_id FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().and_then(|r| r.text("row_id").map(str::to_string)).unwrap(); parked_by_the_server(db, &op); db.run("DELETE FROM cotton_todos WHERE id = ?", &[SqlValue::Text(row)]).unwrap(); assert_eq!(send_again(db, &layout, WORKSPACE, std::slice::from_ref(&op), NOW).unwrap(), (0, 1, 0)); assert!(db.get("SELECT 1 AS here FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().is_none(), "not queued to go nowhere"); assert!(db.get("SELECT 1 AS here FROM _parked WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().is_none()); assert_eq!(crate::unsent::discarded(&layout, WORKSPACE)[0].changes[0].op_id, op, "written down");}/// RULE (UNSENT HEAL 2): Let go is the person's alone: nothing in the crates calls it but the Sync page's act.#[test]fn let_go_is_the_persons_act_alone() {let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap().to_path_buf();letmut callers = Vec::new();letmut stack = vec![root.clone()];whileletSome(dir) = stack.pop() {for entry in std::fs::read_dir(&dir).unwrap().flatten() {let path = entry.path();if path.is_dir() {if !path.ends_with("target") { stack.push(path); } } elseif path.extension().is_some_and(|e| e == "rs") && !path.to_string_lossy().ends_with("_tests.rs") && !path.ends_with("unsent_heal.rs") {if std::fs::read_to_string(&path).unwrap_or_default().contains("unsent_heal::let_go(") { callers.push(path.strip_prefix(&root).unwrap().to_string_lossy().to_string()); } } } } assert_eq!(callers, ["cotton-ffi/src/methods/sync.rs"]);}/// RULE (UNSENT HEAL 2 review, follow-up 3): `stuck` is read on every draw of a Sync line; with 5,000 writes queued/// it is one query, never a read per write. Invented rows: 2,500 never refused, 1,500 without a key for a day, 1,000/// offline.#[test]fn stuck_reads_five_thousand_queued_writes_in_one_query() {let (_dir, _layout, replica) = open_test_replica();let db = &replica.driver; db.transaction(|db| {for i in0..5_000 {let op_id = format!("op-{i:05}");let error = match i % 10 { 0..=4 => None, 5..=7 => Some("seal_key_missing: no key yet"), _ => Some("offline: no answer") }; db.run("INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, last_error) VALUES (?, 'change', 'device:invented', 'cotton_todos', ?, '0', 1, '2026-11-01T10:00:00.000Z', x'00', ?)", &[SqlValue::Text(op_id.clone()), SqlValue::Text(format!("todo-{i:05}")), error.map_or(SqlValue::Null, |e| SqlValue::Text(e.into()))], )?;ifletSome(error) = error { cotton_store::outbox::note_refused(db, &op_id, error.split_once(':').map(|(code, _)| code), DAY_AGO)?; } }Ok(()) }) .unwrap();let started = std::time::Instant::now();let said = stuck(db, now_ms()).unwrap();let took = started.elapsed(); eprintln!("stuck over 5,000 queued writes: {} said in {took:?}", said.len()); assert_eq!(said.len(), 1_500); assert!(took < std::time::Duration::from_secs(2), "took {took:?}");}/// RULE (UNSENT HEAL 2 review, follow-up 4): the count of changes kept only on this phone stays until the Sync page/// has shown it once, though what was written down is filed within a pass; one kept after the page drew stays.#[test]fn the_kept_count_stays_until_the_page_has_shown_it() {let (_dir, layout, _replica) = open_test_replica(); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 0); note_kept_here(&layout, WORKSPACE, 1).unwrap(); note_kept_here(&layout, WORKSPACE, 2).unwrap();crate::unsent::forget_discarded(&layout, WORKSPACE, &crate::unsent::discarded(&layout, WORKSPACE)); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 3, "filing what was written down leaves the count"); note_kept_here(&layout, WORKSPACE, 1).unwrap(); kept_here_seen(&layout, WORKSPACE, 3).unwrap(); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 1, "the one kept after the page drew stays"); kept_here_seen(&layout, WORKSPACE, 1).unwrap(); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 0);}/// RULE (UNSENT HEAL 3 review): what an older build wrote down of changes kept only here, not yet filed, is the/// count's start after the upgrade; it migrates once.#[test]fn the_kept_count_migrates_what_an_older_build_wrote_down() {let (_dir, layout, replica) = open_test_replica(); queue_one_change(&replica, "an invented to-do");let op = the_write(&replica.driver);let row = replica.driver.get("SELECT op_id, bytes, sig FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.clone())]).unwrap().unwrap();let change = crate::unsent::UnsentChange::of(&cotton_store::stored::outbox_row(&row).unwrap(), crate::unsent::Waiting::Queued);// Written down before the count had a file (an older build), and one since (counted by a file that build removed at 0: seen).crate::unsent::record_discarded(&layout, WORKSPACE, vec![change.clone()], std::collections::BTreeMap::new(), NEVER_CARRIED_WHY, "2026-11-25T10:00:00.000Z").unwrap();crate::unsent::record_discarded(&layout, WORKSPACE, vec![change], std::collections::BTreeMap::new(), NEVER_CARRIED_WHY, "2026-11-26T18:00:00.000Z").unwrap(); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 1, "the older build's entry counts; the one already seen does not");// Saved on that first read: a pass filing the entries next leaves the count.crate::unsent::forget_discarded(&layout, WORKSPACE, &crate::unsent::discarded(&layout, WORKSPACE)); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 1, "saved at the first read, kept after filing"); note_kept_here(&layout, WORKSPACE, 1).unwrap(); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 2); kept_here_seen(&layout, WORKSPACE, 2).unwrap(); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 0, "seen, and never migrated again");}/// RULE (UNSENT HEAL 3 review): a pass noting kept changes and the page marking them seen never lose a count.#[test]fn the_kept_count_loses_nothing_to_racing_writers() {let (_dir, layout, _replica) = open_test_replica(); note_kept_here(&layout, WORKSPACE, 50).unwrap();let threads: Vec<_> = (0..8).map(|_| { let layout = layout.clone(); std::thread::spawn(move || for _ in0..25 { note_kept_here(&layout, WORKSPACE, 1).unwrap() }) }).collect();let seen = { let layout = layout.clone(); std::thread::spawn(move || for _ in0..50 { kept_here_seen(&layout, WORKSPACE, 1).unwrap() }) }; threads.into_iter().for_each(|t| t.join().unwrap()); seen.join().unwrap(); assert_eq!(kept_here_only(&layout, WORKSPACE).unwrap(), 200, "50 + 200 noted - 50 seen");}/// RULE (KEPT COUNT review): an unreadable count is an error, never "no file yet" (which would migrate again).#[test]fn a_garbled_kept_count_is_an_error() {let (_dir, layout, _replica) = open_test_replica(); std::fs::write(kept_path(&layout, WORKSPACE), b"not json").unwrap(); assert!(kept_here_only(&layout, WORKSPACE).is_err()); assert!(note_kept_here(&layout, WORKSPACE, 1).is_err()); assert_eq!(std::fs::read(kept_path(&layout, WORKSPACE)).unwrap(), b"not json", "nothing written over it");}