//! Conformance, lane 3a: THE OUTBOX — the Rust twin of //! `harness/writeLocal.test.ts` (spec R9). //! //! The fold lane proves the store agrees about ops somebody else made. This one //! asks the other half: given the same list of local changes, the same device //! and the same instant, does it QUEUE what was recorded? That is what a //! phone's `_outbox` holds while it is offline, and a difference here is a row //! that syncs differently depending on which store wrote it. //! //! Two fields are excluded from the op comparison, and both are named out loud //! rather than quietly dropped: //! //! opId A ULID. It came from `crypto.getRandomValues` when the //! answers were first recorded, which takes no seed, and it //! comes from a fixture seed now — either way it is an id //! nothing outside this crate could be held to. The lane //! compares the SHAPE instead: same count, same order, strictly //! ascending, a real Crockford alphabet, and the same ids in //! `_outbox` as in the returned ops. //! schemaVersion 46 when the answers were first recorded, 1 in the Rust era, //! by design (spec R2: the Rust era starts its own numbering). //! Neither fold reads it; it is the server's guard. //! //! Everything else — the hlc, the device, the table, the row, the patch JSON //! field for field, `queued_at`, and the whole rest of the file the local write //! touched — is compared exactly. use std::collections::BTreeSet; use cotton_store::driver::Driver; use cotton_store::actor::{Actor, JobName}; use cotton_store::mint::{changes_of as minted_changes, mint, Act, Clock, Held, History}; use cotton_store::outbox::LocalChange; use cotton_store::protocol::types::CottonOp; use cotton_store::protocol::ulid::Monotonic; use serde_json::Value as JsonValue; use cotton_conformance::{ baseline, canonical, differences, state_of, vectors, Vectors, Xorshift64, OUTBOX_EXCLUSIONS, WRITE_LOCAL_SEED, }; fn changes_of(vectors: &Vectors) -> Vec { let mut changes: Vec = serde_json::from_value(vectors.write_local.changes.clone()) .expect("the recorded changes parse as local changes"); // A delete names its kind to `mint`, and the kind is never serialised: a // recorded delete is the ordinary one, a Retract. for change in &mut changes { if change.kind == cotton_store::protocol::types::OpKind::Delete { change.delete = Some(cotton_store::mint::Delete::Retract); } } changes } /// The local write, run the way the CLI ran it: clock and randomness pinned. /// /// The one write path is `mint`. The file's author is set to the device the /// answers were recorded for, so every stamp ends where the recording's did — /// a fresh file would coin its own `device:` on this first write and put /// its fact ahead of these ops, which the recording predates. fn write(db: &Driver, vectors: &Vectors, changes: &[LocalChange]) -> Vec { let mut rng = Xorshift64::seeded(WRITE_LOCAL_SEED); let mut ids = Monotonic::new(|bytes: &mut [u8]| rng.fill(bytes)); db.run( "UPDATE _meta SET author_id = ?", &[rusqlite::types::Value::Text(vectors.write_local.device.clone())], ) .expect("the file takes the recorded device as its author"); mint( db, &Act { actor: Actor::DeviceJob(JobName::named("conformance").expect("a job name")), verb: "write".to_string(), history: History::None, changes: minted_changes(db, changes), }, &Clock::wall(vectors.write_local.now_ms), &mut ids, Held::Replica, ) .expect("the local write lands") .ops } /// One op with its two unseedable fields removed, ready to compare. fn comparable(op: &CottonOp) -> JsonValue { let mut value = serde_json::to_value(op).expect("an op serialises"); let fields = value.as_object_mut().expect("an op is an object"); fields.remove("opId"); fields.remove("schemaVersion"); value } #[test] fn stamps_hlcs_that_ascend_from_the_instant_it_was_given() { let vectors: Vectors = vectors(); let db = baseline(&vectors.baseline); let ops = write(&db, &vectors, &changes_of(&vectors)); let stamps: Vec<&str> = ops.iter().map(|op| op.hlc.as_str()).collect(); let mut ascending = stamps.clone(); ascending.sort_unstable(); assert_eq!(stamps, ascending, "the stamps are not in order"); assert_eq!( stamps.iter().collect::>().len(), stamps.len(), "two ops share a stamp" ); let now = vectors.write_local.now_ms; for stamp in &stamps { assert!( stamp.starts_with(&format!("{now:013}:")), "{stamp} is not at the given instant" ); assert!( stamp.ends_with(&format!(":{}", vectors.write_local.device)), "{stamp} names another device" ); } // Same millisecond, so the counter is what separates them: 0000, 0001, … let counters: Vec<&str> = stamps .iter() .map(|stamp| stamp.split(':').nth(1).expect("a counter")) .collect(); let expected: Vec = (0..stamps.len()).map(|at| format!("{at:04}")).collect(); assert_eq!(counters, expected); } #[test] fn gives_every_op_a_distinct_ascending_id_and_the_file_holds_exactly_those() { // The one claim left after `opId` is excluded from the row comparison: the // ids are ULIDs, unique, and in the order the ops were queued — which is // what makes the outbox drain deterministic. let vectors: Vectors = vectors(); let db = baseline(&vectors.baseline); let ours = write(&db, &vectors, &changes_of(&vectors)); let ids: Vec<&str> = ours.iter().map(|op| op.op_id.as_str()).collect(); assert_eq!( ids.iter().collect::>().len(), ids.len(), "a duplicate op id" ); let mut ascending = ids.clone(); ascending.sort_unstable(); assert_eq!(ids, ascending, "the op ids are not in queue order"); for id in &ids { assert_eq!(id.len(), 26, "{id} is not a ULID"); assert!( id.chars() .all(|character| "0123456789ABCDEFGHJKMNPQRSTVWXYZ".contains(character)), "{id} is not Crockford base32" ); } // And what the file holds is what was returned, in the same order — the // returned ops are not a report of an intention, they are the queue. let queued: Vec = db .all("SELECT op_id FROM _outbox ORDER BY op_id", &[]) .expect("the outbox reads") .iter() .map(|row| row.text("op_id").expect("an op id").to_string()) .collect(); assert_eq!(queued, ids); } #[test] fn the_same_seed_gives_the_same_ids_twice() { // The randomness comes from a parameter (spec R7: no RNG in the library), so // a failing run is reproducible from the seed alone. If this ever goes red // the ids stopped being a function of the seed. let vectors: Vectors = vectors(); let changes = changes_of(&vectors); let first = baseline(&vectors.baseline); let second = baseline(&vectors.baseline); assert_eq!( write(&first, &vectors, &changes), write(&second, &vectors, &changes) ); } #[test] fn the_comparison_catches_an_outbox_that_drifted() { // The seeded defect, permanent and negative rather than a breaking commit: // the recorded answer perturbed the four ways a real outbox regression // perturbs it, each run through the comparison the lane above uses. let vectors: Vectors = vectors(); let changes = changes_of(&vectors); let db = baseline(&vectors.baseline); let ours = write(&db, &vectors, &changes); let actual = state_of(&db); let mut minted = vectors.trigger_minted.clone(); minted.insert( "_outbox".to_string(), OUTBOX_EXCLUSIONS .iter() .map(|name| name.to_string()) .collect(), ); // (a) a queued receipt the store wrote differently — the row that would // sync the wrong value. let mut patched = cotton_conformance::StateVector { tables: vectors.write_local.state.tables.clone(), fts: vectors.write_local.state.fts.clone(), }; let outbox = patched .tables .get_mut("_outbox") .expect("the local write queued"); outbox[0].insert("bytes".to_string(), serde_json::json!({ "s": "{}" })); let found = differences(&patched, &actual, &minted); assert!( found.iter().any(|line| line.starts_with("_outbox row")), "a changed receipt went unnoticed: {found:?}" ); // (b) an op that never reached the queue at all. let mut short = cotton_conformance::StateVector { tables: vectors.write_local.state.tables.clone(), fts: vectors.write_local.state.fts.clone(), }; short.tables.get_mut("_outbox").expect("the queue").pop(); let found = differences(&short, &actual, &minted); assert!( found.iter().any(|line| line.starts_with("_outbox:")), "a missing queued op went unnoticed: {found:?}" ); // (c) the delete's tombstone, which is the half of a local delete that is // not in the outbox at all. let mut untombstoned = cotton_conformance::StateVector { tables: vectors.write_local.state.tables.clone(), fts: vectors.write_local.state.fts.clone(), }; untombstoned.tables.remove("_tombstones"); let found = differences(&untombstoned, &actual, &minted); assert!( found.iter().any(|line| line.starts_with("_tombstones:")), "a missing tombstone went unnoticed: {found:?}" ); // (d) an op whose hlc drifted, compared the way the lane compares ops — // `opId` and `schemaVersion` are the only two fields excluded, so a // changed stamp has nowhere to hide. let mut drifted = comparable(&ours[0]); drifted.as_object_mut().expect("an op is an object").insert( "hlc".to_string(), JsonValue::String("0:0000:device:x".into()), ); assert_ne!( canonical(&drifted), canonical(&vectors.write_local.ops[0]), "a changed hlc went unnoticed" ); // The perturbations above are about the recorded answer; this is the file // itself, and it says the queue is really there to be compared. let rows: i64 = db .get("SELECT count(*) AS n FROM _outbox", &[]) .expect("the outbox counts") .and_then(|row| row.int("n")) .expect("a count"); assert_eq!(rows, changes.len() as i64); }