//! **A SYNCED TABLE MUST NOT GROW A NEW CHECK SPANNING TWO COLUMNS.** //! //! A local write is a whole row, and a constraint over two of its columns reads //! as a sentence about the thing: *nothing is queued once an agent has answered //! with its own id*. It is true of every write anybody makes, and it will still //! refuse one — because a synced row does not arrive as a write. //! //! It arrives as a FRAGMENT. [`cotton_store::changes`] answers a row as ONE OP //! PER DISTINCT COLUMN STAMP, carrying only the columns at that stamp, and //! [`cotton_store::fold`] merges an op column by column, dropping the ones a //! newer write has already covered. Both halves are right and neither can be //! given up; together they mean the UPDATE that reaches the table is a SUBSET //! of some past write, chosen by clocks. A subset of a consistent row is not a //! consistent row, and SQLite re-checks every constraint on the whole row. //! //! On 2026-09-22 that cost the owner a coding session: the Mac's //! `queued → running` write reached the server with `state` already covered by //! a later write, leaving `external_id, machine, cwd, started_at, host_owned` //! alone against a row that still read `queued`. The whole op was refused by //! `CHECK (state <> 'queued' OR external_id IS NULL)`, parked in //! `_parked` for ever, and the agent's own session id never reached the //! server — so the next hook call found no row and created a twin. //! Cotton note "Repo landmines — why the build's rules exist" states the rule. //! //! **A CENSUS, NOT A BAN.** Eighty-one of these were already on the file when //! the defect was found, across forty tables, and a CHECK can only be removed //! by REBUILDING its table. So [`ON_THE_FILE`] records every one of them //! verbatim and this guard holds the set EQUAL: a new one fails, and one whose //! table has since been rebuilt fails until its line is deleted. The list only //! shrinks. //! //! **None of them is safe** — they are untriggered, which is a different thing. //! A CHECK over two columns survives only while no two writes ever cover one of //! them and leave the other arriving alone: written once and never amended, or //! always written together by one route. Version 25 cleared the one that had //! already fired, and the invariant moved to where the write happens //! (`cotton_client::session_host::executor`, the phone's `session.create`), //! which is the one place that sees the whole row. Version 26 took two more off //! `cotton_feedback` — the one that made `shipped` a verdict the open queue //! ignored, and the `resolved_at`/`resolved_by_kind` pairing beside it — and //! moved both to `apply_update`, the one writer that sees the whole verdict. use std::collections::BTreeSet; use cotton_store::create::schema_objects; use cotton_store::migrate::migrate_store; use cotton_store::schema::table_specs::handed_over_specs; use cotton_store::Driver; /// Every cross-column CHECK a synced table carried when this guard was written, /// as `(table, the text inside the brackets)`. /// /// Verbatim, so a rung that rewrites one is a diff a reviewer reads rather than /// a count that stayed the same. Delete the line when the rung that rebuilds /// its table takes the constraint off; never add one. const ON_THE_FILE: &[(&str, &str)] = &[ ("cotton_comments", "(author_kind = 'agent') = (author_label IS NOT NULL)"), ("cotton_comments", "(resolved_at IS NULL) = (resolved_by_kind IS NULL)"), ("cotton_comments", "(author_kind = 'user') = (author_user_id IS NOT NULL)"), ("cotton_documents", "(status = 'failed') = (failed_stage IS NOT NULL)"), ("cotton_documents", "(period_start IS NULL) OR (period_end IS NULL) OR (period_end >= period_start)"), ("cotton_feedback", "(image_sha256 IS NULL) OR (app IS NOT NULL)"), ("cotton_feedback", "(image_sha256 IS NULL) = (image_ext IS NULL)"), ("cotton_feedback", "(x IS NULL) = (y IS NULL)"), ("cotton_feedback", "(x IS NULL) OR (app IS NULL) OR (image_sha256 IS NOT NULL)"), ("cotton_feedback", "(author_kind = 'user') = (author_user_id IS NOT NULL)"), ("cotton_feedback", "(author_kind = 'user') OR (author_label IS NOT NULL)"), ("cotton_feedback", "same_as IS NULL OR same_as <> id"), ("cotton_feedback", "(same_as IS NULL) OR (parent_id IS NULL)"), ("cotton_goals", "(status = 'achieved') = (achieved_at IS NOT NULL)"), ("cotton_inbox_items", "(raw_text IS NOT NULL) OR (audio_url IS NOT NULL)"), ("cotton_meeting_utterances", "t1_ms >= t0_ms"), ("cotton_meetings", "(status = 'failed') = (failed_stage IS NOT NULL)"), ("cotton_media_duplicates", "keep_id <> copy_id"), ("cotton_media_duplicates", "substr(keep_id, 1, length(record_kind) + 1) = record_kind || ':'"), ("cotton_media_duplicates", "substr(copy_id, 1, length(record_kind) + 1) = record_kind || ':'"), ("cotton_media_duplicates", "(state = 'open') = (decided_at IS NULL)"), ("cotton_media_albums", "(state = 'open') = (decided_at IS NULL)"), ("cotton_media_albums", "starts_at <= ends_at"), ("cotton_media_album_items", "substr(record_id, 1, length(record_kind) + 1) = record_kind || ':'"), ("cotton_media_faces", "substr(record_id, 1, length(record_kind) + 1) = record_kind || ':'"), ("cotton_media_faces", "x >= 0 AND x <= 1 AND y >= 0 AND y <= 1"), ("cotton_media_faces", "w > 0 AND w <= 1 AND h > 0 AND h <= 1"), ("cotton_media_sightings", "substr(record_id, 1, length(record_kind) + 1) = record_kind || ':'"), ("cotton_media_sightings", "(source = 'message') = (thread_id IS NOT NULL)"), ("cotton_media_sightings", "source NOT IN ('message', 'apple_library', 'email') OR source_id IS NOT NULL"), ("cotton_memories", "superseded_by IS NULL OR status = 'archived'"), ("cotton_memories", "(status = 'archived') = (archived_at IS NOT NULL)"), ("cotton_memories", "(origin_kind = 'agent') = (origin_label IS NOT NULL)"), ("cotton_money_evidence", "(kind = 'external') OR (ref_id IS NOT NULL)"), ("cotton_money_statements", "(period_start IS NULL) OR (period_end IS NULL) OR (period_end >= period_start)"), ("cotton_money_transactions", "(settles_transaction_id IS NULL) OR (settles_transaction_id <> id)"), ("cotton_msg_contact_handles", "kind <> 'phone' OR (length(value) BETWEEN 8 AND 15 AND NOT value GLOB '*[^0-9]*')"), ("cotton_msg_contact_handles", "kind <> 'email' OR (value = lower(value) AND value LIKE '%_@_%' AND value NOT GLOB '* *')"), ("cotton_msg_contact_handles", "kind <> 'cotton' OR (length(value) BETWEEN 2 AND 31 AND value GLOB '[a-z0-9]*' AND NOT value GLOB '*[^a-z0-9-]*' AND value GLOB '*[^0-9]*')"), ("cotton_msg_thread_participants", "(is_self = 1) OR (contact_id IS NOT NULL) OR (NULLIF(trim(COALESCE(display_name, '')), '') IS NOT NULL)"), ("cotton_msg_threads", "((kind = 'dm') AND ((contact_id IS NOT NULL) OR (NULLIF(trim(COALESCE(title, '')), '') IS NOT NULL))) OR ((kind = 'group') AND (contact_id IS NULL) AND (NULLIF(trim(COALESCE(title, '')), '') IS NOT NULL))"), ("cotton_news_editions", "(status = 'failed') = (failed_stage IS NOT NULL)"), ("cotton_news_topics", "(source_url IS NULL) OR (kind = 'source')"), ("cotton_notes", "(author_kind = 'agent') = (author_label IS NOT NULL)"), ("cotton_people", "((birth_month IS NOT NULL) + (birth_day IS NOT NULL)) IN (0, 2)"), ("cotton_person_suggestions", "person_id <> candidate_id"), ("cotton_person_suggestions", "(state = 'open') = (decided_at IS NULL)"), ("cotton_photos", "id = 'photo:' || sha256"), ("cotton_photos", "(summary IS NULL) = (summary_at IS NULL)"), ("cotton_photos", "(review_note IS NULL) = (review_at IS NULL)"), ("cotton_photos", "(latitude IS NULL) = (longitude IS NULL)"), ("cotton_project_links", "record_kind <> 'memory' OR \"position\" IS NOT NULL"), ("cotton_assistant_runs", "(state = 'failed') = (error IS NOT NULL)"), ("cotton_assistant_runs", "(state IN ('done','failed')) = (finished_at IS NOT NULL)"), ("cotton_session_messages", "to_kind <> 'session' OR to_session_id IS NOT NULL"), ("cotton_session_messages", "to_kind <> 'project' OR project_id IS NOT NULL"), ("cotton_session_messages", "from_kind <> 'session' OR from_session_id IS NOT NULL"), ("cotton_session_messages", "kind NOT IN ('decision', 'stop') OR to_kind = 'session'"), ("cotton_session_messages", "kind <> 'decision' OR request_ref IS NOT NULL"), ("cotton_videos", "id = 'video:' || sha256"), ("cotton_videos", "(summary IS NULL) = (summary_at IS NULL)"), ("cotton_videos", "(review_note IS NULL) = (review_at IS NULL)"), ("cotton_videos", "(latitude IS NULL) = (longitude IS NULL)"), ("cotton_repo_runs", "status <> 'completed' OR conclusion IS NOT NULL"), ("cotton_repo_runs", "status = 'completed' OR conclusion IS NULL"), ("cotton_repo_jobs", "status <> 'completed' OR conclusion IS NOT NULL"), ("cotton_repo_jobs", "status = 'completed' OR conclusion IS NULL"), ("cotton_repo_jobs", "log_ack <= log_lines"), ("cotton_repo_bundles", "(kind = 'full') = (basis_sha IS NULL)"), ("cotton_secret_placements", "(format = 'env') = (env_name IS NOT NULL)"), ( "cotton_workspaces", "((city_name IS NOT NULL) + (city_lat IS NOT NULL) + (city_lon IS NOT NULL)) IN (0, 3)", ), ]; /// Every table the exchange may hand over, with the SQL the ladder built it /// from. fn synced_tables() -> Vec<(&'static str, String, Vec<&'static str>)> { let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); let objects = schema_objects(&db).expect("reads the schema"); handed_over_specs() .map(|spec| { let sql = objects .iter() .find(|object| object.name == spec.name) .map(|object| object.sql.clone()) .unwrap_or_else(|| panic!("{} is a spec with no table", spec.name)); let columns: Vec<&'static str> = spec.columns.iter().map(|(name, _)| *name).collect(); (spec.name, sql, columns) }) .collect() } /// Every `CHECK (...)` in a `CREATE TABLE`, as the text inside the brackets. /// /// Balanced rather than "up to the next `)`": `CHECK ((format = 'env') = /// (env_name IS NOT NULL))` has three of them, and a naive cut would read one /// column and call the constraint single-column. fn check_expressions(sql: &str) -> Vec { let bytes: Vec = sql.chars().collect(); let lowered: String = sql.to_ascii_lowercase(); let mut out = Vec::new(); let mut from = 0usize; while let Some(found) = lowered[from..].find("check") { let after_word = from + found + "check".len(); from = after_word; // The opening bracket, past whatever whitespace. let mut at = after_word; while at < bytes.len() && bytes[at].is_whitespace() { at += 1; } if at >= bytes.len() || bytes[at] != '(' { continue; } let start = at + 1; let mut depth = 1usize; let mut end = start; while end < bytes.len() && depth > 0 { match bytes[end] { '(' => depth += 1, ')' => depth -= 1, _ => {} } if depth > 0 { end += 1; } } out.push(bytes[start..end].iter().collect()); from = end; } out } /// The table's own columns this expression names. /// /// String literals come out first: `CHECK (tool IN ('claude-code', 'codex'))` /// names one column, and a value that happens to spell another one is not a /// reference to it. fn columns_named(expression: &str, columns: &[&'static str]) -> BTreeSet<&'static str> { let mut outside = String::new(); let mut in_string = false; for ch in expression.chars() { match ch { '\'' => in_string = !in_string, _ if in_string => {} _ => outside.push(ch), } } let words: BTreeSet = outside .split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) .filter(|word| !word.is_empty()) .map(str::to_ascii_lowercase) .collect(); columns .iter() .copied() .filter(|column| words.contains(&column.to_ascii_lowercase())) .collect() } /// Every cross-column CHECK this file currently declares. fn on_the_file_now() -> BTreeSet<(String, String)> { let mut found = BTreeSet::new(); for (table, sql, columns) in synced_tables() { for expression in check_expressions(&sql) { if columns_named(&expression, &columns).len() >= 2 { found.insert((table.to_string(), expression)); } } } found } /// RULE: No synced table adds a rule spanning two columns, because a synced row arrives one column at a time. #[test] fn no_synced_table_has_grown_a_new_check_spanning_two_columns() { let declared: BTreeSet<(String, String)> = ON_THE_FILE .iter() .map(|(table, expression)| (table.to_string(), expression.to_string())) .collect(); let found = on_the_file_now(); let grown: Vec = found .difference(&declared) .map(|(table, expression)| format!("{table}: CHECK ({expression})")) .collect(); assert!( grown.is_empty(), "a synced row arrives as a FRAGMENT — one op per column stamp, merged column by column — \ so a CHECK over two columns refuses a write nobody made wrong, and that write is LOST \ (see this file's header and the Cotton note on Repo landmines). Put the invariant where \ the write happens instead:\n {}", grown.join("\n ") ); let gone: Vec = declared .difference(&found) .map(|(table, expression)| format!("{table}: CHECK ({expression})")) .collect(); assert!( gone.is_empty(), "the census names a constraint this file no longer has — delete the line from \ ON_THE_FILE, so the list keeps meaning what is actually on the file:\n {}", gone.join("\n ") ); } #[test] fn the_sessions_table_holds_no_constraint_between_its_state_and_its_id() { let (_, sql, columns) = synced_tables() .into_iter() .find(|(name, _, _)| *name == "cotton_sessions") .expect("the sessions table"); for expression in check_expressions(&sql) { let named = columns_named(&expression, &columns); assert!( !(named.contains("state") && named.contains("external_id")), "version 25 took this off the table on purpose — the executor writes an external_id \ only beside a state move, and the phone's session.create writes none at all: \ CHECK ({expression})" ); } }