//! The TAKE-BACK (architect's ruling, 5 Oct 2026): Undo of an add is an erase//! of its own reason, `taken_back`, built once in the store. It is minted only//! when the same person at the same device made the record and nothing has//! changed it since; `mint` judges it, every device folds it as it folds any//! erase, and two devices converge after it.//!//! Every row is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]).use cotton_store::actor::{Actor, DeviceId, JobName};use cotton_store::changes::changes_since;use cotton_store::erase::is_gone;use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::fold::{arrive, Arrival, FoldResult};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Delete, Held, History, IdSource};use cotton_store::protocol::types::CottonOp;use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::take_back::{refusal, Refusal, REASON};use cotton_store::Driver;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};constT0: i64 = 1_759_480_000_000;const NOTES: &str = "cotton_notes";const ATTACHMENTS: &str = "cotton_note_attachments";const LINKS: &str = "cotton_links";const NOTE: &str = "00000000-0000-4000-8000-0000007b0001";const OTHER_NOTE: &str = "00000000-0000-4000-8000-0000007b0002";const ATTACHMENT: &str = "00000000-0000-4000-8000-0000007b0003";const LINK: &str = "00000000-0000-4000-8000-0000007b0006";const PHOTO: &str = "00000000-0000-4000-8000-0000007b0007";structIds(u32, &'static str);implIdSourceforIds {fn next_op_id(&mutself, _now_ms: i64) -> cotton_store::Result<String> {self.0 += 1;Ok(format!("{}-{:05}", self.1, self.0)) }}structDev { db: Driver, ids: Ids, author: String, fact: CottonOp, tag: &'static str,}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);// Both devices' approval rows, in every file: `owner:dev-<tag>` is the// person at that device's screen.for other in ["a", "b"] { db.run("INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, approved_by_device, created_at, updated_at) \ VALUES (?, ?, ?, 'Synthetic', ?, 'owner', ?, ?)", &[SqlValue::Text(format!("dev-{other}")),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(format!("key-{other}")),SqlValue::Text(NOW.to_string()),SqlValue::Text(NOW.to_string()),SqlValue::Text(NOW.to_string()), ], ) .expect("a device row"); }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, author: author.id, fact: author.fact, tag }}/// Two devices that have heard each other's author.fn pair() -> (Dev, Dev) {let a = device("a");let b = device("b"); a.take(std::slice::from_ref(&b.fact)); b.take(std::slice::from_ref(&a.fact)); (a, b)}fn obj(value: Value) -> Map<String, Value> { value.as_object().expect("an object").clone()}fn note(id: &str, body: &str) -> Change {Change::create( NOTES, id, obj(json!({"id": id, "workspace_id": WORKSPACE, "title": "Synthetic", "body": body, "created_at": NOW, "updated_at": NOW})), )}fn attachment(note_id: &str) -> Change {Change::create( ATTACHMENTS, ATTACHMENT, obj(json!({"id": ATTACHMENT, "workspace_id": WORKSPACE, "note_id": note_id, "record_kind": "photo", "record_id": PHOTO,"position": 0, "created_at": NOW, "updated_at": NOW})), )}fn link(from: &str, to: &str) -> Change {Change::create( LINKS, LINK, obj(json!({"id": LINK, "workspace_id": WORKSPACE, "from_kind": "note", "from_id": from, "to_kind": "note","to_id": to, "created_at": NOW})), )}fn body(text: &str) -> Change {Change::update(NOTES, NOTE, obj(json!({"body": text, "updated_at": NOW})))}fn take_back(through: &str) -> Change {Change::delete(NOTES, NOTE, Delete::TakeBack { through: through.to_string() })}implDev {/// The person at this device's screen.fn person(&self) -> Actor {Actor::owner(DeviceId::in_file(&self.db, &format!("dev-{}", self.tag)).expect("the device row")) }fn job() -> Actor {Actor::device_job(JobName::named("test").expect("a job name")) }fn act_as(&mutself, actor: Actor, at_ms: i64, changes: Vec<Change>) -> cotton_store::Result<Vec<CottonOp>> {let act = Act { actor, verb: "test".to_string(), history: History::Kept, changes }; mint(&self.db, &act, &Clock::wall(at_ms), &mutself.ids, Held::Served).map(|minted| minted.ops) }/// An act of the person at this device.fn act(&mutself, at_ms: i64, changes: Vec<Change>) -> Vec<CottonOp> {let person = self.person();self.act_as(person, at_ms, changes).expect("mints") }fn try_act(&mutself, at_ms: i64, changes: Vec<Change>) -> cotton_store::Result<Vec<CottonOp>> {let person = self.person();self.act_as(person, at_ms, changes) }fn take(&self, ops: &[CottonOp]) -> FoldResult { arrive(&self.db, ops, Arrival::Pulled).expect("folds") }fn exchange(&self) -> Vec<CottonOp> { changes_since(&self.db, &self.author, "", 10_000).expect("a page").ops }fn present(&self, table: &str, id: &str) -> bool {self.db .get(&format!("SELECT 1 AS n FROM {table} WHERE id = ?"), &[SqlValue::Text(id.to_string())]) .expect("reads") .is_some() }fn gone_reason(&self, table: &str, id: &str) -> Option<String> {self.db .get("SELECT reason FROM _gone WHERE tbl = ? AND row_id = ?", &[SqlValue::Text(table.to_string()), SqlValue::Text(id.to_string())], ) .expect("reads") .and_then(|row| row.text("reason").map(str::to_string)) }fn parked_class(&self, op_id: &str) -> Option<String> {self.db .get("SELECT class FROM _parked WHERE op_id = ?", &[SqlValue::Text(op_id.to_string())]) .expect("reads") .and_then(|row| row.text("class").map(str::to_string)) }/// Everything two files must agree on after an exchange: every receipt,/// every tombstone, every erasure, and the rows themselves.fn state(&self) -> Vec<String> {letmut out = Vec::new();for (place, order) in [("_writes", "tbl, row_id, hlc"), ("_tombstones", "tbl, row_id"), ("_gone", "tbl, row_id")] {for row inself .db .all(&format!("SELECT tbl, row_id, hlc, op_id, CAST(bytes AS TEXT) AS bytes FROM {place} ORDER BY {order}"), &[]) .expect("reads") { out.push(format!("{place} {} {} {} {} {}", row.text("tbl").unwrap_or_default(), row.text("row_id").unwrap_or_default(), row.text("hlc").unwrap_or_default(), row.text("op_id").unwrap_or_default(), row.text("bytes").unwrap_or_default(), )); } }for table in [NOTES, ATTACHMENTS, LINKS] {for row inself.db.all(&format!("SELECT * FROM {table} ORDER BY id"), &[]).expect("reads") { out.push(format!("row {table} {:?}", row.columns())); } } out }}fn stamp(ops: &[CottonOp]) -> String { ops.last().expect("an op").hlc.clone()}/// RULE: Two devices converge after a take-back: the record, the children its add wrote and their receipts are gone on both, each keeps the same signed erase with reason taken_back.#[test]fn two_devices_converge_after_a_take_back() {let (mut a, mut b) = pair(); b.act(T0 - 5, vec![note(OTHER_NOTE, "a note of the peer's own")]);// The add's own act writes the record and a child of it.let made = a.act(T0, vec![note(NOTE, "added a moment ago"), attachment(NOTE)]); b.take(&made); a.take(&b.exchange());let erase = a.act(T0 + 1_000, vec![take_back(&stamp(&made))]); assert_eq!(erase.len(), 1, "one signed erase is the whole trace"); b.take(&erase);for dev in [&a, &b] {for (table, id) in [(NOTES, NOTE), (ATTACHMENTS, ATTACHMENT)] { assert!(!dev.present(table, id), "{table} {id} outlived the take-back on device {}", dev.tag); assert_eq!(dev.gone_reason(table, id).as_deref(), Some(REASON)); } assert!(dev.present(NOTES, OTHER_NOTE), "the take-back took a record it did not own"); } assert_eq!(a.state(), b.state(), "the two files differ after the take-back");}/// RULE: A peer's edit made before it heard of a take-back is never applied: it parks gone on the device that took the add back, and the id is never created again on either.#[test]fn a_peers_concurrent_edit_parks_gone_after_a_take_back() {let (mut a, mut b) = pair();let made = a.act(T0, vec![note(NOTE, "added a moment ago")]); b.take(&made);let edit = b.act(T0 + 5_000, vec![body("the peer's edit")]);let erase = a.act(T0 + 1_000, vec![take_back(&stamp(&made))]);let folded = a.take(&edit); assert!(folded.applied.is_empty(), "{folded:?}"); assert_eq!(a.parked_class(&edit[0].op_id).as_deref(), Some("gone")); b.take(&erase);for dev in [&mut a, &mut b] { assert!(!dev.present(NOTES, NOTE)); assert!(is_gone(&dev.db, NOTES, NOTE).expect("reads")); assert!(dev.try_act(T0 + 9_000, vec![note(NOTE, "recreated")]).is_err(), "a taken-back id was created again"); }}/// RULE: An add made on another device is never taken back here: the take-back is refused, so its Undo falls back to the table's put-away state.#[test]fn an_add_made_on_another_device_is_not_taken_back() {let (mut a, mut b) = pair();let made = a.act(T0, vec![note(NOTE, "added on device a")]); b.take(&made);let asker = b.person(); assert_eq!(refusal(&b.db, &asker, NOTES, NOTE, &stamp(&made)).expect("judges"), Some(Refusal::MadeElsewhere)); assert!(b.try_act(T0 + 1_000, vec![take_back(&stamp(&made))]).is_err(), "mint took back another device's add"); assert!(b.present(NOTES, NOTE));}/// RULE: Only the person who added a record takes the add back: an add made by a job, an assistant or an automation, and an Undo asked by one, is refused the take-back.#[test]fn an_add_or_an_undo_that_is_not_the_persons_own_is_not_taken_back() {let (mut a, _) = pair();// Made by the person, asked by a job.let made = a.act(T0, vec![note(NOTE, "added by the person")]); assert_eq!(refusal(&a.db, &Dev::job(), NOTES, NOTE, &stamp(&made)).expect("judges"), Some(Refusal::NotAPerson)); assert!(a.act_as(Dev::job(), T0 + 1_000, vec![take_back(&stamp(&made))]).is_err());// Made by a job, asked by the person.let by_job = a.act_as(Dev::job(), T0 + 2_000, vec![note(OTHER_NOTE, "added by a job")]).expect("mints");let person = a.person(); assert_eq!(refusal(&a.db, &person, NOTES, OTHER_NOTE, &stamp(&by_job)).expect("judges"), Some(Refusal::MadeElsewhere)); assert!(a.present(NOTES, NOTE) && a.present(NOTES, OTHER_NOTE));}/// RULE: An add that was edited, linked or given a child record since is never taken back: each is refused, naming what changed, and the record stays.#[test]fn an_add_changed_since_is_not_taken_back() {for (what, change) in [ ("an edit", body("edited since")), ("a link", link(OTHER_NOTE, NOTE)), ("a child record", attachment(NOTE)), ] {let (mut a, _) = pair(); a.act(T0 - 5, vec![note(OTHER_NOTE, "another note")]);let made = a.act(T0, vec![note(NOTE, "added a moment ago")]);let through = stamp(&made);let person = a.person(); assert_eq!(refusal(&a.db, &person, NOTES, NOTE, &through).expect("judges"), None, "a fresh add is taken back");let later = a.act(T0 + 1_000, vec![change]);let judged = refusal(&a.db, &person, NOTES, NOTE, &through).expect("judges"); assert_eq!( judged,Some(Refusal::ChangedSince { table: later[0].table.clone(), row_id: later[0].row_id.clone() }),"{what} since the add" ); assert!(a.try_act(T0 + 2_000, vec![take_back(&through)]).is_err(), "mint took back an add after {what}"); assert!(a.present(NOTES, NOTE), "the record left after {what}"); }}/// RULE: No erase borrows the take-back's reason: an erase that names taken_back without being a judged take-back is refused by mint.#[test]fn no_erase_borrows_the_take_backs_reason() {let (mut a, _) = pair(); a.act(T0, vec![note(NOTE, "added a moment ago")]); a.act(T0 + 1_000, vec![body("edited since")]);let refused = a.try_act(T0 + 2_000, vec![Change::erase(NOTES, NOTE, REASON)]); assert!(refused.is_err(), "an unjudged erase carried the take-back's reason"); assert!(a.present(NOTES, NOTE));}