From 17a3beae1b65a58ee8c22bc62b3a2621c4059141 Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Thu, 19 Nov 2026 22:35:45 -0500 Subject: [PATCH 1/7] Drop the unused delivery_log and subscriptions tables Migration 0105 drops both tables and the three enums only they used. manifest, pgschema ignore list and reconcile script drop their delivery_log parts. Community deletion's catalog is an exact set again. A frozen approval from before 0105 may still list the two tables, and validate_approved_schema accepts that they are gone. Signed-off-by: Luke Tornquist Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- .pgschemaignore | 14 +- ARCHITECTURE.md | 1 - crates/buzz-db/src/runtime/migration.rs | 73 +++-- crates/buzz-db/src/store/deletion.rs | 321 ++++---------------- crates/buzz-deletion/src/lib.rs | 113 +++---- docs/database.md | 40 ++- docs/trigger-retirement-deployment.md | 5 +- migrations/0106_drop_delivery_tables.sql | 39 +++ schema/partitions/delivery_log.sql | 16 - schema/schema.sql | 6 - schema/tables/public/delivery_log.sql | 19 -- schema/tables/public/subscriptions.sql | 22 -- schema/types/delivery_method.sql | 1 - schema/types/pause_reason.sql | 1 - schema/types/subscription_status.sql | 1 - scripts/drop-partitioned-foreign-keys.sql | 16 +- scripts/reconcile-schema-after-pgschema.sql | 71 +---- 17 files changed, 222 insertions(+), 537 deletions(-) create mode 100644 migrations/0106_drop_delivery_tables.sql delete mode 100644 schema/partitions/delivery_log.sql delete mode 100644 schema/tables/public/delivery_log.sql delete mode 100644 schema/tables/public/subscriptions.sql delete mode 100644 schema/types/delivery_method.sql delete mode 100644 schema/types/pause_reason.sql delete mode 100644 schema/types/subscription_status.sql diff --git a/.pgschemaignore b/.pgschemaignore index ef3938b4cf8..56bb462fe97 100644 --- a/.pgschemaignore +++ b/.pgschemaignore @@ -2,11 +2,10 @@ # from the repository root. # # The relay's partition manager creates dated `events` monthlies at runtime -# (see crates/buzz-db/src/store/partition/). Older relays also created -# `delivery_log` monthlies; their pattern stays until a migration drops that -# table. These monthlies are not declared in schema/partitions/, so without -# this file re-applying pgschema to a database a relay has used drops them, and -# their rows, with `DROP TABLE IF EXISTS ... CASCADE`. Only the monthlies schema/partitions/ +# (see crates/buzz-db/src/store/partition/). They are not declared in +# schema/partitions/, so without this file re-applying pgschema to a database a +# relay has used drops them, and their rows, with +# `DROP TABLE IF EXISTS ... CASCADE`. Only the monthlies schema/partitions/ # declares stay managed by pgschema; keep the `!` exemptions below in sync with # them. [tables] @@ -18,9 +17,4 @@ patterns = [ "!events_p2026_04", "!events_p2026_05", "!events_p2026_06", - "delivery_log_p2*", - "!delivery_log_p2026_03", - "!delivery_log_p2026_04", - "!delivery_log_p2026_05", - "!delivery_log_p2026_06", ] diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6a25d266bb1..6e49c91bebf 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -951,7 +951,6 @@ Docker Compose provides the full local development stack. All services include h | `workflow_runs` | Execution records with trigger context and trace | | `workflow_approvals` | Approval gates (token stored as SHA-256 hash) | | `audit_log` | Hash-chain audit entries; per-community chain/head in multi-community mode | -| `delivery_log` | Delivery tracking (partitioned; Rust module pending) | ### Redis Key Patterns diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 33f95a43cfe..8e1fdade636 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -879,7 +879,20 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 105); + assert_eq!(migrations.len(), 106); + assert_eq!(migrations[105].version, 106); + let drop_delivery_tables = strip_sql_comments(migrations[105].sql.as_str()); + assert!(drop_delivery_tables.contains("SET LOCAL lock_timeout = '300ms';")); + for statement in [ + "DROP TABLE IF EXISTS delivery_log;", + "DROP TABLE IF EXISTS subscriptions;", + "DROP TYPE IF EXISTS delivery_method;", + "DROP TYPE IF EXISTS subscription_status;", + "DROP TYPE IF EXISTS pause_reason;", + ] { + assert!(drop_delivery_tables.contains(statement), "{statement}"); + } + assert!(!drop_delivery_tables.contains("CASCADE")); assert_eq!(migrations[104].version, 105); assert!(strip_sql_comments(migrations[104].sql.as_str()) .contains("ADD COLUMN finished BOOLEAN NOT NULL DEFAULT true;")); @@ -1553,9 +1566,12 @@ mod postgres_tests { "media_uploaders", "media_publications", ]; + // 0090 is immutable and also retired the fences on the two tables + // migration 0105 later drops, so list them here. + let dropped_later = ["delivery_log", "subscriptions"]; for table in crate::deletion::EXPECTED_SCOPED_TABLES .iter() - .chain(crate::deletion::RETIRING_SCOPED_TABLES) + .chain(dropped_later.iter()) .filter(|table| !never_fenced.contains(table)) { assert!( @@ -3415,8 +3431,7 @@ mod postgres_tests { async fn catch_all_bounds(pool: &PgPool) -> Vec<(String, Option)> { sqlx::query_as( "SELECT relname::text, pg_get_expr(relpartbound, oid) FROM pg_class \ - WHERE relname IN ('events_p_future', 'delivery_log_p_future') \ - ORDER BY relname", + WHERE relname = 'events_p_future'", ) .fetch_all(pool) .await @@ -3424,13 +3439,12 @@ mod postgres_tests { } let declared_bounds = catch_all_bounds(&pool).await; assert!( - declared_bounds.len() == 2 && declared_bounds.iter().all(|(_, bound)| bound.is_some()), - "reconcile did not attach both catch-alls: {declared_bounds:?}" + declared_bounds.len() == 1 && declared_bounds.iter().all(|(_, bound)| bound.is_some()), + "reconcile did not attach the catch-all: {declared_bounds:?}" ); // The relay's default startup pass advances the `events` catch-all into - // dated monthlies schema/partitions/ does not declare. `delivery_log` is - // retired from partition management, so its catch-all stays as declared. + // dated monthlies schema/partitions/ does not declare. maintain_partitions( &pool, PARTITION_MANAGER_MONTHS_AHEAD, @@ -3443,15 +3457,11 @@ mod postgres_tests { .expect("maintain partitions"); let advanced_bounds = catch_all_bounds(&pool).await; assert!( - advanced_bounds.len() == 2 && advanced_bounds.iter().all(|(_, bound)| bound.is_some()), - "maintenance dropped or detached a catch-all: {advanced_bounds:?}" + advanced_bounds.len() == 1 && advanced_bounds.iter().all(|(_, bound)| bound.is_some()), + "maintenance dropped or detached the catch-all: {advanced_bounds:?}" ); for (declared, advanced) in declared_bounds.iter().zip(&advanced_bounds) { - if declared.0 == "events_p_future" { - assert_ne!(declared, advanced, "catch-all did not advance"); - } else { - assert_eq!(declared, advanced, "retired table was partition-managed"); - } + assert_ne!(declared, advanced, "catch-all did not advance"); } let children: Vec<(String, String)> = sqlx::query_as( "SELECT p.relname::text, c.relname::text FROM pg_inherits i \ @@ -3469,10 +3479,7 @@ mod postgres_tests { child.starts_with(&format!("{parent}_p2")) && !declared.contains(child) }) .collect(); - for (catch_all, bound) in declared_bounds - .iter() - .filter(|(catch_all, _)| catch_all == "events_p_future") - { + for (catch_all, bound) in &declared_bounds { // The first month the declared catch-all served, from its // `FOR VALUES FROM ('YYYY-MM-01 ...')` lower bound. let parent = catch_all @@ -4193,6 +4200,24 @@ mod postgres_tests { ); } + /// Before migration 0105 the delivery tables are live, and the deletion + /// catalog check refuses exactly them as unknown tenant tables and nothing + /// else. Migrations apply before code, so no deployment runs this binary + /// against such a catalog. Asserting the whole drift keeps the check as + /// strict as it is on the current schema. + async fn assert_only_delivery_tables_drift(store: &crate::deletion::DeletionStore) { + let error = store + .validate_catalog() + .await + .expect_err("deletion refuses the delivery tables before migration 0105"); + assert!( + error + .to_string() + .contains("(missing=, unknown=delivery_log,subscriptions)"), + "{error}" + ); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn migrated_catalog_retires_universal_fences_but_keeps_deletion_guards() { @@ -4212,10 +4237,7 @@ mod postgres_tests { .validate_serving_catalog() .await .expect("new runtime must accept pre-retirement catalog"); - store - .validate_catalog() - .await - .expect("deletion must accept pre-retirement catalog"); + assert_only_delivery_tables_drift(&store).await; run_migrations(&pool).await.expect("apply all migrations"); let fence_triggers: i64 = sqlx::query_scalar( "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname LIKE 'community_write_fence_%'", @@ -4288,10 +4310,7 @@ mod postgres_tests { .validate_serving_catalog() .await .expect("new code must boot before the drop"); - store - .validate_catalog() - .await - .expect("deletion must accept the catalog before the drop"); + assert_only_delivery_tables_drift(&store).await; run_migrations(&pool).await.expect("apply all migrations"); assert_eq!(present(&pool).await, (false, false)); store diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 7b054e2b6d6..c613c8b2c23 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -88,8 +88,8 @@ pub const RELAY_ADMIN_TABLES: &[(&str, &str)] = &[ /// Catalog inventory compares the live database against this exact set before /// approval and again before PostgreSQL purge. A new tenant table therefore /// blocks deletion until this manifest is intentionally updated. -/// [`PENDING_SCOPED_TABLES`] and [`RETIRING_SCOPED_TABLES`] are accepted present -/// or absent and are not listed here. +/// [`PENDING_SCOPED_TABLES`] are accepted present or absent and are not listed +/// here. pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "nip_fi_profile_heads", "api_tokens", @@ -127,25 +127,17 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "workflows", ]; -/// Tenant tables a later contract migration drops. +/// Tenant tables that migration 0105 dropped, kept only for frozen approvals. /// -/// Nothing reads or writes these tables any more, but they still exist until -/// that migration runs. Like [`PENDING_SCOPED_TABLES`], the catalog accepts each -/// one present or absent; when present, the purge deletes its rows and -/// verification proves it empty. That keeps community deletion working before -/// the drop, after it, in a mixed fleet, and for a request approved before the -/// drop and executed after it: `validate_approved_schema` in `buzz-deletion` -/// accepts a frozen table from this list that is no longer live, and no other. -/// -/// The list is separate from [`PENDING_SCOPED_TABLES`] because the two -/// lifecycles differ: a pending table is absent now and may appear after an -/// approval ([`APPROVAL_FORWARD_TABLES`]), while a retiring table is live now -/// and may vanish after one. They are purged ahead of [`PURGE_SCOPED_TABLES`], -/// which satisfies the foreign key from `subscriptions` to `users`; -/// `delivery_log` has no foreign key to another tenant table. Once the -/// migration that drops a table has shipped everywhere and its approvals have -/// drained, remove it from this list. -pub const RETIRING_SCOPED_TABLES: &[&str] = &["delivery_log", "subscriptions"]; +/// No database has these tables at this version: deployments apply migrations +/// before code, and auto-migration runs before the relay serves. A live table +/// with one of these names is an unknown scoped table, so the catalog check +/// fails closed and deletion refuses it. The one use is +/// `validate_approved_schema` in `buzz-deletion`: a deletion request approved +/// before migration 0105 froze an inventory that lists these tables, and its +/// executor must still accept that they are gone. Remove this list once no +/// approval from before migration 0105 can remain. +pub const DROPPED_SCOPED_TABLES: &[&str] = &["delivery_log", "subscriptions"]; /// Tenant tables that a later release's expand migration adds. /// @@ -2380,8 +2372,8 @@ impl DeletionStore { } // Child before parent, not alphabetical (see PURGE_SCOPED_TABLES). A // later unit can observe zero rows; each scoped WHERE stays idempotent. - let optional = live_optional_tables_on(&mut tx).await?; - for table in optional.iter().chain(PURGE_SCOPED_TABLES) { + let pending = live_pending_tables_on(&mut tx).await?; + for table in pending.iter().chain(PURGE_SCOPED_TABLES) { let sql = format!("DELETE FROM {table} WHERE community_id = $1"); let affected = sqlx::query(AssertSqlSafe(sql)) .bind(token.community_id.as_uuid()) @@ -2476,10 +2468,10 @@ impl DeletionStore { token.community_id ))); } - let optional = live_optional_tables_on(&mut tx).await?; + let pending = live_pending_tables_on(&mut tx).await?; let scoped = EXPECTED_SCOPED_TABLES .iter() - .chain(&optional) + .chain(&pending) .map(|table| (*table, format!("FROM {table} WHERE community_id = $1"))); let relay_admin = RELAY_ADMIN_TABLES .iter() @@ -3620,10 +3612,7 @@ async fn validate_catalog_on(conn: &mut PgConnection) -> Result<()> { .map(str::to_owned) .collect::>(); let mut live_tables = live_scoped_tables_on(conn).await?; - live_tables.retain(|table| { - !PENDING_SCOPED_TABLES.contains(&table.as_str()) - && !RETIRING_SCOPED_TABLES.contains(&table.as_str()) - }); + live_tables.retain(|table| !PENDING_SCOPED_TABLES.contains(&table.as_str())); if live_tables != expected { let missing = expected .difference(&live_tables) @@ -3643,14 +3632,12 @@ async fn validate_catalog_on(conn: &mut PgConnection) -> Result<()> { Ok(()) } -/// The [`PENDING_SCOPED_TABLES`] and [`RETIRING_SCOPED_TABLES`] that exist. -/// Call under the shared schema/destruction lock so the answer holds until the -/// transaction ends. -async fn live_optional_tables_on(conn: &mut PgConnection) -> Result> { +/// The [`PENDING_SCOPED_TABLES`] that exist. Call under the shared +/// schema/destruction lock so the answer holds until the transaction ends. +async fn live_pending_tables_on(conn: &mut PgConnection) -> Result> { let live = live_scoped_tables_on(conn).await?; Ok(PENDING_SCOPED_TABLES .iter() - .chain(RETIRING_SCOPED_TABLES) .copied() .filter(|table| live.contains(*table)) .collect()) @@ -4162,19 +4149,6 @@ mod tests { } } - /// A retiring table is optional everywhere: never required by the catalog - /// or the fixed purge list, never also pending, and never added after an - /// approval. - #[test] - fn retiring_scoped_tables_are_only_optional() { - for table in RETIRING_SCOPED_TABLES { - assert!(!EXPECTED_SCOPED_TABLES.contains(table), "{table}"); - assert!(!PURGE_SCOPED_TABLES.contains(table), "{table}"); - assert!(!PENDING_SCOPED_TABLES.contains(table), "{table}"); - assert!(!APPROVAL_FORWARD_TABLES.contains(table), "{table}"); - } - } - fn empty_prefix(prefix: &str) -> PrefixManifest { PrefixManifest { prefix: prefix.to_string(), @@ -4804,11 +4778,6 @@ pub(crate) mod postgres_tests { .chain(COMMUNITY_SCOPED_CONTROL_PLANE_TABLES.iter()) .map(|table| (*table).to_owned()) .collect::>(); - // Retiring tables are accepted present or absent. - let live = live - .into_iter() - .filter(|table| !RETIRING_SCOPED_TABLES.contains(&table.as_str())) - .collect::>(); assert_eq!(live, accounted); } @@ -4863,6 +4832,13 @@ pub(crate) mod postgres_tests { crate::migration::run_migrations_through(&db.pool, 89) .await .expect("migrate with fence objects present"); + // Migration 0105 drops the delivery tables, and the deletion catalog no + // longer accepts them as tenant tables. Drop them by hand so the + // catalog is the current one; their triggers go with them. + sqlx::raw_sql("DROP TABLE delivery_log, subscriptions") + .execute(&db.pool) + .await + .expect("drop the tables migration 0105 drops"); let store = db.deletion_store(); let community = db .ensure_configured_community("optional-fences.example") @@ -4883,7 +4859,6 @@ DROP TRIGGER IF EXISTS community_write_fence_channel_members ON channel_members; DROP TRIGGER IF EXISTS community_write_fence_channels ON channels; DROP TRIGGER IF EXISTS community_write_fence_community_bans ON community_bans; DROP TRIGGER IF EXISTS community_write_fence_community_nip_fi_issuers ON community_nip_fi_issuers; -DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log; DROP TRIGGER IF EXISTS community_write_fence_event_mentions ON event_mentions; DROP TRIGGER IF EXISTS community_write_fence_events ON events; DROP TRIGGER IF EXISTS community_write_fence_git_repo_names ON git_repo_names; @@ -4901,7 +4876,6 @@ DROP TRIGGER IF EXISTS community_write_fence_reactions ON reactions; DROP TRIGGER IF EXISTS community_write_fence_relay_invites ON relay_invites; DROP TRIGGER IF EXISTS community_write_fence_relay_members ON relay_members; DROP TRIGGER IF EXISTS community_write_fence_scheduled_workflow_fires ON scheduled_workflow_fires; -DROP TRIGGER IF EXISTS community_write_fence_subscriptions ON subscriptions; DROP TRIGGER IF EXISTS community_write_fence_thread_metadata ON thread_metadata; DROP TRIGGER IF EXISTS community_write_fence_users ON users; DROP TRIGGER IF EXISTS community_write_fence_workflow_approvals ON workflow_approvals; @@ -4931,12 +4905,7 @@ DROP FUNCTION community_deletion_lock_key(UUID); .expect("readiness"); store.validate_catalog().await.expect("deletion catalog"); let inventory = store.inventory_schema(community).await.expect("inventory"); - let required = inventory - .scoped_tables - .iter() - .filter(|table| !RETIRING_SCOPED_TABLES.contains(&table.as_str())) - .count(); - assert_eq!(required, EXPECTED_SCOPED_TABLES.len()); + assert_eq!(inventory.scoped_tables.len(), EXPECTED_SCOPED_TABLES.len()); assert!(inventory.fenced_tables.is_empty()); let lease = store .acquire_serving_write_lease( @@ -5008,6 +4977,13 @@ DROP FUNCTION community_deletion_lock_key(UUID); crate::migration::run_migrations_through(&db.pool, 86) .await .expect("phase-one schema"); + // Migration 0105 drops the delivery tables, and the deletion catalog no + // longer accepts them as tenant tables. Drop them by hand so the + // catalog is the current one. + sqlx::raw_sql("DROP TABLE delivery_log, subscriptions") + .execute(&db.pool) + .await + .expect("drop the tables migration 0105 drops"); let community = db .ensure_configured_community("optional-guards.example") .await @@ -8933,16 +8909,9 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); let first = store.purge_postgres(&token).await.expect("purge postgres"); assert_eq!(first["media_uploaders"], 1); assert_eq!(first["media_publications"], 1); - let optional = { - let mut conn = db.pool.acquire().await.expect("acquire connection"); - live_optional_tables_on(&mut conn) - .await - .expect("live optional tables") - }; let expected_tables: BTreeSet<&str> = EXPECTED_SCOPED_TABLES .iter() .chain(RELAY_ADMIN_TABLES.iter().map(|(table, _)| table)) - .chain(&optional) .copied() .collect(); assert_eq!( @@ -9689,9 +9658,13 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); } } - /// Scratch desired-state database and a store on it. - async fn scratch_retiring_store(prefix: &str) -> (Db, DeletionStore, ScratchDb) { - let (_, scratch) = scratch_desired_state_database(prefix).await; + /// Migration 0105 dropped `delivery_log` and `subscriptions`. A live table + /// with either name is no longer accepted: it is an unknown tenant table, so + /// the catalog check fails closed and deletion refuses to proceed. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn dropped_scoped_tables_are_rejected_as_unknown_when_live() { + let (_, scratch) = scratch_desired_state_database("deletion_dropped").await; let db = Db::new(&DbConfig { database_url: scratch.url().to_owned(), max_connections: 5, @@ -9701,219 +9674,31 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .await .expect("connect scratch database"); let store = db.deletion_store(); - (db, store, scratch) - } - - /// Approve, claim, fence, drain and remove bindings, leaving the request - /// ready for `purge_postgres`. - async fn fence_and_drain( - store: &DeletionStore, - request: &DeletionRequest, - inventory: &FrozenInventory, - ) -> LeaseToken { - store - .approve(request.id, "approver", None) - .await - .expect("approve"); - let claim = store - .claim_specific(request.id, "executor", DEFAULT_LEASE_DURATION) - .await - .expect("claim") - .expect("won claim"); - store.begin_quiescing(&claim.lease).await.expect("quiesce"); - let generation = store.fence(&claim.lease).await.expect("fence"); - let token = LeaseToken { - fence_generation: Some(generation), - ..claim.lease - }; - store - .freeze_destructive_storage_manifest(&token, &inventory.storage) - .await - .expect("freeze destructive storage"); - store.mark_drained(&token).await.expect("drain"); - store - .mark_bindings_removed(&token, serde_json::json!({"keys": 0})) - .await - .expect("bindings"); - token - } - - /// One `subscriptions` row and one `delivery_log` row per community. - async fn seed_retiring_tables(db: &Db, communities: &[Uuid]) { - for community in communities { - for statement in [ - "INSERT INTO users (community_id, pubkey) VALUES ($1, decode(repeat('51', 32), 'hex'))", - "INSERT INTO subscriptions (community_id, id, owner_pubkey) \ - VALUES ($1, 'retiring', decode(repeat('51', 32), 'hex'))", - "INSERT INTO delivery_log (community_id, subscription_id) VALUES ($1, 'retiring')", - ] { - sqlx::query(statement) - .bind(community) - .execute(&db.pool) - .await - .expect("seed retiring table"); - } - } - } - - /// While the retiring tables still exist, the catalog accepts them, the - /// purge deletes the target community's rows and no one else's, and - /// verification proves them empty. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn retiring_scoped_tables_are_purged_and_verified_while_present() { - let (db, store, _scratch) = scratch_retiring_store("deletion_retiring_present").await; store .validate_catalog() .await - .expect("retiring tables present"); - let (request, inventory) = inventoried_request(&db, &store).await; - for table in RETIRING_SCOPED_TABLES { - assert!( - inventory - .schema - .scoped_tables - .iter() - .any(|frozen| frozen == table), - "{table} is inventoried while it exists" - ); - } - let community = *request.community_id.as_uuid(); - let bystander = *db - .ensure_configured_community(&format!("bystander-{}.example", Uuid::new_v4().simple())) - .await - .expect("bystander community") - .id - .as_uuid(); - seed_retiring_tables(&db, &[community, bystander]).await; - - let token = fence_and_drain(&store, &request, &inventory).await; - let deleted = store.purge_postgres(&token).await.expect("purge postgres"); - for table in RETIRING_SCOPED_TABLES { - assert_eq!(deleted.get(*table), Some(&1), "{table}"); - } - store - .mark_cache_purged(&token, serde_json::json!({"keys": 0})) - .await - .expect("cache"); + .expect("catalog without the dropped tables"); - // Verification covers the retiring tables: a straggler fails it. - for (table, insert) in [ - ( - "subscriptions", - "INSERT INTO subscriptions (community_id, id, owner_pubkey) \ - VALUES ($1, 'straggler', decode(repeat('51', 32), 'hex'))", - ), - ( - "delivery_log", - "INSERT INTO delivery_log (community_id, subscription_id) VALUES ($1, 'straggler')", - ), - ] { - sqlx::query(insert) - .bind(community) - .execute(&db.pool) - .await - .expect("seed straggler"); - let error = store - .verify_postgres_logically_deleted(&token) - .await - .expect_err("a straggler in a retiring table fails verification"); - assert!(error.to_string().contains(table), "{error}"); + for table in DROPPED_SCOPED_TABLES { sqlx::query(AssertSqlSafe(format!( - "DELETE FROM {table} WHERE community_id = $1" + "CREATE TABLE {table} (community_id UUID NOT NULL)" ))) - .bind(community) .execute(&db.pool) .await - .expect("remove straggler"); - } - store - .verify_postgres_logically_deleted(&token) - .await - .expect("verify"); - for table in RETIRING_SCOPED_TABLES { - let kept: i64 = sqlx::query_scalar(AssertSqlSafe(format!( - "SELECT count(*) FROM {table} WHERE community_id = $1" - ))) - .bind(bystander) - .fetch_one(&db.pool) - .await - .expect("count bystander rows"); - assert_eq!(kept, 1, "{table} keeps the bystander's row"); - } - } - - /// A deletion inventoried while the retiring tables existed and executed - /// after a later migration dropped them: the catalog still validates, the - /// purge and verification skip the missing tables, and another unknown - /// tenant table still fails closed. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn retiring_scoped_tables_may_be_dropped_before_purge() { - let (db, store, _scratch) = scratch_retiring_store("deletion_retiring_dropped").await; - let (request, inventory) = inventoried_request(&db, &store).await; - for table in RETIRING_SCOPED_TABLES { + .expect("create dropped table"); + let error = store + .validate_catalog() + .await + .expect_err("a live dropped table fails closed"); assert!( - inventory - .schema - .scoped_tables - .iter() - .any(|frozen| frozen == table), - "{table} is frozen while it exists" + error.to_string().contains(&format!("unknown={table}")), + "{error}" ); - } - - // The contract migration lands after the request was inventoried. - for table in RETIRING_SCOPED_TABLES { sqlx::query(AssertSqlSafe(format!("DROP TABLE {table}"))) .execute(&db.pool) .await - .expect("drop retiring table"); - } - store - .validate_catalog() - .await - .expect("catalog accepts the retiring tables absent"); - let live = store - .inventory_schema(request.community_id) - .await - .expect("inventory after drop"); - for table in RETIRING_SCOPED_TABLES { - assert!(!live.scoped_tables.iter().any(|live| live == table)); - } - - sqlx::query("CREATE TABLE deletion_unknown_scoped (community_id UUID NOT NULL)") - .execute(&db.pool) - .await - .expect("create unknown table"); - let error = store - .validate_catalog() - .await - .expect_err("an unknown tenant table still fails closed"); - assert!( - error - .to_string() - .contains("(missing=, unknown=deletion_unknown_scoped)"), - "{error}" - ); - sqlx::query("DROP TABLE deletion_unknown_scoped") - .execute(&db.pool) - .await - .expect("drop unknown table"); - - let token = fence_and_drain(&store, &request, &inventory).await; - let deleted = store.purge_postgres(&token).await.expect("purge postgres"); - for table in RETIRING_SCOPED_TABLES { - assert!(!deleted.contains_key(*table), "{table}"); + .expect("drop dropped table"); } - store - .mark_cache_purged(&token, serde_json::json!({"keys": 0})) - .await - .expect("cache"); - store - .verify_postgres_logically_deleted(&token) - .await - .expect("verify"); } /// Report-backed staff actions FK `moderation_reports`, and outbox rows FK diff --git a/crates/buzz-deletion/src/lib.rs b/crates/buzz-deletion/src/lib.rs index 40a584a44b5..f074edea61c 100644 --- a/crates/buzz-deletion/src/lib.rs +++ b/crates/buzz-deletion/src/lib.rs @@ -1423,9 +1423,9 @@ fn validate_approved_schema( ) -> Result<()> { // The approved catalog binds exactly, with two bounded exceptions. An // expand migration between approval and execution may add a table listed - // in APPROVAL_FORWARD_TABLES, which this binary purges and verifies. A - // contract migration may drop a table listed in RETIRING_SCOPED_TABLES, which - // this binary purges and verifies only while it exists. The frozen manifest + // in APPROVAL_FORWARD_TABLES, which this binary purges and verifies. And an + // approval from before migration 0105 may freeze a table listed in + // DROPPED_SCOPED_TABLES, which that migration dropped. The frozen manifest // and its digest are never rewritten. let frozen_tables = frozen .schema @@ -1438,7 +1438,7 @@ fn validate_approved_schema( .collect::>(); let removed = frozen_tables .difference(&live_tables) - .any(|table| !buzz_db::deletion::RETIRING_SCOPED_TABLES.contains(&table.as_str())); + .any(|table| !buzz_db::deletion::DROPPED_SCOPED_TABLES.contains(&table.as_str())); let unlisted_addition = live_tables .difference(&frozen_tables) .any(|table| !buzz_db::deletion::APPROVAL_FORWARD_TABLES.contains(&table.as_str())); @@ -1895,12 +1895,13 @@ mod postgres_tests { assert!(resolve_submit_host(None, Some("not a URL")).is_err()); } - /// An approved catalog tolerates a retiring table vanishing before - /// execution, and nothing else: any other frozen table that is gone, or a - /// table added after approval and not forward-listed, is still drift. + /// An approval from before migration 0105 froze the tables it dropped, and + /// its catalog tolerates exactly those being gone: any other frozen table + /// that is gone, or a table live now that the approval did not freeze and + /// that is not forward-listed, is still drift. #[test] - fn approved_schema_tolerates_only_retiring_tables_vanishing() { - use buzz_db::deletion::{SchemaManifest, EXPECTED_SCOPED_TABLES, RETIRING_SCOPED_TABLES}; + fn approved_schema_tolerates_only_dropped_tables_vanishing() { + use buzz_db::deletion::{SchemaManifest, DROPPED_SCOPED_TABLES, EXPECTED_SCOPED_TABLES}; let manifest = |tables: &[String]| SchemaManifest { scoped_tables: tables.to_vec(), @@ -1911,34 +1912,32 @@ mod postgres_tests { .iter() .map(|table| (*table).to_owned()) .collect(); - let mut with_retiring = required.clone(); - with_retiring.extend( - RETIRING_SCOPED_TABLES + let mut with_dropped = required.clone(); + with_dropped.extend( + DROPPED_SCOPED_TABLES .iter() .map(|table| (*table).to_owned()), ); let frozen = FrozenInventory { - schema: manifest(&with_retiring), + schema: manifest(&with_dropped), storage: empty_storage_manifest(buzz_core::CommunityId::from_uuid(Uuid::new_v4())), }; - validate_approved_schema(&manifest(&with_retiring), &frozen) - .expect("retiring tables still live"); validate_approved_schema(&manifest(&required), &frozen) - .expect("every retiring table dropped after approval"); - for kept in RETIRING_SCOPED_TABLES { - let partial: Vec = with_retiring + .expect("every dropped table gone after approval"); + for kept in DROPPED_SCOPED_TABLES { + let partial: Vec = with_dropped .iter() .filter(|table| table.as_str() != *kept) .cloned() .collect(); validate_approved_schema(&manifest(&partial), &frozen) - .expect("one retiring table dropped after approval"); + .expect("one dropped table gone after approval"); } - // A required table that is gone is drift, with or without the - // retiring tables beside it. - for live in [&with_retiring, &required] { + // A required table that is gone is drift, with or without the dropped + // tables beside it. + for live in [&with_dropped, &required] { let missing: Vec = live .iter() .filter(|table| table.as_str() != "workflows") @@ -1946,16 +1945,16 @@ mod postgres_tests { .collect(); assert!(validate_approved_schema(&manifest(&missing), &frozen).is_err()); } - // An unlisted addition is drift, and a retiring table is not exempt - // from that when the approval never froze it. + // An unlisted addition is drift, and a dropped table coming back is not + // exempt from that when the approval never froze it. let mut unknown = required.clone(); unknown.push("unknown_tenant_table".to_owned()); assert!(validate_approved_schema(&manifest(&unknown), &frozen).is_err()); - let without_retiring = FrozenInventory { + let without_dropped = FrozenInventory { schema: manifest(&required), storage: frozen.storage.clone(), }; - assert!(validate_approved_schema(&manifest(&with_retiring), &without_retiring).is_err()); + assert!(validate_approved_schema(&manifest(&with_dropped), &without_dropped).is_err()); } fn empty_storage_manifest(community: buzz_core::CommunityId) -> StorageManifest { @@ -2584,14 +2583,15 @@ mod postgres_tests { validate_approved_schema(&live, &decoded) .expect("legacy fence list is no longer structural"); - // A retiring table the approval froze may be dropped before execution. - let mut dropped = live.clone(); - dropped - .scoped_tables - .retain(|table| !buzz_db::deletion::RETIRING_SCOPED_TABLES.contains(&table.as_str())); - assert!(dropped.scoped_tables.len() < live.scoped_tables.len()); - validate_approved_schema(&dropped, &decoded) - .expect("a dropped retiring table is not drift"); + // An approval from before migration 0105 froze the tables it dropped. + let mut approved_before_drop = decoded.clone(); + approved_before_drop.schema.scoped_tables.extend( + buzz_db::deletion::DROPPED_SCOPED_TABLES + .iter() + .map(|table| (*table).to_owned()), + ); + validate_approved_schema(&live, &approved_before_drop) + .expect("a table dropped by migration 0105 is not drift"); // Only a listed forward table may appear after approval. A required // table the approval lacks is drift, and so is a removed frozen table. @@ -2926,7 +2926,6 @@ mod postgres_tests { /// runs to completion through the executor: the target's rows in the added /// tables are purged and verified and a bystander's survive. A table added /// after approval that is not listed still stops the request before fencing. - /// A retiring table dropped after approval does not stop it. async fn approval_before_an_expand_migration_completes() { let redis_url = std::env::var("BUZZ_TEST_REDIS_URL") .or_else(|_| std::env::var("REDIS_URL")) @@ -3056,50 +3055,6 @@ mod postgres_tests { .expect("load request"); assert!(request.fence_generation.is_none()); - // A retiring table the approval froze may be dropped before execution. - // The request is inventoried and approved while `delivery_log` and - // `subscriptions` exist, then the contract migration drops them, and - // the executor still advances through the Approved stage on the - // original digest. - let (db, services, claim) = - claimed_test_deletion_in(scratch.clone(), "deletion-retired").await; - let services = services_with_infra(services); - let request_id = claim.request.id; - let approved_digest = claim - .request - .inventory_digest - .clone() - .expect("approval froze an inventory digest"); - let frozen = validate_frozen_inventory(&claim.request).expect("frozen inventory"); - for table in buzz_db::deletion::RETIRING_SCOPED_TABLES { - assert!( - frozen - .schema - .scoped_tables - .iter() - .any(|t| t.as_str() == *table), - "approval froze {table}" - ); - sqlx::query(sqlx::AssertSqlSafe(format!("DROP TABLE {table}"))) - .execute(db.pool()) - .await - .expect("drop retiring table"); - } - let output = execute_claim(&services, LoopMode::Run, claim, &CancellationToken::new()) - .await - .expect("execute deletion"); - assert_eq!( - output.stage, - DeletionStage::RetentionPending, - "{:?}", - output.blocked_reason.or(output.last_error) - ); - let request = db - .deletion_store() - .get(request_id) - .await - .expect("load request"); - assert_eq!(request.inventory_digest.as_deref(), Some(&*approved_digest)); drop_scratch_test_db(scratch, &scratch_name).await; } diff --git a/docs/database.md b/docs/database.md index 3fe2271714c..12a8fbdbf6f 100644 --- a/docs/database.md +++ b/docs/database.md @@ -16,7 +16,7 @@ PostgreSQL stores data. The application owns behavior. | Concern | Today | Target | |---|---|---| | Schema source of truth | Two parallel sources: ordered sqlx migrations in `migrations/` and the desired-state manifest in `schema/` | The declarative desired state in `schema/tables/public/` is the source of truth. Deployments that apply schema out of band plan each change from it, with the tool of their choice. `migrations/` stays, because auto-migration stays supported (next row). Each app owns its own migrations and declarative schema: the relay's copies of the push gateway's tables are debt to remove (Rule 4). | -| Who applies DDL | Startup migrations when `BUZZ_AUTO_MIGRATE` is on (binary default off, Helm chart default on), `buzz-admin migrate`, the push gateway's pre-upgrade Helm Job, and partition creation at relay startup and on a schedule | Both modes stay supported. Deployments at scale, including Block's hosted deployment, apply schema changes out of band through a reviewed workflow before deploying, and their serving relay runs no DDL. Smaller and self-hosted deployments MAY keep auto-migration on. Still open: how the two modes share one schema source, how auto-migration orders a release whose expand, backfill, and contract steps arrive in one upgrade, and how an operator recovers after a contract migration fails at boot (Rule 5). Monthly partition creation is planned to move out of the relay. Changes to partitioned tables (`events`, `delivery_log`) are outside the out-of-band envelope (Rule 6): attaching a partition to a live parent and building an index on a partitioned parent need their own reviewed procedure. | +| Who applies DDL | Startup migrations when `BUZZ_AUTO_MIGRATE` is on (binary default off, Helm chart default on), `buzz-admin migrate`, the push gateway's pre-upgrade Helm Job, and partition creation at relay startup and on a schedule | Both modes stay supported. Deployments at scale, including Block's hosted deployment, apply schema changes out of band through a reviewed workflow before deploying, and their serving relay runs no DDL. Smaller and self-hosted deployments MAY keep auto-migration on. Still open: how the two modes share one schema source, how auto-migration orders a release whose expand, backfill, and contract steps arrive in one upgrade, and how an operator recovers after a contract migration fails at boot (Rule 5). Monthly partition creation is planned to move out of the relay. Changes to the partitioned `events` table are outside the out-of-band envelope (Rule 6): attaching a partition to a live parent and building an index on a partitioned parent need their own reviewed procedure. | | Integrity between tables | None in the database (migrations `0102`-`0104` dropped the last foreign keys) | None in the database. The owning application transaction checks references and performs deletes explicitly. | | Guards and follow-up writes | Triggers and PL/pgSQL functions (`schema/functions/`, `schema/triggers/`) | None in the database. Guards run in the owning writer's transaction; follow-up work is recorded in the same transaction and processed as durable, retryable application work. | | Data repair | Some historical repair embedded in migrations | Backfill definitions in application code, run by the durable framework in [data-backfills.md](data-backfills.md). | @@ -150,16 +150,31 @@ on the list is not covered by an older approval, even when it is in #### Retiring a tenant-owned table -Before a contract migration drops a table with a `community_id` column, ship a -release that removes every reader and writer of it and moves it from -`EXPECTED_SCOPED_TABLES` and `PURGE_SCOPED_TABLES` to -`RETIRING_SCOPED_TABLES` (`crates/buzz-db/src/store/deletion.rs`), and deploy it -to every relay, deletion executor and operator CLI. The catalog then accepts -the table present or absent, the purge deletes its rows only while it exists, -and an approval that froze it still executes after the drop -(`validate_approved_schema` tolerates a frozen `RETIRING_SCOPED_TABLES` entry -that is gone, and nothing else). Run the drop migration after that release -is everywhere, and remove the entry once no pre-drop approval remains. +Retiring takes two releases, each deployed to every relay, deletion executor +and operator CLI before the next starts. + +1. **Code removal.** Remove every reader and writer of the table, and move it + from `EXPECTED_SCOPED_TABLES` and `PURGE_SCOPED_TABLES` + (`crates/buzz-db/src/store/deletion.rs`) to a retiring list. The catalog, + the purge and verification treat that list as they treat + `PENDING_SCOPED_TABLES`: each table is accepted present or absent, its rows + are deleted and verified only while it exists, and it is purged ahead of + `PURGE_SCOPED_TABLES`. Community deletion then works on either side of the + drop, in a mixed fleet and after a rollback to this release. The list + (`RETIRING_SCOPED_TABLES`) exists only between the two releases: the + code-removal PR adds it and the drop PR removes it. +2. **Drop migration.** Ship the drop with its schema removal (Rule 4). In the + same PR, remove the table from the retiring list and add it to + `DROPPED_SCOPED_TABLES`. The catalog is again an exact set: a live table + that no list names is unknown and blocks deletion. Deployments apply + migrations before code, so no database has the table at this version. + `DROPPED_SCOPED_TABLES` has one use: a request approved before the drop + froze an inventory that lists the table, and `validate_approved_schema` + (`crates/buzz-deletion/src/lib.rs`) accepts that it is gone, and nothing + else. Remove the entry once no approval from before the drop can remain. + +Migration `0105` dropped `delivery_log` and `subscriptions` this way, after +#9746 removed their code. #### Checklist: adding a provenance-only table @@ -432,7 +447,8 @@ which the parent's drop already removed (`42704`). A deployment that applies `schema/` with pgschema applies the dropping migration first, under that migration's lock budgets, then runs pgschema. For the trigger drops see [trigger-retirement-deployment.md](trigger-retirement-deployment.md); for the -foreign keys on `events` and `delivery_log`, apply `0104`. +foreign keys on `events` and, before `0105` dropped it, `delivery_log`, apply +`0104`. ### 6. Bound every lock and statement diff --git a/docs/trigger-retirement-deployment.md b/docs/trigger-retirement-deployment.md index 569fafa7bc0..1c441007eba 100644 --- a/docs/trigger-retirement-deployment.md +++ b/docs/trigger-retirement-deployment.md @@ -64,8 +64,9 @@ are still serving: A deployment that applies `schema/` with pgschema follows the same order. Apply the migrations first, or first drop the triggers on the partitioned parents: `events_created_at_floor`, `community_write_fence_events` and -`trg_events_guard_channel_roster_snapshot` on `events`, and -`community_write_fence_delivery_log` on `delivery_log`. +`trg_events_guard_channel_roster_snapshot` on `events`, and, while the table +still exists (migration 0105 drops it), `community_write_fence_delivery_log` on +`delivery_log`. Otherwise pgschema plans the partition copies' drops before the parent's, and PostgreSQL refuses with `2BP01`. diff --git a/migrations/0106_drop_delivery_tables.sql b/migrations/0106_drop_delivery_tables.sql new file mode 100644 index 00000000000..b6fbb7c1ba1 --- /dev/null +++ b/migrations/0106_drop_delivery_tables.sql @@ -0,0 +1,39 @@ +-- Contract step (docs/database.md Rule 5 and "Retiring a tenant-owned table"): +-- drop the unused delivery_log and subscriptions tables and the three enum +-- types only they used (delivery_method, subscription_status, pause_reason). +-- The initial schema created them for a delivery feature that was never built. +-- +-- Why this is safe: +-- * No code reads or writes either table. The release that removed every +-- reader, writer, partition-manager entry and deletion selection (#9746) +-- is the required stop: run a relay, deletion executor and operator CLI +-- build with it, or later, everywhere before this migration. A build +-- older than it still selects from these tables during community deletion +-- and user deletion, and community deletion fails its table catalog check +-- once they are gone. +-- * No foreign key references or starts at either table: 0102 and 0103 +-- dropped the subscriptions keys, 0104 the delivery_log key, and the +-- delivery_log to subscriptions link was never a database constraint. +-- * Nothing ever wrote a row, so there is no data to repair first and no +-- backfill to wait for. Dropping a table does not scan it, so the drop +-- takes the same time however many rows an operator's copy holds. +-- * No other object depends on the tables or the types. The drops use +-- neither CASCADE nor a row check: an unexpected dependent fails the +-- migration instead of being dropped with the table. +-- +-- Dropping the partitioned delivery_log drops its partitions, including any +-- dated monthly the relay's partition manager created at runtime before +-- #9746. Each drop takes ACCESS EXCLUSIVE on the table and, for delivery_log, +-- on every partition. The budgets end the attempt before the 1s +-- deadlock_timeout, so this transaction fails instead of queueing behind a +-- query. Retry on failure. Deployments that apply schema out of band apply +-- this file in its own transaction. +SET LOCAL lock_timeout = '300ms'; +SET LOCAL statement_timeout = '800ms'; + +DROP TABLE IF EXISTS delivery_log; +DROP TABLE IF EXISTS subscriptions; + +DROP TYPE IF EXISTS delivery_method; +DROP TYPE IF EXISTS subscription_status; +DROP TYPE IF EXISTS pause_reason; diff --git a/schema/partitions/delivery_log.sql b/schema/partitions/delivery_log.sql deleted file mode 100644 index f37c086585b..00000000000 --- a/schema/partitions/delivery_log.sql +++ /dev/null @@ -1,16 +0,0 @@ --- The static layout migrations/0001 creates. The relay's partition manager --- (crates/buzz-db/src/store/partition/) adds later monthlies at runtime; --- .pgschemaignore hides those from pgschema and must exempt every dated --- monthly declared here. -CREATE TABLE delivery_log_p_past PARTITION OF delivery_log - FOR VALUES FROM (MINVALUE) TO ('2026-03-01'); -CREATE TABLE delivery_log_p2026_03 PARTITION OF delivery_log - FOR VALUES FROM ('2026-03-01') TO ('2026-04-01'); -CREATE TABLE delivery_log_p2026_04 PARTITION OF delivery_log - FOR VALUES FROM ('2026-04-01') TO ('2026-05-01'); -CREATE TABLE delivery_log_p2026_05 PARTITION OF delivery_log - FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); -CREATE TABLE delivery_log_p2026_06 PARTITION OF delivery_log - FOR VALUES FROM ('2026-06-01') TO ('2026-07-01'); -CREATE TABLE delivery_log_p_future PARTITION OF delivery_log - FOR VALUES FROM ('2026-07-01') TO (MAXVALUE); diff --git a/schema/schema.sql b/schema/schema.sql index e8e651167f5..4e6a6ca84bb 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -56,9 +56,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i types/workflow_status.sql \i types/run_status.sql \i types/approval_status.sql -\i types/delivery_method.sql -\i types/subscription_status.sql -\i types/pause_reason.sql \i types/channel_add_policy.sql -- functions @@ -72,8 +69,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i tables/public/personal_read_frontiers.sql \i tables/public/events.sql \i tables/public/event_mentions.sql -\i tables/public/subscriptions.sql -\i tables/public/delivery_log.sql \i tables/public/workflows.sql \i tables/public/workflow_runs.sql \i tables/public/workflow_approvals.sql @@ -129,7 +124,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; -- partitions \i partitions/events.sql -\i partitions/delivery_log.sql -- triggers diff --git a/schema/tables/public/delivery_log.sql b/schema/tables/public/delivery_log.sql deleted file mode 100644 index b3afa31e03f..00000000000 --- a/schema/tables/public/delivery_log.sql +++ /dev/null @@ -1,19 +0,0 @@ --- ── Delivery log (partitioned by month on delivered_at) ────────────────────── --- Conformance: subscription delivery audit. community_id carried for tenant --- attribution; child of subscriptions. - -CREATE TABLE delivery_log ( - community_id UUID NOT NULL, - id BIGINT GENERATED ALWAYS AS IDENTITY, - subscription_id VARCHAR(255), - event_id BYTEA, - method delivery_method, - delivered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - success BOOLEAN, - http_status INT, - error_message TEXT, - attempt_number INT DEFAULT 1, - PRIMARY KEY (delivered_at, id) -) PARTITION BY RANGE (delivered_at); - -CREATE INDEX idx_delivery_log_community_sub ON delivery_log (community_id, subscription_id); diff --git a/schema/tables/public/subscriptions.sql b/schema/tables/public/subscriptions.sql deleted file mode 100644 index b57a2b0a507..00000000000 --- a/schema/tables/public/subscriptions.sql +++ /dev/null @@ -1,22 +0,0 @@ --- ── Subscriptions ───────────────────────────────────────────────────────────── --- Conformance: "Mesh, agents, ACP/MCP, and CLI" (persisted subscriptions). - -CREATE TABLE subscriptions ( - community_id UUID NOT NULL, - id VARCHAR(255) NOT NULL, - owner_pubkey BYTEA NOT NULL, - filter_kinds JSONB, - filter_authors JSONB, - filter_channel_ids JSONB, - filter_since TIMESTAMPTZ, - filter_until TIMESTAMPTZ, - delivery_method delivery_method NOT NULL DEFAULT 'webhook', - delivery_url TEXT, - status subscription_status NOT NULL DEFAULT 'active', - pause_reason pause_reason, - delivered_count BIGINT NOT NULL DEFAULT 0, - error_count BIGINT NOT NULL DEFAULT 0, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (community_id, id) -); diff --git a/schema/types/delivery_method.sql b/schema/types/delivery_method.sql deleted file mode 100644 index b35c62e71c5..00000000000 --- a/schema/types/delivery_method.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE TYPE delivery_method AS ENUM ('webhook', 'websocket'); diff --git a/schema/types/pause_reason.sql b/schema/types/pause_reason.sql deleted file mode 100644 index 7517da078ce..00000000000 --- a/schema/types/pause_reason.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE TYPE pause_reason AS ENUM ('user', 'system', 'rate_limit'); diff --git a/schema/types/subscription_status.sql b/schema/types/subscription_status.sql deleted file mode 100644 index c447f20d9b0..00000000000 --- a/schema/types/subscription_status.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE TYPE subscription_status AS ENUM ('active', 'paused', 'deleted'); diff --git a/scripts/drop-partitioned-foreign-keys.sql b/scripts/drop-partitioned-foreign-keys.sql index 677850a4b97..840468eabdf 100644 --- a/scripts/drop-partitioned-foreign-keys.sql +++ b/scripts/drop-partitioned-foreign-keys.sql @@ -5,6 +5,11 @@ -- drop already removed (SQLSTATE 42704). This file runs migration 0104's drop -- for a database that pgschema brings up to date instead. -- +-- Migration 0105 dropped delivery_log and the schema no longer declares it, so +-- a fresh database, or one migrated through 0105, has only events. A reused +-- database from before the drop may still have delivery_log; its key is +-- dropped too, only while the table exists. +-- -- For the test launchers only: scripts/start-relay-for-tests.sh, which reuses -- its database, and the populated-upgrade test run it before apply. -- Deployments apply migration 0104 instead (docs/database.md, "Retiring a @@ -23,8 +28,13 @@ BEGIN IF to_regclass('events') IS NULL THEN RETURN; END IF; - LOCK TABLE events, delivery_log, communities IN ACCESS EXCLUSIVE MODE; - ALTER TABLE events DROP CONSTRAINT IF EXISTS events_community_id_fkey; - ALTER TABLE delivery_log DROP CONSTRAINT IF EXISTS delivery_log_community_id_fkey; + IF to_regclass('delivery_log') IS NOT NULL THEN + LOCK TABLE events, delivery_log, communities IN ACCESS EXCLUSIVE MODE; + ALTER TABLE events DROP CONSTRAINT IF EXISTS events_community_id_fkey; + ALTER TABLE delivery_log DROP CONSTRAINT IF EXISTS delivery_log_community_id_fkey; + ELSE + LOCK TABLE events, communities IN ACCESS EXCLUSIVE MODE; + ALTER TABLE events DROP CONSTRAINT IF EXISTS events_community_id_fkey; + END IF; END $$; COMMIT; diff --git a/scripts/reconcile-schema-after-pgschema.sql b/scripts/reconcile-schema-after-pgschema.sql index cf0ed20fe25..0d0239c81c0 100644 --- a/scripts/reconcile-schema-after-pgschema.sql +++ b/scripts/reconcile-schema-after-pgschema.sql @@ -79,73 +79,6 @@ BEGIN ALTER TABLE events ATTACH PARTITION events_p_future FOR VALUES FROM ('2026-07-01') TO (MAXVALUE); END IF; - - -- When pgschema creates partition children as standalone tables, it also - -- preserves the parent's identity column on delivery_log children. PostgreSQL - -- rejects attaching a child table that has its own identity column, so each - -- delivery_log attach path drops that standalone identity first. Raw - -- schema-created partitions are already attached, so these branches do not - -- run against inherited partition columns. - - IF NOT EXISTS ( - SELECT 1 FROM pg_inherits - WHERE inhparent = 'delivery_log'::regclass - AND inhrelid = 'delivery_log_p_past'::regclass - ) THEN - ALTER TABLE delivery_log_p_past ALTER COLUMN id DROP IDENTITY IF EXISTS; - ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p_past - FOR VALUES FROM (MINVALUE) TO ('2026-03-01'); - END IF; - - IF NOT EXISTS ( - SELECT 1 FROM pg_inherits - WHERE inhparent = 'delivery_log'::regclass - AND inhrelid = 'delivery_log_p2026_03'::regclass - ) THEN - ALTER TABLE delivery_log_p2026_03 ALTER COLUMN id DROP IDENTITY IF EXISTS; - ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_03 - FOR VALUES FROM ('2026-03-01') TO ('2026-04-01'); - END IF; - - IF NOT EXISTS ( - SELECT 1 FROM pg_inherits - WHERE inhparent = 'delivery_log'::regclass - AND inhrelid = 'delivery_log_p2026_04'::regclass - ) THEN - ALTER TABLE delivery_log_p2026_04 ALTER COLUMN id DROP IDENTITY IF EXISTS; - ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_04 - FOR VALUES FROM ('2026-04-01') TO ('2026-05-01'); - END IF; - - IF NOT EXISTS ( - SELECT 1 FROM pg_inherits - WHERE inhparent = 'delivery_log'::regclass - AND inhrelid = 'delivery_log_p2026_05'::regclass - ) THEN - ALTER TABLE delivery_log_p2026_05 ALTER COLUMN id DROP IDENTITY IF EXISTS; - ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_05 - FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); - END IF; - - IF NOT EXISTS ( - SELECT 1 FROM pg_inherits - WHERE inhparent = 'delivery_log'::regclass - AND inhrelid = 'delivery_log_p2026_06'::regclass - ) THEN - ALTER TABLE delivery_log_p2026_06 ALTER COLUMN id DROP IDENTITY IF EXISTS; - ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_06 - FOR VALUES FROM ('2026-06-01') TO ('2026-07-01'); - END IF; - - IF NOT EXISTS ( - SELECT 1 FROM pg_inherits - WHERE inhparent = 'delivery_log'::regclass - AND inhrelid = 'delivery_log_p_future'::regclass - ) THEN - ALTER TABLE delivery_log_p_future ALTER COLUMN id DROP IDENTITY IF EXISTS; - ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p_future - FOR VALUES FROM ('2026-07-01') TO (MAXVALUE); - END IF; END $$; -- pgschema moves the partition key to the front of a partitioned table's @@ -155,8 +88,8 @@ END $$; -- events_pkey and each declared child's key, which fails once the children are -- attached because their keys are inherited. Rebuild the key on the parent in -- the declared order; PostgreSQL recreates each partition's key with it. --- delivery_log already declares its partition key first. This block is a --- verbatim copy of scripts/repair-events-pkey.sql; keep the two identical. +-- This block is a verbatim copy of scripts/repair-events-pkey.sql; keep the two +-- identical. DO $$ DECLARE declared CONSTANT text := 'PRIMARY KEY (community_id, created_at, id)'; From 861ca3880355d63b378d0658bbd908cf718659e9 Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Thu, 19 Nov 2026 22:42:12 -0500 Subject: [PATCH 2/7] Drop delivery tables before pgschema in the upgrade fixture pgschema drops the fence function before the tables whose triggers still use it. A deployment applies 0105 first, so the fixture does too. Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Luke Tornquist --- .../relay_invite/upgrade_postgres_tests.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs index ae33ae0ab2d..19589dbf60c 100644 --- a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs @@ -418,12 +418,15 @@ async fn assert_admission_column(pool: &PgPool) { } async fn apply_pgschema_to_existing_database(pool: &PgPool) { - // The pinned migration history has retired triggers on partitioned - // parents (events, delivery_log), including the floor trigger 0089 and - // the roster trigger 0095 drop, and auto-named deletion-request checks - // that the desired schema replaces. pgschema orders child-trigger drops - // before their parent (Postgres refuses with 2BP01) and schedules a - // replacement check before dropping its same-named copy. + // The pinned migration history has retired triggers on the partitioned + // events parent, including the floor trigger 0089 and the roster trigger + // 0095 drop, and auto-named deletion-request checks that the desired + // schema replaces. pgschema orders child-trigger drops before their + // parent (Postgres refuses with 2BP01) and schedules a replacement check + // before dropping its same-named copy. It also drops the fence function + // before the delivery tables whose triggers still use it, so drop those + // tables first, as a deployment applies migration 0105 before pgschema + // (docs/database.md Rule 5). // Remove only those stale objects in this disposable fixture; pgschema // still applies desired state; historical repair is a separate reviewed // operation after deployment. @@ -435,7 +438,7 @@ async fn apply_pgschema_to_existing_database(pool: &PgPool) { DROP TRIGGER IF EXISTS events_created_at_floor ON events; \ DROP TRIGGER IF EXISTS community_write_fence_events ON events; \ DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events; \ - DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log; \ + DROP TABLE IF EXISTS delivery_log, subscriptions; \ ALTER TABLE community_deletion_requests \ DROP CONSTRAINT IF EXISTS community_deletion_requests_check1; \ ALTER TABLE community_deletion_requests \ From 96e521763657bf141e0e85311a1d8543cf836b1d Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Thu, 19 Nov 2026 22:47:39 -0500 Subject: [PATCH 3/7] Address review: pre-0105 approval, populated drop, launcher order - Restore the executor check that an approval frozen with the dropped tables still reaches RetentionPending on its original digest. - Test that 0105 drops populated tables, and state the discard decision. - Apply 0105 before pgschema in start-relay-for-tests.sh. - docs: run the rollback build with auto-migration off after the drop. Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Luke Tornquist --- crates/buzz-db/src/runtime/migration.rs | 37 ++++++++++++++ crates/buzz-deletion/src/lib.rs | 63 ++++++++++++++++++++++-- docs/database.md | 3 ++ migrations/0106_drop_delivery_tables.sql | 8 +-- scripts/start-relay-for-tests.sh | 4 ++ 5 files changed, 108 insertions(+), 7 deletions(-) diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 8e1fdade636..095d104dc24 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -4323,6 +4323,43 @@ mod postgres_tests { .expect("deletion must accept the catalog after the drop"); } + /// Migration 0105 discards any rows in the delivery tables. No Buzz + /// release ever wrote them, but an operator copy (for example one made by + /// the legacy cutover script) may hold rows. The drop must not depend on + /// the tables being empty. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_0105_drops_populated_delivery_tables() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + MIGRATOR + .run_to(104, &pool) + .await + .expect("apply migrations through 0104"); + let community = uuid::Uuid::new_v4(); + for statement in [ + "INSERT INTO subscriptions (community_id, id, owner_pubkey) \ + VALUES ($1, 'legacy', decode(repeat('51', 32), 'hex'))", + "INSERT INTO delivery_log (community_id, subscription_id) VALUES ($1, 'legacy')", + ] { + sqlx::query(statement) + .bind(community) + .execute(&pool) + .await + .expect("seed delivery table"); + } + run_migrations(&pool).await.expect("apply 0105"); + let present: (bool, bool, bool) = sqlx::query_as( + "SELECT to_regclass('delivery_log') IS NOT NULL, \ + to_regclass('subscriptions') IS NOT NULL, \ + to_regtype('delivery_method') IS NOT NULL", + ) + .fetch_one(&pool) + .await + .expect("look up dropped objects"); + assert_eq!(present, (false, false, false)); + } + /// Verify migration 0044 applies cleanly against a DB that has rows in /// the NIP-FI 0041+0042 tables. The immutability guards (no_delete, /// no_truncate) are enforced via triggers; DROP TABLE bypasses them and diff --git a/crates/buzz-deletion/src/lib.rs b/crates/buzz-deletion/src/lib.rs index f074edea61c..2d56e2aaf71 100644 --- a/crates/buzz-deletion/src/lib.rs +++ b/crates/buzz-deletion/src/lib.rs @@ -2026,6 +2026,16 @@ mod postgres_tests { } async fn claimed_test_deletion_in(db: Db, prefix: &str) -> (Db, Services, ClaimedDeletion) { + claimed_test_deletion_freezing(db, prefix, &[]).await + } + + /// Like [`claimed_test_deletion_in`], but the frozen schema manifest also + /// lists `extra_tables`, as an approval made by an older binary would. + async fn claimed_test_deletion_freezing( + db: Db, + prefix: &str, + extra_tables: &[&str], + ) -> (Db, Services, ClaimedDeletion) { let store = db.deletion_store(); let host = format!("{prefix}-{}.example", Uuid::new_v4().simple()); let community = db @@ -2036,11 +2046,16 @@ mod postgres_tests { .submit(Some(&host), "test", None, None) .await .expect("submit deletion request"); + let mut schema = store + .inventory_schema(community.id) + .await + .expect("inventory schema"); + schema + .scoped_tables + .extend(extra_tables.iter().map(|table| (*table).to_owned())); + schema.scoped_tables.sort(); let inventory = FrozenInventory { - schema: store - .inventory_schema(community.id) - .await - .expect("inventory schema"), + schema, storage: empty_storage_manifest(community.id), }; store @@ -2926,6 +2941,7 @@ mod postgres_tests { /// runs to completion through the executor: the target's rows in the added /// tables are purged and verified and a bystander's survive. A table added /// after approval that is not listed still stops the request before fencing. + /// An approval from before migration 0105 still executes after it. async fn approval_before_an_expand_migration_completes() { let redis_url = std::env::var("BUZZ_TEST_REDIS_URL") .or_else(|_| std::env::var("REDIS_URL")) @@ -3055,6 +3071,45 @@ mod postgres_tests { .expect("load request"); assert!(request.fence_generation.is_none()); + // An approval from before migration 0105 froze `delivery_log` and + // `subscriptions`, which are gone now. The executor still advances + // through the Approved stage on the original digest. + let (db, services, claim) = claimed_test_deletion_freezing( + scratch.clone(), + "deletion-dropped", + buzz_db::deletion::DROPPED_SCOPED_TABLES, + ) + .await; + let services = services_with_infra(services); + let request_id = claim.request.id; + let approved_digest = claim + .request + .inventory_digest + .clone() + .expect("approval froze an inventory digest"); + let frozen = validate_frozen_inventory(&claim.request).expect("frozen inventory"); + for table in buzz_db::deletion::DROPPED_SCOPED_TABLES { + assert!( + frozen.schema.scoped_tables.iter().any(|t| t == table), + "approval froze {table}" + ); + } + let output = execute_claim(&services, LoopMode::Run, claim, &CancellationToken::new()) + .await + .expect("execute deletion"); + assert_eq!( + output.stage, + DeletionStage::RetentionPending, + "{:?}", + output.blocked_reason.or(output.last_error) + ); + let request = db + .deletion_store() + .get(request_id) + .await + .expect("load request"); + assert_eq!(request.inventory_digest.as_deref(), Some(&*approved_digest)); + drop_scratch_test_db(scratch, &scratch_name).await; } diff --git a/docs/database.md b/docs/database.md index 12a8fbdbf6f..58449e5dfb8 100644 --- a/docs/database.md +++ b/docs/database.md @@ -172,6 +172,9 @@ and operator CLI before the next starts. froze an inventory that lists the table, and `validate_approved_schema` (`crates/buzz-deletion/src/lib.rs`) accepts that it is gone, and nothing else. Remove the entry once no approval from before the drop can remain. + The code-removal release is the required stop and the rollback target. It + does not know the drop migration's version, so run it with auto-migration + off once the drop has applied. Migration `0105` dropped `delivery_log` and `subscriptions` this way, after #9746 removed their code. diff --git a/migrations/0106_drop_delivery_tables.sql b/migrations/0106_drop_delivery_tables.sql index b6fbb7c1ba1..a40f8a3fe56 100644 --- a/migrations/0106_drop_delivery_tables.sql +++ b/migrations/0106_drop_delivery_tables.sql @@ -14,9 +14,11 @@ -- * No foreign key references or starts at either table: 0102 and 0103 -- dropped the subscriptions keys, 0104 the delivery_log key, and the -- delivery_log to subscriptions link was never a database constraint. --- * Nothing ever wrote a row, so there is no data to repair first and no --- backfill to wait for. Dropping a table does not scan it, so the drop --- takes the same time however many rows an operator's copy holds. +-- * No Buzz release ever wrote a row, so there is no data to repair first +-- and no backfill to wait for. Any rows an operator copied in, for example +-- with scripts/cutover/1321_backfill_default_community.sql, have no +-- reader and are discarded with the table. Dropping a table does not scan +-- it, so the drop takes the same time however many rows it holds. -- * No other object depends on the tables or the types. The drops use -- neither CASCADE nor a row check: an unexpected dependent fails the -- migration instead of being dropped with the table. diff --git a/scripts/start-relay-for-tests.sh b/scripts/start-relay-for-tests.sh index ee3f0bbd6b4..852b9b66ec6 100755 --- a/scripts/start-relay-for-tests.sh +++ b/scripts/start-relay-for-tests.sh @@ -110,6 +110,10 @@ docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ # pgschema cannot drop the partitioned tables' foreign keys (see the script). docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 < scripts/drop-partitioned-foreign-keys.sql +# Apply the table-dropping migration first, as deployments do: pgschema drops +# the fence function before the tables whose triggers still use it. +docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ + psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 -1 < migrations/0105_drop_delivery_tables.sql ./bin/pgschema apply --file schema/schema.sql --auto-approve docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 < scripts/reconcile-schema-after-pgschema.sql From c1ed32170e7b8bbbdba0762b2ffc8d48d1aeee52 Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Thu, 19 Nov 2026 22:54:14 -0500 Subject: [PATCH 4/7] Pass 0105 to psql with -f in the test launcher; note the row discard Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Luke Tornquist --- docs/database.md | 4 +++- scripts/start-relay-for-tests.sh | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/database.md b/docs/database.md index 58449e5dfb8..16efb91de4c 100644 --- a/docs/database.md +++ b/docs/database.md @@ -177,7 +177,9 @@ and operator CLI before the next starts. off once the drop has applied. Migration `0105` dropped `delivery_log` and `subscriptions` this way, after -#9746 removed their code. +#9746 removed their code. It discards any rows in them, including rows the +legacy cutover script copied in; export those before `0105` if you need them. +Deployments that apply `schema/` with pgschema apply `0105` first. #### Checklist: adding a provenance-only table diff --git a/scripts/start-relay-for-tests.sh b/scripts/start-relay-for-tests.sh index 852b9b66ec6..769713e4dce 100755 --- a/scripts/start-relay-for-tests.sh +++ b/scripts/start-relay-for-tests.sh @@ -113,7 +113,7 @@ docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ # Apply the table-dropping migration first, as deployments do: pgschema drops # the fence function before the tables whose triggers still use it. docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ - psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 -1 < migrations/0105_drop_delivery_tables.sql + psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 -1 -f - < migrations/0105_drop_delivery_tables.sql ./bin/pgschema apply --file schema/schema.sql --auto-approve docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 < scripts/reconcile-schema-after-pgschema.sql From 365c1645e67a6e5e5f1c678bd123477b1fae7592 Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Fri, 20 Nov 2026 13:36:13 -0500 Subject: [PATCH 5/7] Name the 0105 required stop in the chart upgrade docs Also check all three dropped types in the populated 0105 test. Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Luke Tornquist --- crates/buzz-db/src/runtime/migration.rs | 8 +++++--- deploy/charts/buzz/README.md | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 095d104dc24..4edd1228d9a 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -4349,15 +4349,17 @@ mod postgres_tests { .expect("seed delivery table"); } run_migrations(&pool).await.expect("apply 0105"); - let present: (bool, bool, bool) = sqlx::query_as( + let present: (bool, bool, bool, bool, bool) = sqlx::query_as( "SELECT to_regclass('delivery_log') IS NOT NULL, \ to_regclass('subscriptions') IS NOT NULL, \ - to_regtype('delivery_method') IS NOT NULL", + to_regtype('delivery_method') IS NOT NULL, \ + to_regtype('subscription_status') IS NOT NULL, \ + to_regtype('pause_reason') IS NOT NULL", ) .fetch_one(&pool) .await .expect("look up dropped objects"); - assert_eq!(present, (false, false, false)); + assert_eq!(present, (false, false, false, false, false)); } /// Verify migration 0044 applies cleanly against a DB that has rows in diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index 380eec84f3f..88206c760a4 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -631,12 +631,14 @@ default so long-lived WebSocket connections have time to drain. ## Upgrades -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. +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 stops below, `helm upgrade` is the entire upgrade procedure. **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. **Required stop before migration 0100.** Migrations 0098–0100 undo migration 0097, and 0100 drops the columns and indexes that 0097 added. No tagged relay release reads them. Only rolling images built from commit `eebf62b6` (#9650) up to, but not including, `a4061916` (#9689) do. Their channel artifact reads and writes fail once 0100 runs. If any relay pod, job or rollback target runs one of those images, move all of them to `sha-a406191` or later before you upgrade. To roll back after 0100 has run, set `migrate.autoMigrate=false` first, because an older binary with auto-migration on refuses a database that has migrations it does not know. Then roll back to `sha-a406191` or later, never to an image in that range. Migration 0098 refuses a database whose `artifact_heads` primary key is not `(community_id, artifact_id)`. Recover such a database as #9689 describes before upgrading. +**Required stop before migration 0105.** Migration 0105 drops the unused `delivery_log` and `subscriptions` tables. Builds before commit `7e94503f` (#9746), including `relay-v0.3.0`, still use them: community deletion fails its catalog check, user deletion fails, and startup partition maintenance logs errors. No data is lost. Before you upgrade to a build that contains 0105, move every relay pod, job and rollback target to `sha-7e94503` or later, or to the first tagged relay release that contains #9746. To roll back after 0105 has run, set `migrate.autoMigrate=false` first, then roll back to that build or later. + Apply migrations before rolling the relay; for large installations, prefer a controlled `buzz-admin migrate` job with PostgreSQL lock monitoring before the code rollout. If you prefer decoupling migrations from serving, set `migrate.autoMigrate=false`. **In that mode the chart does not run migrations for you** — you own running `buzz-admin migrate` (separate Pod / one-shot Job) against the database before every `helm install` / `helm upgrade`. Readiness probes only verify DB connectivity, not schema freshness, so a pod will appear healthy against an unmigrated schema and fail under load. A pre-upgrade Helm Job for this is on the chart roadmap; the values knob `migrate.preUpgradeJob.enabled` is reserved. From bbaaaf3d26c6cf240f58574f074d3b0b9f5dafcc Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Fri, 20 Nov 2026 14:41:52 -0500 Subject: [PATCH 6/7] Renumber the delivery table drop to migration 0106 Main took 0105 for the push gateway in-flight column (#9802). The drop moves to 0106. Every reference, the count test and the chart README required stop now name 0106. Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Luke Tornquist --- crates/buzz-db/src/runtime/migration.rs | 16 ++++++++-------- crates/buzz-db/src/store/deletion.rs | 16 ++++++++-------- .../store/relay_invite/upgrade_postgres_tests.rs | 2 +- crates/buzz-deletion/src/lib.rs | 12 ++++++------ deploy/charts/buzz/README.md | 2 +- docs/database.md | 8 ++++---- docs/trigger-retirement-deployment.md | 2 +- scripts/drop-partitioned-foreign-keys.sql | 4 ++-- scripts/start-relay-for-tests.sh | 2 +- 9 files changed, 32 insertions(+), 32 deletions(-) diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 4edd1228d9a..93c97f1f60d 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -1567,7 +1567,7 @@ mod postgres_tests { "media_publications", ]; // 0090 is immutable and also retired the fences on the two tables - // migration 0105 later drops, so list them here. + // migration 0106 later drops, so list them here. let dropped_later = ["delivery_log", "subscriptions"]; for table in crate::deletion::EXPECTED_SCOPED_TABLES .iter() @@ -4200,7 +4200,7 @@ mod postgres_tests { ); } - /// Before migration 0105 the delivery tables are live, and the deletion + /// Before migration 0106 the delivery tables are live, and the deletion /// catalog check refuses exactly them as unknown tenant tables and nothing /// else. Migrations apply before code, so no deployment runs this binary /// against such a catalog. Asserting the whole drift keeps the check as @@ -4209,7 +4209,7 @@ mod postgres_tests { let error = store .validate_catalog() .await - .expect_err("deletion refuses the delivery tables before migration 0105"); + .expect_err("deletion refuses the delivery tables before migration 0106"); assert!( error .to_string() @@ -4323,19 +4323,19 @@ mod postgres_tests { .expect("deletion must accept the catalog after the drop"); } - /// Migration 0105 discards any rows in the delivery tables. No Buzz + /// Migration 0106 discards any rows in the delivery tables. No Buzz /// release ever wrote them, but an operator copy (for example one made by /// the legacy cutover script) may hold rows. The drop must not depend on /// the tables being empty. #[tokio::test] #[ignore = "requires Postgres"] - async fn migration_0105_drops_populated_delivery_tables() { + async fn migration_0106_drops_populated_delivery_tables() { let pool = connect_test_pool().await; reset_public_schema(&pool).await; MIGRATOR - .run_to(104, &pool) + .run_to(105, &pool) .await - .expect("apply migrations through 0104"); + .expect("apply migrations through 0105"); let community = uuid::Uuid::new_v4(); for statement in [ "INSERT INTO subscriptions (community_id, id, owner_pubkey) \ @@ -4348,7 +4348,7 @@ mod postgres_tests { .await .expect("seed delivery table"); } - run_migrations(&pool).await.expect("apply 0105"); + run_migrations(&pool).await.expect("apply 0106"); let present: (bool, bool, bool, bool, bool) = sqlx::query_as( "SELECT to_regclass('delivery_log') IS NOT NULL, \ to_regclass('subscriptions') IS NOT NULL, \ diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index c613c8b2c23..21be2ba3e76 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -127,16 +127,16 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "workflows", ]; -/// Tenant tables that migration 0105 dropped, kept only for frozen approvals. +/// Tenant tables that migration 0106 dropped, kept only for frozen approvals. /// /// No database has these tables at this version: deployments apply migrations /// before code, and auto-migration runs before the relay serves. A live table /// with one of these names is an unknown scoped table, so the catalog check /// fails closed and deletion refuses it. The one use is /// `validate_approved_schema` in `buzz-deletion`: a deletion request approved -/// before migration 0105 froze an inventory that lists these tables, and its +/// before migration 0106 froze an inventory that lists these tables, and its /// executor must still accept that they are gone. Remove this list once no -/// approval from before migration 0105 can remain. +/// approval from before migration 0106 can remain. pub const DROPPED_SCOPED_TABLES: &[&str] = &["delivery_log", "subscriptions"]; /// Tenant tables that a later release's expand migration adds. @@ -4832,13 +4832,13 @@ pub(crate) mod postgres_tests { crate::migration::run_migrations_through(&db.pool, 89) .await .expect("migrate with fence objects present"); - // Migration 0105 drops the delivery tables, and the deletion catalog no + // Migration 0106 drops the delivery tables, and the deletion catalog no // longer accepts them as tenant tables. Drop them by hand so the // catalog is the current one; their triggers go with them. sqlx::raw_sql("DROP TABLE delivery_log, subscriptions") .execute(&db.pool) .await - .expect("drop the tables migration 0105 drops"); + .expect("drop the tables migration 0106 drops"); let store = db.deletion_store(); let community = db .ensure_configured_community("optional-fences.example") @@ -4977,13 +4977,13 @@ DROP FUNCTION community_deletion_lock_key(UUID); crate::migration::run_migrations_through(&db.pool, 86) .await .expect("phase-one schema"); - // Migration 0105 drops the delivery tables, and the deletion catalog no + // Migration 0106 drops the delivery tables, and the deletion catalog no // longer accepts them as tenant tables. Drop them by hand so the // catalog is the current one. sqlx::raw_sql("DROP TABLE delivery_log, subscriptions") .execute(&db.pool) .await - .expect("drop the tables migration 0105 drops"); + .expect("drop the tables migration 0106 drops"); let community = db .ensure_configured_community("optional-guards.example") .await @@ -9658,7 +9658,7 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); } } - /// Migration 0105 dropped `delivery_log` and `subscriptions`. A live table + /// Migration 0106 dropped `delivery_log` and `subscriptions`. A live table /// with either name is no longer accepted: it is an unknown tenant table, so /// the catalog check fails closed and deletion refuses to proceed. #[tokio::test] diff --git a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs index 19589dbf60c..0f7a72a305b 100644 --- a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs @@ -425,7 +425,7 @@ async fn apply_pgschema_to_existing_database(pool: &PgPool) { // parent (Postgres refuses with 2BP01) and schedules a replacement check // before dropping its same-named copy. It also drops the fence function // before the delivery tables whose triggers still use it, so drop those - // tables first, as a deployment applies migration 0105 before pgschema + // tables first, as a deployment applies migration 0106 before pgschema // (docs/database.md Rule 5). // Remove only those stale objects in this disposable fixture; pgschema // still applies desired state; historical repair is a separate reviewed diff --git a/crates/buzz-deletion/src/lib.rs b/crates/buzz-deletion/src/lib.rs index 2d56e2aaf71..07966c5836b 100644 --- a/crates/buzz-deletion/src/lib.rs +++ b/crates/buzz-deletion/src/lib.rs @@ -1424,7 +1424,7 @@ fn validate_approved_schema( // The approved catalog binds exactly, with two bounded exceptions. An // expand migration between approval and execution may add a table listed // in APPROVAL_FORWARD_TABLES, which this binary purges and verifies. And an - // approval from before migration 0105 may freeze a table listed in + // approval from before migration 0106 may freeze a table listed in // DROPPED_SCOPED_TABLES, which that migration dropped. The frozen manifest // and its digest are never rewritten. let frozen_tables = frozen @@ -1895,7 +1895,7 @@ mod postgres_tests { assert!(resolve_submit_host(None, Some("not a URL")).is_err()); } - /// An approval from before migration 0105 froze the tables it dropped, and + /// An approval from before migration 0106 froze the tables it dropped, and /// its catalog tolerates exactly those being gone: any other frozen table /// that is gone, or a table live now that the approval did not freeze and /// that is not forward-listed, is still drift. @@ -2598,7 +2598,7 @@ mod postgres_tests { validate_approved_schema(&live, &decoded) .expect("legacy fence list is no longer structural"); - // An approval from before migration 0105 froze the tables it dropped. + // An approval from before migration 0106 froze the tables it dropped. let mut approved_before_drop = decoded.clone(); approved_before_drop.schema.scoped_tables.extend( buzz_db::deletion::DROPPED_SCOPED_TABLES @@ -2606,7 +2606,7 @@ mod postgres_tests { .map(|table| (*table).to_owned()), ); validate_approved_schema(&live, &approved_before_drop) - .expect("a table dropped by migration 0105 is not drift"); + .expect("a table dropped by migration 0106 is not drift"); // Only a listed forward table may appear after approval. A required // table the approval lacks is drift, and so is a removed frozen table. @@ -2941,7 +2941,7 @@ mod postgres_tests { /// runs to completion through the executor: the target's rows in the added /// tables are purged and verified and a bystander's survive. A table added /// after approval that is not listed still stops the request before fencing. - /// An approval from before migration 0105 still executes after it. + /// An approval from before migration 0106 still executes after it. async fn approval_before_an_expand_migration_completes() { let redis_url = std::env::var("BUZZ_TEST_REDIS_URL") .or_else(|_| std::env::var("REDIS_URL")) @@ -3071,7 +3071,7 @@ mod postgres_tests { .expect("load request"); assert!(request.fence_generation.is_none()); - // An approval from before migration 0105 froze `delivery_log` and + // An approval from before migration 0106 froze `delivery_log` and // `subscriptions`, which are gone now. The executor still advances // through the Approved stage on the original digest. let (db, services, claim) = claimed_test_deletion_freezing( diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index 88206c760a4..8b1649598cd 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -637,7 +637,7 @@ Schema migrations are embedded in the relay binary via `sqlx::migrate!` and run **Required stop before migration 0100.** Migrations 0098–0100 undo migration 0097, and 0100 drops the columns and indexes that 0097 added. No tagged relay release reads them. Only rolling images built from commit `eebf62b6` (#9650) up to, but not including, `a4061916` (#9689) do. Their channel artifact reads and writes fail once 0100 runs. If any relay pod, job or rollback target runs one of those images, move all of them to `sha-a406191` or later before you upgrade. To roll back after 0100 has run, set `migrate.autoMigrate=false` first, because an older binary with auto-migration on refuses a database that has migrations it does not know. Then roll back to `sha-a406191` or later, never to an image in that range. Migration 0098 refuses a database whose `artifact_heads` primary key is not `(community_id, artifact_id)`. Recover such a database as #9689 describes before upgrading. -**Required stop before migration 0105.** Migration 0105 drops the unused `delivery_log` and `subscriptions` tables. Builds before commit `7e94503f` (#9746), including `relay-v0.3.0`, still use them: community deletion fails its catalog check, user deletion fails, and startup partition maintenance logs errors. No data is lost. Before you upgrade to a build that contains 0105, move every relay pod, job and rollback target to `sha-7e94503` or later, or to the first tagged relay release that contains #9746. To roll back after 0105 has run, set `migrate.autoMigrate=false` first, then roll back to that build or later. +**Required stop before migration 0106.** Migration 0106 drops the unused `delivery_log` and `subscriptions` tables. Builds before commit `7e94503f` (#9746), including `relay-v0.3.0`, still use them: community deletion fails its catalog check, user deletion fails, and startup partition maintenance logs errors. No data is lost. Before you upgrade to a build that contains 0106, move every relay pod, job and rollback target to `sha-7e94503` or later, or to the first tagged relay release that contains #9746. To roll back after 0106 has run, set `migrate.autoMigrate=false` first, then roll back to that build or later. 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/database.md b/docs/database.md index 16efb91de4c..63ecf244598 100644 --- a/docs/database.md +++ b/docs/database.md @@ -176,10 +176,10 @@ and operator CLI before the next starts. does not know the drop migration's version, so run it with auto-migration off once the drop has applied. -Migration `0105` dropped `delivery_log` and `subscriptions` this way, after +Migration `0106` dropped `delivery_log` and `subscriptions` this way, after #9746 removed their code. It discards any rows in them, including rows the -legacy cutover script copied in; export those before `0105` if you need them. -Deployments that apply `schema/` with pgschema apply `0105` first. +legacy cutover script copied in; export those before `0106` if you need them. +Deployments that apply `schema/` with pgschema apply `0106` first. #### Checklist: adding a provenance-only table @@ -452,7 +452,7 @@ which the parent's drop already removed (`42704`). A deployment that applies `schema/` with pgschema applies the dropping migration first, under that migration's lock budgets, then runs pgschema. For the trigger drops see [trigger-retirement-deployment.md](trigger-retirement-deployment.md); for the -foreign keys on `events` and, before `0105` dropped it, `delivery_log`, apply +foreign keys on `events` and, before `0106` dropped it, `delivery_log`, apply `0104`. ### 6. Bound every lock and statement diff --git a/docs/trigger-retirement-deployment.md b/docs/trigger-retirement-deployment.md index 1c441007eba..960a68caf17 100644 --- a/docs/trigger-retirement-deployment.md +++ b/docs/trigger-retirement-deployment.md @@ -65,7 +65,7 @@ A deployment that applies `schema/` with pgschema follows the same order. Apply the migrations first, or first drop the triggers on the partitioned parents: `events_created_at_floor`, `community_write_fence_events` and `trg_events_guard_channel_roster_snapshot` on `events`, and, while the table -still exists (migration 0105 drops it), `community_write_fence_delivery_log` on +still exists (migration 0106 drops it), `community_write_fence_delivery_log` on `delivery_log`. Otherwise pgschema plans the partition copies' drops before the parent's, and PostgreSQL refuses with `2BP01`. diff --git a/scripts/drop-partitioned-foreign-keys.sql b/scripts/drop-partitioned-foreign-keys.sql index 840468eabdf..9792d75845e 100644 --- a/scripts/drop-partitioned-foreign-keys.sql +++ b/scripts/drop-partitioned-foreign-keys.sql @@ -5,8 +5,8 @@ -- drop already removed (SQLSTATE 42704). This file runs migration 0104's drop -- for a database that pgschema brings up to date instead. -- --- Migration 0105 dropped delivery_log and the schema no longer declares it, so --- a fresh database, or one migrated through 0105, has only events. A reused +-- Migration 0106 dropped delivery_log and the schema no longer declares it, so +-- a fresh database, or one migrated through 0106, has only events. A reused -- database from before the drop may still have delivery_log; its key is -- dropped too, only while the table exists. -- diff --git a/scripts/start-relay-for-tests.sh b/scripts/start-relay-for-tests.sh index 769713e4dce..09f75cd4a0a 100755 --- a/scripts/start-relay-for-tests.sh +++ b/scripts/start-relay-for-tests.sh @@ -113,7 +113,7 @@ docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ # Apply the table-dropping migration first, as deployments do: pgschema drops # the fence function before the tables whose triggers still use it. docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ - psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 -1 -f - < migrations/0105_drop_delivery_tables.sql + psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 -1 -f - < migrations/0106_drop_delivery_tables.sql ./bin/pgschema apply --file schema/schema.sql --auto-approve docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 < scripts/reconcile-schema-after-pgschema.sql From 852660cd86c2163b1ac849c384b71e96495e6b42 Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Fri, 20 Nov 2026 16:17:17 -0500 Subject: [PATCH 7/7] Clarify the 0106 required stop in the chart README Say that the failures on older builds lose no data, but 0106 discards any rows left in the tables. Scope the user-deletion failure to builds after relay-v0.3.0, which has no user-deletion executor. Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Luke Tornquist --- deploy/charts/buzz/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index 8b1649598cd..943fe0f0222 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -637,7 +637,7 @@ Schema migrations are embedded in the relay binary via `sqlx::migrate!` and run **Required stop before migration 0100.** Migrations 0098–0100 undo migration 0097, and 0100 drops the columns and indexes that 0097 added. No tagged relay release reads them. Only rolling images built from commit `eebf62b6` (#9650) up to, but not including, `a4061916` (#9689) do. Their channel artifact reads and writes fail once 0100 runs. If any relay pod, job or rollback target runs one of those images, move all of them to `sha-a406191` or later before you upgrade. To roll back after 0100 has run, set `migrate.autoMigrate=false` first, because an older binary with auto-migration on refuses a database that has migrations it does not know. Then roll back to `sha-a406191` or later, never to an image in that range. Migration 0098 refuses a database whose `artifact_heads` primary key is not `(community_id, artifact_id)`. Recover such a database as #9689 describes before upgrading. -**Required stop before migration 0106.** Migration 0106 drops the unused `delivery_log` and `subscriptions` tables. Builds before commit `7e94503f` (#9746), including `relay-v0.3.0`, still use them: community deletion fails its catalog check, user deletion fails, and startup partition maintenance logs errors. No data is lost. Before you upgrade to a build that contains 0106, move every relay pod, job and rollback target to `sha-7e94503` or later, or to the first tagged relay release that contains #9746. To roll back after 0106 has run, set `migrate.autoMigrate=false` first, then roll back to that build or later. +**Required stop before migration 0106.** Migration 0106 drops the unused `delivery_log` and `subscriptions` tables. Builds before commit `7e94503f` (#9746) still use them. On those builds community deletion fails its catalog check and startup partition maintenance logs errors. Builds after `relay-v0.3.0` also fail user deletion. These failures lose no data. Migration 0106 discards any rows in these unused tables; export them first if you need them. Before you upgrade to a build that contains 0106, move every relay pod, job and rollback target to `sha-7e94503` or later, or to the first tagged relay release that contains #9746. To roll back after 0106 has run, set `migrate.autoMigrate=false` first, then roll back to that build or later. Apply migrations before rolling the relay; for large installations, prefer a controlled `buzz-admin migrate` job with PostgreSQL lock monitoring before the code rollout.