diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6000fd606f7..7c58a5d87cb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -498,8 +498,8 @@ Relay-owned write APIs provide the supported mutation path for tenant data: checks active, undeleted state. Deletion lifecycle transitions take the matching exclusive lock. A serving transaction never spans communities. The universal per-table write-fence triggers and their functions have been - retired after writer coverage and fleet gates; the community tombstone guard - remains. New tenant-owned tables rely on this admission alone. + retired after writer coverage and fleet gates. New tenant-owned tables rely + on this admission alone. - **Replica floor:** supported channel-event insertions check `created_at` against `clock_timestamp()` on their admitted transaction using the shared 960-second floor. The ordered heartbeat handshake and activity scan retain @@ -511,6 +511,11 @@ Relay-owned write APIs provide the supported mutation path for tenant data: Drain old connections/in-flight transactions, stop out-of-band writers, and hold the replica breaker closed through the drop until replay catches up. Already-running old pods do not reverify the trigger on each heartbeat. +- **Single-table guards:** channel tenant binding, community lifecycle, + request/approval evidence and manifest chunks are owned by application writers. + Serving/deletion catalog validation tolerates the five legacy guards being + absent. Their contract migration is gated on the writer and catalog-expand + release (#8320) being deployed fleet-wide. - **Role separation:** relay/runtime code owns admission and lock protocols; operator maintenance/backfill workflows must either use those protocols or run under explicit reviewed procedures that keep routing fences closed. diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 4e595753b2b..bf2e65361ec 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -844,17 +844,6 @@ mod postgres_tests { .collect() } - fn has_channels_community_id_immutability_guard(sql: &str) -> bool { - let normalized = normalize_sql(sql); - normalized.contains("create trigger") - && normalized.contains("before update") - && normalized.contains(" on channels") - && normalized.contains("community_id") - && normalized.contains("old.community_id") - && normalized.contains("new.community_id") - && normalized.contains("raise exception") - } - fn forbidden_channels_community_id_mutations(sql: &str) -> Vec { split_sql_statements(sql) .into_iter() @@ -890,7 +879,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 95); + assert_eq!(migrations.len(), 96); assert_eq!(migrations[89].version, 90); assert!(migrations[89] .sql @@ -929,6 +918,12 @@ mod postgres_tests { for (index, migration) in migrations.iter().enumerate() { assert_eq!(migration.version, (index + 1) as i64); } + // 0096 retires the five single-table guard triggers and functions. + assert_eq!(migrations[95].version, 96); + assert!(migrations[95] + .sql + .as_str() + .contains("SET LOCAL lock_timeout = '5s'")); assert!(migrations[79] .sql .as_str() @@ -2213,10 +2208,6 @@ mod postgres_tests { "channels.community_id must not be re-tenanted after insert; forbidden migration statements:\n{}", forbidden_mutations.join("\n---\n") ); - assert!( - has_channels_community_id_immutability_guard(sql), - "migrations define channels.community_id but no BEFORE UPDATE trigger/function guard that rejects OLD.community_id <> NEW.community_id was found" - ); } #[test] @@ -2485,16 +2476,9 @@ mod postgres_tests { .expect("embedded migration 0029") .sql .as_ref(); - let migration_0051: &str = MIGRATOR - .iter() - .find(|migration| migration.version == 51) - .expect("embedded migration 0051") - .sql - .as_ref(); let schema_sql = crate::test_support::desired_state_schema_sql(); let migration = surface(migration_0029); - let owner_admission_migration = surface(migration_0051); let schema = surface(&schema_sql); assert_eq!( @@ -2562,6 +2546,11 @@ mod postgres_tests { "enforce_community_write_fence", "attach_community_write_fence", "community_deletion_lock_key", + // 0096 retires the four deletion guard functions. + "enforce_community_tombstone", + "prevent_community_deletion_request_retargeting", + "prevent_community_deletion_approval_removal", + "protect_community_deletion_manifest_keys", ] .contains(&function.as_str()) { @@ -2579,17 +2568,6 @@ mod postgres_tests { ); } } - assert_eq!( - schema - .functions - .get("prevent_community_deletion_request_retargeting") - .expect("schema.sql deletion retargeting guard"), - owner_admission_migration - .functions - .get("prevent_community_deletion_request_retargeting") - .expect("0051 deletion retargeting guard"), - "schema.sql must carry the latest immutable owner-provenance guard" - ); let request_table = schema .tables .get("community_deletion_requests") @@ -2607,6 +2585,16 @@ mod postgres_tests { ); } for (trigger, definition) in &migration.triggers { + if matches!( + trigger.as_str(), + "communities_deletion_tombstone" + | "community_deletion_request_retargeting_guard" + | "community_deletion_approval_removal_guard" + | "community_deletion_manifest_keys_guard" + ) { + assert!(!schema.triggers.contains_key(trigger)); + continue; + } let in_schema = schema .triggers .get(trigger) @@ -3214,6 +3202,57 @@ mod postgres_tests { schema/ does not declare (or the reverse)" ); } + // Compare columns, keys and remaining triggers on the five guarded tables; + // foreign keys must survive 0096 unchanged. + for table in [ + "channels", + "communities", + "community_deletion_requests", + "community_deletion_approvals", + "community_deletion_manifest_keys", + ] { + assert_eq!( + columns(&desired, table).await, + columns(&migrated, table).await, + "single-table guard column parity: {table}" + ); + // pgschema rewrites CHECK expressions (e.g. BETWEEN) into an + // equivalent tree with different grouping. Compare key/FK shapes + // here; existing CHECK assertions above remain unchanged. + let desired_keys: Vec<_> = constraints(&desired, table) + .await + .into_iter() + .filter(|(_, definition, _)| !definition.starts_with("CHECK")) + .collect(); + let migrated_keys: Vec<_> = constraints(&migrated, table) + .await + .into_iter() + .filter(|(_, definition, _)| !definition.starts_with("CHECK")) + .collect(); + assert_eq!( + desired_keys, migrated_keys, + "single-table guard key parity: {table}" + ); + let query = "SELECT pg_get_triggerdef(oid) FROM pg_trigger \ + WHERE tgrelid = $1::regclass AND NOT tgisinternal ORDER BY tgname"; + let desired_triggers: Vec = sqlx::query_scalar(query) + .bind(table) + .fetch_all(&desired) + .await + .expect("desired table triggers"); + let migrated_triggers: Vec = sqlx::query_scalar(query) + .bind(table) + .fetch_all(&migrated) + .await + .expect("migrated table triggers"); + assert_eq!( + desired_triggers, migrated_triggers, + "remaining trigger parity: {table}" + ); + } + // Shared with the isolated desired-template and migration regressions. + crate::deletion::postgres_tests::assert_single_table_guards_retired(&desired).await; + crate::deletion::postgres_tests::assert_single_table_guards_retired(&migrated).await; } /// Re-applying `schema/schema.sql` to a database bootstrapped the way every @@ -3974,8 +4013,9 @@ mod postgres_tests { ) .fetch_one(&pool) .await - .expect("read retained guard"); - assert!(tombstone); + .expect("read retired guard"); + // 0096 retired the tombstone trigger. + assert!(!tombstone); store .validate_serving_catalog() .await diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 4fedb1e77db..490d53cf6ad 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -4582,7 +4582,7 @@ pub(crate) mod owner_provenance_contract { } #[cfg(test)] -mod postgres_tests { +pub(crate) mod postgres_tests { use super::*; use crate::test_support::ScratchDb; use crate::{ @@ -4803,8 +4803,9 @@ mod postgres_tests { ) .fetch_one(&db.pool) .await - .expect("lookup retired functions and retained guard"); - assert_eq!(retired, (false, false, true)); + .expect("lookup retired functions and guard"); + // 0094 retired the functions; 0096 retired the tombstone trigger. + assert_eq!(retired, (false, false, false)); } #[tokio::test] @@ -5047,6 +5048,67 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); } } + /// Assert the contract catalog, including disabled copies and overloads. + pub(crate) async fn assert_single_table_guards_retired(pool: &sqlx::PgPool) { + let retired_triggers = [ + "trg_channels_community_id_immutable", + "communities_deletion_tombstone", + "community_deletion_request_retargeting_guard", + "community_deletion_approval_removal_guard", + "community_deletion_manifest_keys_guard", + ]; + let retired_functions = [ + "channels_community_id_immutable", + "enforce_community_tombstone", + "prevent_community_deletion_request_retargeting", + "prevent_community_deletion_approval_removal", + "protect_community_deletion_manifest_keys", + ]; + let remaining: Vec = sqlx::query_scalar( + "SELECT 'trigger:' || c.relname || '.' || t.tgname FROM pg_trigger t \ + JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace \ + WHERE n.nspname='public' AND t.tgname=ANY($1) \ + UNION ALL SELECT 'function:' || p.proname FROM pg_proc p \ + JOIN pg_namespace n ON n.oid=p.pronamespace \ + WHERE n.nspname='public' AND p.proname=ANY($2) ORDER BY 1", + ) + .bind(&retired_triggers[..]) + .bind(&retired_functions[..]) + .fetch_all(pool) + .await + .expect("inspect retired guard objects"); + assert!( + remaining.is_empty(), + "single-table guard objects remain: {remaining:?}" + ); + let db = Db::from_pool(pool.clone()); + db.validate_deletion_serving_catalog() + .await + .expect("serving startup after retirement"); + db.validate_deletion_serving_catalog_for_readiness( + tokio::time::Instant::now() + Duration::from_secs(5), + ) + .await + .expect("readiness after retirement"); + db.validate_deletion_catalog() + .await + .expect("deletion catalog after retirement"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn desired_schema_single_table_guards_are_retired() { + let (db, _) = store().await; + assert_single_table_guards_retired(&db.pool).await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_schema_single_table_guards_are_retired() { + let (db, _) = store().await; + assert_single_table_guards_retired(&db.pool).await; + } + fn empty_prefix_manifest(prefix: String) -> PrefixManifest { PrefixManifest { prefix, @@ -5115,7 +5177,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[tokio::test] #[ignore = "requires Postgres"] - async fn single_table_guard_channels_remain_tenant_bound_without_trigger() { + async fn single_table_guard_channels_remain_tenant_bound() { let (db, _) = store().await; let first = db .ensure_configured_community(&format!("channel-a-{}.example", Uuid::new_v4())) @@ -5137,10 +5199,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); ) .await .expect("create first-community channel"); - sqlx::query("ALTER TABLE channels DISABLE TRIGGER trg_channels_community_id_immutable") - .execute(&db.pool) - .await - .expect("disable only channel immutability trigger"); assert!(matches!( db.update_channel( second.id, @@ -5175,7 +5233,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[tokio::test] #[ignore = "requires Postgres"] - async fn single_table_guard_community_lifecycle_rejects_deleted_row_without_trigger() { + async fn single_table_guard_community_lifecycle_rejects_deleted_row() { let (db, store) = store().await; let (request, inventory) = inventoried_request(&db, &store).await; store @@ -5191,10 +5249,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .expect("claim") .expect("won claim"); store.begin_quiescing(&claim.lease).await.expect("quiesce"); - sqlx::query("ALTER TABLE communities DISABLE TRIGGER communities_deletion_tombstone") - .execute(&db.pool) - .await - .expect("disable only tombstone trigger"); assert!(matches!( db.set_community_icon(request.community_id, Some("quiescing-icon")) .await, @@ -5248,12 +5302,8 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[tokio::test] #[ignore = "requires Postgres"] - async fn single_table_guard_abort_invalidates_generation_without_trigger() { + async fn single_table_guard_abort_invalidates_generation() { let (db, store) = store().await; - sqlx::query("ALTER TABLE communities DISABLE TRIGGER communities_deletion_tombstone") - .execute(&db.pool) - .await - .expect("disable only tombstone trigger"); for pre_archived in [false, true] { for fenced in [false, true] { let (request, _) = inventoried_request(&db, &store).await; @@ -5323,7 +5373,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[tokio::test] #[ignore = "requires Postgres"] - async fn single_table_guard_request_inventory_freeze_is_one_way_without_trigger() { + async fn single_table_guard_request_inventory_freeze_is_one_way() { let (db, store) = store().await; let host = format!("request-{}.example", Uuid::new_v4()); let community = db @@ -5341,12 +5391,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .expect("schema inventory"), storage: empty_storage_manifest(community.id), }; - sqlx::query( - "ALTER TABLE community_deletion_requests DISABLE TRIGGER community_deletion_request_retargeting_guard", - ) - .execute(&db.pool) - .await - .expect("disable only request guard"); sqlx::query( "UPDATE community_deletion_requests SET inventory_frozen_at = now(), \ inventory_digest = decode(repeat('00', 32), 'hex') WHERE id = $1", @@ -5475,15 +5519,9 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[tokio::test] #[ignore = "requires Postgres"] - async fn single_table_guard_approval_evidence_is_append_only_without_trigger() { + async fn single_table_guard_approval_evidence_is_append_only() { let (db, store) = store().await; let (request, _) = inventoried_request(&db, &store).await; - sqlx::query( - "ALTER TABLE community_deletion_approvals DISABLE TRIGGER community_deletion_approval_removal_guard", - ) - .execute(&db.pool) - .await - .expect("disable only approval guard"); store .approve(request.id, "first", None) .await @@ -5505,7 +5543,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[tokio::test] #[ignore = "requires Postgres"] - async fn single_table_guard_manifest_chunks_stop_at_freeze_without_trigger() { + async fn single_table_guard_manifest_chunks_stop_at_freeze() { let (db, store) = store().await; let (request, inventory) = inventoried_request(&db, &store).await; store @@ -5539,12 +5577,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .freeze_destructive_storage_manifest(&token, &manifest) .await .expect("freeze matching manifest"); - sqlx::query( - "ALTER TABLE community_deletion_manifest_keys DISABLE TRIGGER community_deletion_manifest_keys_guard", - ) - .execute(&db.pool) - .await - .expect("disable only manifest key guard"); assert!(matches!( store.append_manifest_key_chunk(&token, 1, &prefix, std::slice::from_ref(&key)).await, Err(DbError::DeletionSafety(message)) if message.contains("frozen") @@ -7503,41 +7535,9 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[tokio::test] #[ignore = "requires Postgres"] - async fn approved_request_cannot_be_retargeted_rewritten_or_claimed_without_approval() { + async fn approved_request_requires_approval_and_blocked_claim_cannot_renew() { let (db, store) = store().await; let (request, _) = inventoried_request(&db, &store).await; - let other_host = format!("control-{}.example", Uuid::new_v4().simple()); - let control = db - .ensure_configured_community(&other_host) - .await - .expect("create control community"); - - for mutation in [ - sqlx::query("UPDATE community_deletion_requests SET community_id = $2 WHERE id = $1") - .bind(request.id) - .bind(*control.id.as_uuid()) - .execute(&db.pool) - .await, - sqlx::query("UPDATE community_deletion_requests SET community_host = $2 WHERE id = $1") - .bind(request.id) - .bind(&other_host) - .execute(&db.pool) - .await, - sqlx::query( - "UPDATE community_deletion_requests SET inventory_manifest = '{}'::jsonb WHERE id = $1", - ) - .bind(request.id) - .execute(&db.pool) - .await, - sqlx::query( - "UPDATE community_deletion_requests SET storage_manifest = '{}'::jsonb WHERE id = $1", - ) - .bind(request.id) - .execute(&db.pool) - .await, - ] { - assert!(mutation.is_err(), "frozen deletion target and inventory must be immutable"); - } store .approve(request.id, "approver", None) @@ -7548,29 +7548,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .await .expect("claim approved request") .expect("approved request is claimable"); - let approval_delete = - sqlx::query("DELETE FROM community_deletion_approvals WHERE request_id = $1") - .bind(request.id) - .execute(&db.pool) - .await; - assert!( - approval_delete.is_err(), - "approval evidence must be immutable" - ); - for approval_update in [ - "UPDATE community_deletion_approvals SET approved_by = 'forged' WHERE request_id = $1", - "UPDATE community_deletion_approvals SET approved_at = now() + interval '1 hour' WHERE request_id = $1", - "UPDATE community_deletion_approvals SET note = 'rewritten' WHERE request_id = $1", - ] { - assert!( - sqlx::query(approval_update) - .bind(request.id) - .execute(&db.pool) - .await - .is_err(), - "approval evidence updates must be rejected" - ); - } store .verify_execution_token(&claim.lease, DeletionStage::Approved) .await @@ -8880,28 +8857,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .await, Err(DbError::DeletionSafety(_)) )); - for mutation in [ - sqlx::query( - "UPDATE community_deletion_requests \ - SET destructive_storage_manifest = '{}'::jsonb WHERE id = $1", - ) - .bind(request.id) - .execute(&db.pool) - .await, - sqlx::query( - "UPDATE community_deletion_requests \ - SET destructive_storage_frozen_at = destructive_storage_frozen_at + interval '1 second' \ - WHERE id = $1", - ) - .bind(request.id) - .execute(&db.pool) - .await, - ] { - assert!( - mutation.is_err(), - "frozen destructive storage evidence must be immutable" - ); - } store.mark_drained(&token).await.expect("drain"); store .mark_bindings_removed(&token, serde_json::json!({"keys": 0})) @@ -8962,14 +8917,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .await .expect("serving lookup") .is_none()); - let direct_delete = sqlx::query("DELETE FROM communities WHERE id = $1") - .bind(request.community_id.as_uuid()) - .execute(&db.pool) - .await - .expect_err("tombstone row must be permanent"); - assert!(direct_delete - .to_string() - .contains("tombstones are permanent")); } #[tokio::test] @@ -9053,37 +9000,8 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .await .expect("freeze manifest matching chunks"); - // Frozen chunks are immutable working data until terminal cleanup. - assert!(sqlx::query( - "UPDATE community_deletion_manifest_keys SET keys = '[]'::jsonb \ - WHERE request_id = $1 AND chunk_no = 0", - ) - .bind(request.id) - .execute(&db.pool) - .await - .is_err()); - assert!( - sqlx::query("DELETE FROM community_deletion_manifest_keys WHERE request_id = $1") - .bind(request.id) - .execute(&db.pool) - .await - .is_err() - ); + // Application cleanup refuses frozen chunks before the terminal stage. assert!(store.clear_manifest_key_chunks(&token).await.is_err()); - assert!( - sqlx::query( - "INSERT INTO community_deletion_manifest_keys \ - (request_id, chunk_no, prefix, keys) VALUES ($1, 2, $2, $3)", - ) - .bind(request.id) - .bind(&meta_prefix) - .bind(sqlx::types::Json(&keys[..1])) - .execute(&db.pool) - .await - .is_err(), - "the database must reject chunks appended after freeze" - ); - store.mark_drained(&token).await.expect("drained"); let first = store .next_pending_manifest_chunk(&token) @@ -9871,8 +9789,8 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); /// Before the parity restoration this wedged post-fence: /// `freeze_destructive_storage_manifest` hit the missing /// `community_deletion_manifest_keys` relation only after the write fence - /// was already up, leaving the request with no forward path — and even a - /// hand-created table would have lacked the immutability guard trigger. + /// was already up, leaving the request with no forward path. The owning + /// application transactions now enforce chunk immutability and staging. #[tokio::test] #[ignore = "requires Postgres"] async fn desired_state_schema_bootstrap_progresses_beyond_fencing() { @@ -9889,26 +9807,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); let store = db.deletion_store(); let (request, inventory) = inventoried_request(&db, &store).await; - // The immutability guard must exist and enforce: chunk rows are - // rejected outside an unfrozen fenced request (this request is still - // `inventoried`). - let premature_chunk = sqlx::query( - "INSERT INTO community_deletion_manifest_keys (request_id, chunk_no, prefix, keys) \ - VALUES ($1, 0, '_meta/premature/', '[]'::jsonb)", - ) - .bind(request.id) - .execute(&db.pool) - .await; - let guard_enforced = matches!( - &premature_chunk, - Err(sqlx::Error::Database(db_err)) if db_err.code().as_deref() == Some("23000") - ); - assert!( - guard_enforced, - "manifest-keys immutability guard must reject pre-fence chunks \ - with integrity_constraint_violation: {premature_chunk:?}" - ); - store .approve(request.id, "approver", None) .await diff --git a/crates/buzz-db/src/store/nip_fi_binding.rs b/crates/buzz-db/src/store/nip_fi_binding.rs index 79be374790d..7e57eaef1c9 100644 --- a/crates/buzz-db/src/store/nip_fi_binding.rs +++ b/crates/buzz-db/src/store/nip_fi_binding.rs @@ -852,8 +852,8 @@ mod postgres_tests { } /// Move `host`'s community out of `active` the way the deletion executor - /// does: the tombstone trigger admits the state change only under the - /// executor's community and fence-generation settings. + /// does, retaining transaction-scoped executor settings for older catalogs + /// that still enforce lifecycle changes in the database. async fn start_deleting(db: &Db, host: &str) { let mut tx = db.pool.begin().await.expect("begin"); let id: Uuid = sqlx::query_scalar("SELECT id FROM communities WHERE host = $1") diff --git a/crates/buzz-db/src/test_support.rs b/crates/buzz-db/src/test_support.rs index 783da0e7f75..f089297578b 100644 --- a/crates/buzz-db/src/test_support.rs +++ b/crates/buzz-db/src/test_support.rs @@ -394,9 +394,8 @@ pub(crate) async fn insert_historical_event_with_thread_metadata( } /// Move a community fixture into a deletion lifecycle state the way the -/// executor does: the tombstone trigger only accepts lifecycle changes from a -/// transaction carrying the executor GUCs for that community, including its -/// current fence generation. +/// executor does. Retain transaction-scoped executor GUCs for older catalogs +/// with a tombstone guard and fixtures that also write through universal fences. pub(crate) async fn set_deletion_state(pool: &sqlx::PgPool, id: uuid::Uuid, state: &str) { let mut tx = pool.begin().await.expect("begin lifecycle fixture"); set_deletion_state_in_transaction(&mut tx, id, state).await; diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index 35e657c243b..cc165e2480f 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -633,7 +633,7 @@ default so long-lived WebSocket connections have time to drain. Schema migrations are embedded in the relay binary via `sqlx::migrate!` and run at startup, gated by `BUZZ_AUTO_MIGRATE` (default `true`). Multiple replicas race-safely behind a Postgres advisory lock. Outside the required stop below, `helm upgrade` is the entire upgrade procedure. -**Required stop before migrations 0089–0091 and 0095.** These migrations drop database triggers whose work the relay now does in application code. Before you upgrade to a build that contains any of them, every relay pod, job and rollback target must run a stop build. An older relay that keeps serving after they run can write data the dropped triggers used to refuse, and some older builds refuse to start without the 0032 roster trigger. [`docs/trigger-retirement-deployment.md`](../../../docs/trigger-retirement-deployment.md) names the stop build and gives the procedure and rollback. +**Required stop before migrations 0089–0091, 0095 and 0096.** These migrations drop database triggers whose work the relay now does in application code. Before you upgrade to a build that contains any of them, every relay pod, job and rollback target must run a stop build. An older relay that keeps serving after they run can write data the dropped triggers used to refuse, and some older builds refuse to start without the 0032 roster trigger or the community tombstone trigger. [`docs/trigger-retirement-deployment.md`](../../../docs/trigger-retirement-deployment.md) names the stop build and gives the procedure and rollback. Apply migrations before rolling the relay; for large installations, prefer a controlled `buzz-admin migrate` job with PostgreSQL lock monitoring before the code rollout. diff --git a/docs/trigger-retirement-deployment.md b/docs/trigger-retirement-deployment.md index 0a64aadc2eb..569fafa7bc0 100644 --- a/docs/trigger-retirement-deployment.md +++ b/docs/trigger-retirement-deployment.md @@ -102,3 +102,41 @@ search fails with `42883 profile_name_fields(text) does not exist`. `0094` takes no table locks. It needs no cleanup, and a rollback to a stop build needs auto-migration off, as above. + +## Single-table guards (`0096`) + +`0096_drop_single_table_guards.sql` drops five single-table guard triggers and +their functions. The application writers and the catalog expand from +[#8320](https://github.com/block/buzz/pull/8320) now own each rule: + +| Table | Trigger / function | Application rule | +| --- | --- | --- | +| `channels` | `trg_channels_community_id_immutable` / `channels_community_id_immutable()` | `community_id` is bound at insert and never updated | +| `communities` | `communities_deletion_tombstone` / `enforce_community_tombstone()` | lifecycle changes go through one transition function | +| `community_deletion_requests` | `community_deletion_request_retargeting_guard` / `prevent_community_deletion_request_retargeting()` | inventory freezes are one-way | +| `community_deletion_approvals` | `community_deletion_approval_removal_guard` / `prevent_community_deletion_approval_removal()` | approvals are insert-only | +| `community_deletion_manifest_keys` | `community_deletion_manifest_keys_guard` / `protect_community_deletion_manifest_keys()` | chunk writes stop at freeze and `deleted_at` is one-way | + +**A relay build at or after commit `ec778bff` (the merge of +[#8320](https://github.com/block/buzz/pull/8320)) and before `0096` is a +required stop.** No tagged relay release contains it, so a deployment on a +tagged release must move to a stop build first. For a deployment that has not +yet passed `0094`, this supersedes the `0094` stop: `ec778bff` is an ancestor +of the `0094` merge, so one build at or after `ec778bff` that is also a valid +`0094` stop satisfies both, while a build between `279a31da` and `ec778bff` +satisfies only `0094`'s. Follow the same procedure as above. + +An older relay requires the tombstone trigger both at startup and on every +readiness check. Once `0096` has run, it fails both with +`community tombstone trigger is missing`: serving pods go not ready and a +restarted pod does not start, with auto-migration on or off. Its writers also +do not enforce the five rules above. + +`0096` takes `ACCESS EXCLUSIVE` on those five tables in one transaction, under +a 5s `lock_timeout` that bounds each lock acquisition. Reads and writes on +`channels` can queue while it acquires the remaining locks. A lock timeout +rolls the whole migration back, and a retry is clean. + +Roll back only to a build at or after `ec778bff`, with auto-migration off, as +in [Rollback](#rollback). A build below `ec778bff` does not start after +`0096`. diff --git a/migrations/0096_drop_single_table_guards.sql b/migrations/0096_drop_single_table_guards.sql new file mode 100644 index 00000000000..c84a19e0925 --- /dev/null +++ b/migrations/0096_drop_single_table_guards.sql @@ -0,0 +1,29 @@ +-- Drop the five single-table guard triggers and their functions. The +-- application writers now own each rule (crates/buzz-db/src/store/deletion.rs +-- and the channel writers), and serving/readiness catalog checks no longer +-- require these objects: +-- +-- - channels.community_id is bound once at insert and never updated; +-- - community lifecycle changes go through one transition function; +-- - deletion request inventory freezes are one-way; +-- - deletion approvals are insert-only; +-- - manifest chunk writes stop at freeze and deleted_at is one-way. +-- +-- Deploy the release that contains the application guards and the catalog +-- expand to every pod and job first; do not roll back below it. +-- +-- DROP TRIGGER takes ACCESS EXCLUSIVE on each table; fail the deployment +-- rather than queue relay reads and writes behind a long holder. +SET LOCAL lock_timeout = '5s'; + +DROP TRIGGER trg_channels_community_id_immutable ON channels; +DROP TRIGGER communities_deletion_tombstone ON communities; +DROP TRIGGER community_deletion_request_retargeting_guard ON community_deletion_requests; +DROP TRIGGER community_deletion_approval_removal_guard ON community_deletion_approvals; +DROP TRIGGER community_deletion_manifest_keys_guard ON community_deletion_manifest_keys; + +DROP FUNCTION channels_community_id_immutable(); +DROP FUNCTION enforce_community_tombstone(); +DROP FUNCTION prevent_community_deletion_request_retargeting(); +DROP FUNCTION prevent_community_deletion_approval_removal(); +DROP FUNCTION protect_community_deletion_manifest_keys(); diff --git a/schema/functions/channels_community_id_immutable.sql b/schema/functions/channels_community_id_immutable.sql deleted file mode 100644 index a22a5f91105..00000000000 --- a/schema/functions/channels_community_id_immutable.sql +++ /dev/null @@ -1,12 +0,0 @@ --- channels.community_id is immutable: a channel can never be re-tenanted. --- (Conformance: "Migration lint forbids channel re-tenanting except through an --- explicitly modeled admission path." We have no such path, so: hard block.) -CREATE FUNCTION channels_community_id_immutable() RETURNS TRIGGER AS $$ -BEGIN - IF NEW.community_id IS DISTINCT FROM OLD.community_id THEN - RAISE EXCEPTION 'channels.community_id is immutable (channel % cannot be re-tenanted)', OLD.id - USING ERRCODE = 'check_violation'; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; diff --git a/schema/functions/enforce_community_tombstone.sql b/schema/functions/enforce_community_tombstone.sql deleted file mode 100644 index b36b51333e0..00000000000 --- a/schema/functions/enforce_community_tombstone.sql +++ /dev/null @@ -1,28 +0,0 @@ -CREATE FUNCTION enforce_community_tombstone() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -DECLARE - executor_community TEXT := current_setting('buzz.deletion_executor_community', true); - executor_generation TEXT := current_setting('buzz.deletion_fence_generation', true); - expected_generation BIGINT; -BEGIN - IF TG_OP = 'DELETE' THEN - IF OLD.deletion_state <> 'active' OR OLD.deleted_at IS NOT NULL THEN - RAISE EXCEPTION 'community tombstones are permanent' - USING ERRCODE = 'object_not_in_prerequisite_state'; - END IF; - RETURN OLD; - END IF; - expected_generation := CASE WHEN NEW.deletion_fence_generation > OLD.deletion_fence_generation - THEN NEW.deletion_fence_generation ELSE OLD.deletion_fence_generation END; - IF executor_community = OLD.id::text AND executor_generation ~ '^[0-9]+$' - AND executor_generation::BIGINT = expected_generation THEN RETURN NEW; END IF; - IF OLD.deletion_state <> 'active' OR NEW.deletion_state <> OLD.deletion_state - OR NEW.deletion_fence_generation <> OLD.deletion_fence_generation - OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN - RAISE EXCEPTION 'community tombstone mutation rejected: community % generation %', - OLD.id, OLD.deletion_fence_generation - USING ERRCODE = 'object_not_in_prerequisite_state'; - END IF; - RETURN NEW; -END -$$; diff --git a/schema/functions/prevent_community_deletion_approval_removal.sql b/schema/functions/prevent_community_deletion_approval_removal.sql deleted file mode 100644 index 2e1d95db881..00000000000 --- a/schema/functions/prevent_community_deletion_approval_removal.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE FUNCTION prevent_community_deletion_approval_removal() -RETURNS trigger -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE EXCEPTION 'community deletion approval evidence is immutable' - USING ERRCODE = 'integrity_constraint_violation'; -END; -$$; diff --git a/schema/functions/prevent_community_deletion_request_retargeting.sql b/schema/functions/prevent_community_deletion_request_retargeting.sql deleted file mode 100644 index 23cff698bd7..00000000000 --- a/schema/functions/prevent_community_deletion_request_retargeting.sql +++ /dev/null @@ -1,39 +0,0 @@ -CREATE OR REPLACE FUNCTION prevent_community_deletion_request_retargeting() -RETURNS trigger -LANGUAGE plpgsql -AS $$ -BEGIN - IF NEW.community_id IS DISTINCT FROM OLD.community_id - OR NEW.community_host IS DISTINCT FROM OLD.community_host - THEN - RAISE EXCEPTION 'community deletion target identity is immutable' - USING ERRCODE = 'integrity_constraint_violation'; - END IF; - IF NEW.request_origin IS DISTINCT FROM OLD.request_origin - OR NEW.owner_pubkey IS DISTINCT FROM OLD.owner_pubkey - OR NEW.mediating_operator_pubkey IS DISTINCT FROM OLD.mediating_operator_pubkey - OR NEW.acknowledgement_version IS DISTINCT FROM OLD.acknowledgement_version - THEN - RAISE EXCEPTION 'community deletion request provenance is immutable' - USING ERRCODE = 'integrity_constraint_violation'; - END IF; - IF OLD.inventory_frozen_at IS NOT NULL AND ( - NEW.schema_manifest IS DISTINCT FROM OLD.schema_manifest - OR NEW.storage_manifest IS DISTINCT FROM OLD.storage_manifest - OR NEW.inventory_manifest IS DISTINCT FROM OLD.inventory_manifest - OR NEW.inventory_digest IS DISTINCT FROM OLD.inventory_digest - OR NEW.inventory_frozen_at IS DISTINCT FROM OLD.inventory_frozen_at - ) THEN - RAISE EXCEPTION 'frozen community deletion inventory is immutable' - USING ERRCODE = 'integrity_constraint_violation'; - END IF; - IF OLD.destructive_storage_frozen_at IS NOT NULL AND ( - NEW.destructive_storage_manifest IS DISTINCT FROM OLD.destructive_storage_manifest - OR NEW.destructive_storage_frozen_at IS DISTINCT FROM OLD.destructive_storage_frozen_at - ) THEN - RAISE EXCEPTION 'frozen destructive storage manifest is immutable' - USING ERRCODE = 'integrity_constraint_violation'; - END IF; - RETURN NEW; -END; -$$; diff --git a/schema/functions/protect_community_deletion_manifest_keys.sql b/schema/functions/protect_community_deletion_manifest_keys.sql deleted file mode 100644 index 4e90abaead8..00000000000 --- a/schema/functions/protect_community_deletion_manifest_keys.sql +++ /dev/null @@ -1,48 +0,0 @@ --- Chunk content is immutable once written; the only permitted update is the --- one-way deleted_at stamp. New chunks are permitted only while the request is --- fenced and its destructive manifest remains unfrozen. Removal is permitted --- only while the destructive manifest has not yet frozen (a retried partial --- freeze rewrites its chunks) or once the request has passed logical --- verification (terminal cleanup). -CREATE FUNCTION protect_community_deletion_manifest_keys() -RETURNS trigger -LANGUAGE plpgsql -AS $$ -DECLARE - frozen_at TIMESTAMPTZ; - request_stage TEXT; -BEGIN - IF TG_OP = 'UPDATE' THEN - IF NEW.request_id IS DISTINCT FROM OLD.request_id - OR NEW.chunk_no IS DISTINCT FROM OLD.chunk_no - OR NEW.prefix IS DISTINCT FROM OLD.prefix - OR NEW.keys IS DISTINCT FROM OLD.keys - OR OLD.deleted_at IS NOT NULL - THEN - RAISE EXCEPTION 'community deletion manifest key chunks are immutable' - USING ERRCODE = 'integrity_constraint_violation'; - END IF; - RETURN NEW; - END IF; - SELECT destructive_storage_frozen_at, stage - INTO frozen_at, request_stage - FROM community_deletion_requests - WHERE id = CASE WHEN TG_OP = 'INSERT' THEN NEW.request_id ELSE OLD.request_id END - FOR UPDATE; - IF TG_OP = 'INSERT' THEN - IF FOUND AND frozen_at IS NULL AND request_stage = 'fenced' THEN - RETURN NEW; - END IF; - RAISE EXCEPTION 'community deletion manifest key chunks require an unfrozen fenced request' - USING ERRCODE = 'integrity_constraint_violation'; - END IF; - IF NOT FOUND - OR frozen_at IS NULL - OR request_stage IN ('logically_verified', 'retention_pending') - THEN - RETURN OLD; - END IF; - RAISE EXCEPTION 'community deletion manifest key chunks cannot be removed mid-execution' - USING ERRCODE = 'integrity_constraint_violation'; -END; -$$; diff --git a/schema/schema.sql b/schema/schema.sql index 4b0529424a0..e8e651167f5 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -44,7 +44,7 @@ -- 2. No UNIQUE / PRIMARY KEY / FK on a scoped table is observable across -- communities: each leads with `community_id` (or, for child rows whose -- parent already pins the community, joins carry the community tuple). --- 3. `channels.community_id` is immutable (triggers/channels.sql; no UPDATE path). +-- 3. `channels.community_id` is immutable (application writers; no UPDATE path). -- 4. Operator-global tables are named in the explicit allowlist, not implied. CREATE EXTENSION IF NOT EXISTS pgcrypto; @@ -62,11 +62,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i types/channel_add_policy.sql -- functions -\i functions/channels_community_id_immutable.sql -\i functions/prevent_community_deletion_request_retargeting.sql -\i functions/prevent_community_deletion_approval_removal.sql -\i functions/protect_community_deletion_manifest_keys.sql -\i functions/enforce_community_tombstone.sql -- tables \i tables/public/communities.sql @@ -137,11 +132,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i partitions/delivery_log.sql -- triggers -\i triggers/channels.sql -\i triggers/community_deletion_requests.sql -\i triggers/community_deletion_approvals.sql -\i triggers/community_deletion_manifest_keys.sql -\i triggers/communities.sql -- seeds \i seeds/communities.sql diff --git a/schema/triggers/channels.sql b/schema/triggers/channels.sql deleted file mode 100644 index 0a7130cdb33..00000000000 --- a/schema/triggers/channels.sql +++ /dev/null @@ -1,3 +0,0 @@ -CREATE TRIGGER trg_channels_community_id_immutable - BEFORE UPDATE ON channels - FOR EACH ROW EXECUTE FUNCTION channels_community_id_immutable(); diff --git a/schema/triggers/communities.sql b/schema/triggers/communities.sql deleted file mode 100644 index 3bb684e1751..00000000000 --- a/schema/triggers/communities.sql +++ /dev/null @@ -1,2 +0,0 @@ -CREATE TRIGGER communities_deletion_tombstone BEFORE UPDATE OR DELETE ON communities -FOR EACH ROW EXECUTE FUNCTION enforce_community_tombstone(); diff --git a/schema/triggers/community_deletion_approvals.sql b/schema/triggers/community_deletion_approvals.sql deleted file mode 100644 index d23673a95b9..00000000000 --- a/schema/triggers/community_deletion_approvals.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TRIGGER community_deletion_approval_removal_guard -BEFORE UPDATE OR DELETE ON community_deletion_approvals -FOR EACH ROW -EXECUTE FUNCTION prevent_community_deletion_approval_removal(); diff --git a/schema/triggers/community_deletion_manifest_keys.sql b/schema/triggers/community_deletion_manifest_keys.sql deleted file mode 100644 index 477339bcaba..00000000000 --- a/schema/triggers/community_deletion_manifest_keys.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TRIGGER community_deletion_manifest_keys_guard -BEFORE INSERT OR UPDATE OR DELETE ON community_deletion_manifest_keys -FOR EACH ROW -EXECUTE FUNCTION protect_community_deletion_manifest_keys(); diff --git a/schema/triggers/community_deletion_requests.sql b/schema/triggers/community_deletion_requests.sql deleted file mode 100644 index 952f03322cd..00000000000 --- a/schema/triggers/community_deletion_requests.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TRIGGER community_deletion_request_retargeting_guard -BEFORE UPDATE ON community_deletion_requests -FOR EACH ROW -EXECUTE FUNCTION prevent_community_deletion_request_retargeting();