//! Schema 145: a media-only message keeps its kind in its mark (7 Nov 2026), //! so one whose bytes were left behind holds an empty body. The message //! table's `(deleted_at IS NOT NULL) OR (trim(COALESCE(body, '')) <> '') OR //! (json_array_length(media) > 0)` CHECK refused that row, and until now such //! a row held a typed token in its body. The rise drops the CHECK by //! rebuilding `cotton_msg_messages` in place with every row and rowid; rows //! never move, so an old token or an old English label stays as it was. use std::collections::{BTreeMap, BTreeSet}; use cotton_store::{ create::{apply_schema, fresh_schema, SchemaObject}, fold::fold_pulled, mint::{served, Actor, JobName, ServedRow}, schema::move_intents::{rebuilt_above, INTENTS}, shape_move::{crossing, move_to_current}, Driver, }; use serde_json::{json, Value}; const TABLE: &str = "cotton_msg_messages"; /// A file of this build whose message table is 144's, stamped 144. fn at_144() -> (Driver, Vec) { let had: Vec = serde_json::from_str(include_str!("fixtures/schema-v144.json")).unwrap(); let db = Driver::open_in_memory().unwrap(); apply_schema(&db).unwrap(); db.exec("PRAGMA foreign_keys=OFF").unwrap(); let old = had.iter().find(|o| o.kind == "table" && o.name == TABLE).unwrap(); db.exec(&format!("DROP TABLE {TABLE}")).unwrap(); db.exec(&old.sql).unwrap(); for object in had.iter().filter(|o| o.tbl_name == TABLE && o.kind != "table") { let _ = db.exec(&object.sql); } // A later rise's search index over messages (149's `fts_chat`) is not // 144's: its triggers went with the table above, so it goes too, and the // move makes it as it makes it for any 144 file. for object in fresh_schema().unwrap().iter().filter(|o| o.is_fts5_virtual() && !had.iter().any(|h| h.name == o.name)) { db.exec(&format!("DROP TABLE {}", object.name)).unwrap(); } db.exec("PRAGMA foreign_keys=ON").unwrap(); db.exec("PRAGMA user_version=144").unwrap(); (db, had) } /// Media-only rows as importers wrote them before 145: a token body, an old /// English label, one whose media landed, a deleted one (144's CHECK admits an /// empty body only once deleted_at is set, so it is inserted deleted), and words. const SEED: &str = "INSERT INTO cotton_workspaces(id,name,owner_user_id,created_at) VALUES ('synthetic','Synthetic','person','now'); INSERT INTO cotton_msg_threads(id,workspace_id,kind,title,created_at,updated_at) VALUES ('t','synthetic','dm','A synthetic chat','now','now'); INSERT INTO cotton_msg_messages(rowid,id,thread_id,workspace_id,direction,channel,origin,body,media,external_id,sent_at,created_at,meta,deleted_at) VALUES (11,'m-token','t','synthetic','in','whatsapp','imported','conversation.preview.photo','[]','x-1','2026-11-01T09:00:00.000Z','now','{\"mediaOnly\":\"image\"}',NULL), (12,'m-label','t','synthetic','in','whatsapp','imported','Voice message','[]','x-2','2026-11-01T09:01:00.000Z','now','{\"mediaOnly\":\"voice\"}',NULL), (13,'m-landed','t','synthetic','out','whatsapp','imported','','[{\"key\":\"synthetic/a.jpg\"}]','x-3','2026-11-01T09:02:00.000Z','now','{\"mediaOnly\":\"image\"}',NULL), (14,'m-deleted','t','synthetic','in','whatsapp','imported',NULL,'[]','x-4','2026-11-01T09:03:00.000Z','now','{}','now'), (15,'m-words','t','synthetic','in','whatsapp','imported','A synthetic hello','[]','x-5','2026-11-01T09:04:00.000Z','now','{}',NULL); INSERT INTO cotton_msg_reactions(id,workspace_id,thread_id,message_id,actor,emoji,created_at) VALUES ('r','synthetic','t','m-token','person','👍','now');"; fn rows(db: &Driver, table: &str) -> Vec { db.all(&format!("SELECT rowid, * FROM {table} ORDER BY rowid"), &[]).unwrap() } fn actor() -> Actor { Actor::job(JobName::named("object-sync").expect("a job name")) } /// A media-only message the object serves with its bytes left behind: no /// body, no media, the mark. The fold takes a served row after its codecs /// (the client decodes each column on the way in), so the JSON columns are /// handed over as the strings they are stored as. fn left_behind(external_id: &str) -> BTreeMap { BTreeMap::from([ ("thread_id".to_string(), json!("t")), ("workspace_id".to_string(), json!("synthetic")), ("direction".to_string(), json!("in")), ("channel".to_string(), json!("whatsapp")), ("origin".to_string(), json!("imported")), ("body".to_string(), json!("")), ("media".to_string(), json!("[]")), ("external_id".to_string(), json!(external_id)), ("meta".to_string(), json!("{\"mediaOnly\":\"image\"}")), ("sent_at".to_string(), json!("2026-11-02T09:00:00.000Z")), ("created_at".to_string(), json!("2026-11-02T09:00:00.000Z")), ]) } /// RULE: The 145 rise rebuilds cotton_msg_messages in place — every old row, rowid and byte kept, the token and old-label bodies too, its reactions and search index whole — and afterwards a media-only message with an empty body lands, while every other CHECK on the table still holds. #[test] fn the_body_check_goes_and_every_row_stays() { let (db, had) = at_144(); db.exec(SEED).unwrap(); assert!( db.exec("INSERT INTO cotton_msg_messages(id,thread_id,workspace_id,direction,channel,origin,body,media,sent_at,created_at,meta) VALUES ('m-early','t','synthetic','in','whatsapp','imported','','[]','now','now','{\"mediaOnly\":\"image\"}')").is_err(), "144 refuses the empty body" ); let before = rows(&db, TABLE); let reactions = rows(&db, "cotton_msg_reactions"); let plan = crossing(&had, &fresh_schema().unwrap()).unwrap(); let rebuilt: BTreeSet<&str> = plan.rebuild.iter().map(String::as_str).collect(); assert_eq!( rebuilt.difference(&rebuilt_above(145)).copied().collect::>(), [TABLE].into_iter().collect(), "the message table, and beside it only a later rise's rebuilds" ); assert_eq!(rebuilt_above(144), rebuilt, "REBUILDS says so"); move_to_current(&db).unwrap(); assert_eq!(rows(&db, TABLE), before, "every row and rowid stays, byte for byte"); assert_eq!(rows(&db, "cotton_msg_reactions"), reactions); let sql = db.get("SELECT sql FROM sqlite_master WHERE name = ?", &[TABLE.to_string().into()]).unwrap().unwrap().text("sql").unwrap().to_string(); let old = &had.iter().find(|o| o.kind == "table" && o.name == TABLE).unwrap().sql; assert_eq!( sql, old.replace("\n CHECK ((deleted_at IS NOT NULL) OR (trim(COALESCE(body, '')) <> '') OR (json_array_length(media) > 0)),", ""), "the table is 144's minus that one CHECK" ); assert_eq!(db.get("SELECT count(*) AS n FROM fts_messages WHERE fts_messages MATCH 'hello'", &[]).unwrap().unwrap().int("n"), Some(1)); db.exec("INSERT INTO cotton_msg_messages(id,thread_id,workspace_id,direction,channel,origin,body,media,sent_at,created_at,meta) VALUES ('m-new','t','synthetic','in','whatsapp','imported','','[]','now','now','{\"mediaOnly\":\"image\"}')").unwrap(); assert!( db.exec("INSERT INTO cotton_msg_messages(id,thread_id,workspace_id,direction,channel,origin,body,media,sent_at,created_at) VALUES ('m-bad','t','synthetic','in','whatsapp','imported','','{}','now','now')").is_err(), "the media array's own CHECK stays" ); assert!(db.all("PRAGMA foreign_key_check", &[]).unwrap().is_empty()); } /// RULE: A served media-only message with an empty body that 144's CHECK refused is due again after the move, and folds into the rebuilt table with its body empty and its mark. #[test] fn a_refused_media_only_row_folds_after_the_move() { let (db, _) = at_144(); db.exec(SEED).unwrap(); let op = served("op-left-behind".into(), TABLE, "m-served", "1794456264079:0185:object", &actor(), ServedRow::Live(left_behind("x-9")), None).unwrap(); let refused = fold_pulled(&db, std::slice::from_ref(&op)).unwrap(); assert!(!refused.rejected.is_empty() || db.get("SELECT 1 AS n FROM _parked", &[]).unwrap().is_some(), "144 refuses it"); assert!(db.get("SELECT id FROM cotton_msg_messages WHERE id = 'm-served'", &[]).unwrap().is_none()); move_to_current(&db).unwrap(); let folded = fold_pulled(&db, std::slice::from_ref(&op)).unwrap(); assert!(folded.rejected.is_empty(), "{:?}", folded.rejected); let row = db.get("SELECT body, media, meta FROM cotton_msg_messages WHERE id = 'm-served'", &[]).unwrap().expect("it landed"); assert_eq!(row.text("body"), Some("")); assert_eq!(row.text("media"), Some("[]")); assert_eq!(serde_json::from_str::(row.text("meta").unwrap()).unwrap()["mediaOnly"], "image"); } /// RULE: 145 is one rise and not additive: it rebuilds the message table, and it discards no stored value. #[test] fn the_145_rise_rebuilds_and_discards_nothing() { let rises: Vec<_> = INTENTS.iter().filter(|intent| intent.version == 145).collect(); assert_eq!(rises.len(), 1); assert!(!rises[0].additive && rises[0].losses.is_empty()); }