//! A row deleted and written again in ONE batch (3a): the writer collects a//! delete and then an upsert of the same (table, row id), and `changes_of`//! turns them into receipts. The upsert must be the row's CREATE — the delete//! before it is the row's retract, and a change above a retract with no create//! above it is dormant (3.7 point 2), so reading the upsert as a change would//! make the rewritten row vanish on this file and on every peer.//!//! The case that found it: an edge table with a unique index on a pair, whose//! writer deletes the edge and inserts it again in one write. A unique-index//! table is the shape used here (`cotton_voice_vocabulary`, unique on//! `(workspace_id, lower(term))`), so the retract has to take the old row out//! before the create puts the pair back.use cotton_store::actor::{Actor, JobName};use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::fold::{arrive, Arrival};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{changes_of, first_author, mint, Act, AuthorReason, Clock, Held, History, IdSource, Kind};use cotton_store::outbox::LocalChange;use cotton_store::protocol::types::{CottonOp, OpKind};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::Driver;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};constT0: i64 = 1_759_480_000_000;const TABLE: &str = "cotton_voice_vocabulary";structIds(u32, &'static str);implIdSourceforIds {fn next_op_id(&mutself, _now_ms: i64) -> cotton_store::Result<String> {self.0 += 1;Ok(format!("{}-{:04}", self.1, self.0)) }}structDev { db: Driver, ids: Ids, fact: CottonOp,/// Every op this file minted, in order — what it hands a peer. minted: Vec<CottonOp>,}fn device(tag: &'static str) -> Dev {let db = file_at_version(SCHEMA_VERSION); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: format!("device:{tag}"), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds"); seed_workspace_row(&db);letmut ids = Ids(0, tag);let author = first_author(&db, &format!("key-{tag}"), Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served) .expect("the author");Dev { db, ids, fact: author.fact, minted: Vec::new() }}fn term(row_id: &str, term: &str, source: &str) -> Map<String, Value> { json!({"id": row_id, "workspace_id": WORKSPACE, "term": term, "source": source, "created_at": NOW}) .as_object() .expect("an object") .clone()}fn upsert(row_id: &str, patch: Map<String, Value>) -> LocalChange {LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: TABLE.to_string(), row_id: row_id.to_string(), patch: Some(patch) }}fn delete(row_id: &str) -> LocalChange {LocalChange::delete(TABLE, row_id).retract()}implDev {/// One writer's batch, read by `changes_of` and minted as one act.fn write(&mutself, at_ms: i64, batch: &[LocalChange]) {let act = Act { actor: Actor::device_job(JobName::named("test").expect("a job name")), verb: "test".to_string(), history: History::None, changes: changes_of(&self.db, batch), };let minted = mint(&self.db, &act, &Clock::wall(at_ms), &mutself.ids, Held::Served).expect("mints");self.minted.extend(minted.ops); }fn row(&self, row_id: &str) -> Option<(String, String)> {self.db .get(&format!("SELECT term, source FROM {TABLE} WHERE id = ?"), &[SqlValue::Text(row_id.to_string())]) .expect("reads") .map(|row| (row.text("term").unwrap_or_default().to_string(), row.text("source").unwrap_or_default().to_string())) }fn rows(&self) -> Vec<(String, String, String)> {self.db .all(&format!("SELECT id, term, source FROM {TABLE} ORDER BY id"), &[]) .expect("reads") .iter() .map(|row| { ( row.text("id").unwrap_or_default().to_string(), row.text("term").unwrap_or_default().to_string(), row.text("source").unwrap_or_default().to_string(), ) }) .collect() }}/// A second file that hears everything `from` minted, through the wire form/// (serialized and read back), in the order it was minted.fn replay(from: &Dev) -> Dev {let to = device("b");let wire = serde_json::to_string(&from.minted).expect("serializes");let ops: Vec<CottonOp> = serde_json::from_str(&wire).expect("reads back");let fact = arrive(&to.db, std::slice::from_ref(&from.fact), Arrival::Handed).expect("folds the fact"); assert!(fact.rejected.is_empty(), "the author fact folds: {:?}", fact.rejected);let result = arrive(&to.db, &ops, Arrival::Handed).expect("folds"); assert!(result.rejected.is_empty(), "nothing is refused: {:?}", result.rejected); assert!(result.skipped_stale.is_empty(), "nothing is stale: {:?}", result.skipped_stale); to}/// RULE: Within one batch, an upsert that follows a delete of the same row is that row's create, so the rewritten row stays present with exactly its new values, here and on a peer.#[test]fn a_delete_then_an_upsert_of_the_same_row_in_one_batch_leaves_the_new_row() {letmut a = device("a"); a.write(T0, &[upsert("v1", term("v1", "cotton", "manual"))]); assert_eq!(a.row("v1"), Some(("cotton".to_string(), "manual".to_string())));let batch = [delete("v1"), upsert("v1", term("v1", "Cotton", "auto"))];let kinds: Vec<Kind> = changes_of(&a.db, &batch).iter().map(|c| c.kind).collect(); assert_eq!(kinds, vec![Kind::Retract, Kind::Create], "the upsert after the delete is the row's create"); a.write(T0 + 1_000, &batch); assert_eq!(a.row("v1"), Some(("Cotton".to_string(), "auto".to_string())), "the rewritten row is present with its new values");let b = replay(&a); assert_eq!(b.rows(), a.rows(), "a peer folding the same receipts holds the same row");}/// RULE: Within one batch, a delete of a row holding a unique pair and a create of another row holding that pair leaves only the new row.#[test]fn a_unique_pair_moves_to_a_new_row_in_one_batch() {letmut a = device("a"); a.write(T0, &[upsert("v1", term("v1", "cotton", "manual"))]); a.write(T0 + 1_000, &[delete("v1"), upsert("v2", term("v2", "cotton", "auto"))]); assert_eq!(a.rows(), vec![("v2".to_string(), "cotton".to_string(), "auto".to_string())]);let b = replay(&a); assert_eq!(b.rows(), a.rows());}/// RULE: Within one batch, an upsert of a row the batch already created is a change, never a second create; and a create, delete and upsert of one row is create, retract, create.#[test]fn a_row_walked_through_one_batch_gets_one_create_per_life() {letmut a = device("a");let twice = [upsert("v1", term("v1", "cotton", "manual")), upsert("v1", json!({"id": "v1", "source": "auto"}).as_object().unwrap().clone())];let kinds: Vec<Kind> = changes_of(&a.db, &twice).iter().map(|c| c.kind).collect(); assert_eq!(kinds, vec![Kind::Create, Kind::Change]); a.write(T0, &twice); assert_eq!(a.row("v1"), Some(("cotton".to_string(), "auto".to_string())));let thrice = [delete("v1"), upsert("v1", term("v1", "one", "manual")), delete("v1"), upsert("v1", term("v1", "two", "manual")), upsert("v1", json!({"id": "v1", "source": "auto"}).as_object().unwrap().clone())];let kinds: Vec<Kind> = changes_of(&a.db, &thrice).iter().map(|c| c.kind).collect(); assert_eq!(kinds, vec![Kind::Retract, Kind::Create, Kind::Retract, Kind::Create, Kind::Change]); a.write(T0 + 1_000, &thrice); assert_eq!(a.row("v1"), Some(("two".to_string(), "auto".to_string())));let b = replay(&a); assert_eq!(b.rows(), a.rows());}/// RULE: A re-create after a delete in one batch still names every column the table requires — a partial create is refused, not minted as a change.#[test]fn a_re_create_in_one_batch_still_names_every_required_column() {letmut a = device("a"); a.write(T0, &[upsert("v1", term("v1", "cotton", "manual"))]);let batch = [delete("v1"), upsert("v1", json!({"id": "v1", "source": "auto"}).as_object().unwrap().clone())];let act = Act { actor: Actor::device_job(JobName::named("test").expect("a job name")), verb: "test".to_string(), history: History::None, changes: changes_of(&a.db, &batch), };let refused = mint(&a.db, &act, &Clock::wall(T0 + 1_000), &mut a.ids, Held::Served).expect_err("a partial create is refused"); assert!(refused.to_string().contains("which the table requires"), "{refused}"); assert_eq!(a.row("v1"), Some(("cotton".to_string(), "manual".to_string())), "the refused act changed nothing");}