From db7d37107a1b1b72759ff33fe437d27b833e552a Mon Sep 17 00:00:00 2001 From: Phil Azar Date: Mon, 16 Nov 2026 09:57:23 -0600 Subject: [PATCH] Keep community deletion working across a new tenant table's migration (#9304) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why The deletion engine compares the live set of `community_id` tables with an exact list. An expand migration that adds a tenant table therefore breaks community deletion for every community on the release that is deployed. It breaks again after a rollback to that release. #9301's migration 0087 adds three such tables. I reproduced this with the actual `buzz-admin` from #9301's merge-base (`838976d6e`): - Once 0087 is applied, that binary blocks every deletion with `catalog drift (missing=, unknown=identity_retirement_actions,…)`. - A request it approved before 0087 then fails permanently on #9301 too, with `approved structural catalog drifted before fencing`. A short gap between migrating and deploying doesn't make this compatible, so this release has to ship first. ## What - **`PENDING_SCOPED_TABLES`**: tables a later migration adds (the three identity retirement tables). - The catalog check accepts each of them whether it exists or not. - Purge and logical verification handle every one that is present. - The lookup runs inside the transaction that uses it, under the shared schema/destruction lock that migrations take exclusively. - **`APPROVAL_FORWARD_TABLES`**: a bounded exception to the approved-catalog check in `validate_approved_schema`. - A live table missing from the frozen inventory is accepted only if it is on this list. The list names only tables this binary purges and verifies. - A removed frozen table is still rejected before fencing, and so is any other addition. - The frozen manifest and digest are never rewritten. - Unlike `EXPECTED_SCOPED_TABLES`, a table stays on this list after the release that ships it moves it into the required catalog. - **`docs/database.md`**: - The table row for a new tenant table now requires this precursor release instead of "keep the gap short". - The checklist adds the matching step. - A paragraph documents the approval exception. #9301 is rebased onto this branch: it moves the three tables to the required catalog, empties `PENDING_SCOPED_TABLES`, and keeps `APPROVAL_FORWARD_TABLES`. ## Evidence All local runs, at head `21df5ece3` (on main `dd9da3ac6`). **Postgres lane** (`scripts/postgres-test-run.sh -p buzz-db -p buzz-deletion --lib --tests`): 782 passed, 258 skipped. **Store test** `pending_scoped_tables_are_optional_purged_and_verified`: - The catalog is accepted with the tables both absent and present. - An unknown table fails. - Purge deletes one target row per pending table. - A straggler row fails verification and names its table. - The bystander's rows survive. **Executor test** `approval_before_an_expand_migration_completes`: - It is in `external_infra_s3_tests` and needs Postgres, Redis and S3. CI doesn't run it; I ran it locally against MinIO. - It drives `execute_claim` on a request approved before the tables exist, through `RetentionPending`. - Target rows are gone and bystander rows survive. - An unlisted added table blocks the request before fencing. - A request whose frozen inventory includes the pending tables is blocked before fencing once those tables are dropped, with `approved structural catalog drifted`. - The test runs in a scratch database of its own, because it changes the catalog. **Falsification**: each of these mutations makes the executor test fail. - An exact approval comparison (the approved-legacy test fails too). - Swapping the forward list for `EXPECTED_SCOPED_TABLES` (the approved-legacy test fails too). - Purge skipping the pending tables. - Removing the catalog tolerance. - Ignoring removed frozen tables. The other S3 executor tests: `drained_stage…` and `final_storage…` pass. `approved_stage_allows_post_inventory_row_churn_before_fencing` fails here, and it fails the same way on `838976d6e`. **CLI exercise**, kept separate from the store tests. These are real `buzz-admin` binaries on a scratch database with local Redis and MinIO: - R0 is `838976d6e` (pre-feature), R1 is this branch, R2 is #9301 rebased onto it. | Step | Result | |---|---| | R0 migrates to 0086, then submits and approves c1, c2, c3 and c8 | `approved`, with 0 of 36 frozen tables being retirement tables | | R2 migrator applies 0087 and 0088 | at 88 | | Retirement-shaped rows inserted for targets c1, c2, c5, c6 and bystander c4 | 3 rows each | | R0 runs c8 | blocked, unknown identity retirement tables (below the floor) | | Unknown `compat_unknown_scoped` table present: R1 runs c3, then R2 runs c3 | both blocked (`unknown=compat_unknown_scoped`), `fence=none` | | R1 runs R0-approved c1 | `retention_pending` | | R2 runs R0-approved c2 | `retention_pending` | | R2 approves c5 (3 of 39 frozen tables are retirement tables), R1 runs it | `retention_pending` | | Rows afterwards | c1, c2, c5: 0; bystander c4: 3 | | R2 approves c6, the three tables are dropped, R1 runs c6 | blocked, `approved structural catalog drifted before fencing`, `fence=none` | **R1 relay restart after 0087**, with `BUZZ_AUTO_MIGRATE=false`: the relay starts, readiness returns 200, and it serves NIP-11 for a configured community. With auto-migration on, the same restart fails with `migration 87 was previously applied but is missing`. That is the existing Rule 5 limitation, and this PR doesn't fix it. Operators keep auto-migration off through the rollout. **Agent review**: an independent review found one blocker. The executor test changed the shared test database's catalog and left the tables behind. It now uses its own database. The review's optional findings on doc wording, checklist placement and removed-table executor coverage are also addressed. ## Limits - The migration of a later release still has to be applied with the documented migrator, which holds the schema lock. - A human has not tested this yet. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Philip Azar Co-authored-by: Claude Opus 5.5 --- crates/buzz-db/src/store/deletion.rs | 207 +++++++++++++++++++++++- crates/buzz-deletion/src/lib.rs | 234 ++++++++++++++++++++++++++- docs/database.md | 25 ++- 3 files changed, 456 insertions(+), 10 deletions(-) diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 7d4899e966..0cc325f4f7 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -128,6 +128,37 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "workflows", ]; +/// Tenant tables that a later release's expand migration adds. +/// +/// The catalog accepts each one present or absent; when present, the purge +/// deletes its rows and verification proves it empty. Listing a table here in +/// a release deployed before its migration keeps community deletion working +/// before and after the migration, in a mixed fleet, and after a rollback to +/// this release. The release that ships the table moves it to +/// [`EXPECTED_SCOPED_TABLES`] and [`PURGE_SCOPED_TABLES`]. These tables have +/// no foreign keys, so purge order does not matter. +pub const PENDING_SCOPED_TABLES: &[&str] = &[ + "identity_retirement_actions", + "identity_retirement_holds", + "identity_retirement_workflows", +]; + +/// Tenant tables an expand migration may add between a deletion's approval +/// and its execution. +/// +/// An approved catalog is otherwise exact: the executor rejects a frozen table +/// that is gone and any table added after approval that is not listed here +/// (`validate_approved_schema` in `buzz-deletion`). Each entry must be one +/// this release purges and verifies, in [`EXPECTED_SCOPED_TABLES`] or +/// [`PENDING_SCOPED_TABLES`]. A table stays here after it moves out of +/// `PENDING_SCOPED_TABLES`, so a request approved before its migration still +/// runs on the release that requires it. +pub const APPROVAL_FORWARD_TABLES: &[&str] = &[ + "identity_retirement_actions", + "identity_retirement_holds", + "identity_retirement_workflows", +]; + /// Control-plane tables with community provenance that the tenant purge does /// not own. Keep this list separate from the expected tenant table manifest so /// catalog validation still detects newly introduced tenant tables. @@ -2372,7 +2403,8 @@ impl DeletionStore { } // The order is child-before-parent/FK-safe, not alphabetical. Cascades // can make later units observe zero rows; each scoped WHERE stays idempotent. - for table in 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()) @@ -2478,8 +2510,10 @@ impl DeletionStore { token.community_id ))); } + let pending = live_pending_tables_on(&mut tx).await?; let scoped = EXPECTED_SCOPED_TABLES .iter() + .chain(&pending) .map(|table| (*table, format!("FROM {table} WHERE community_id = $1"))); let relay_admin = RELAY_ADMIN_TABLES .iter() @@ -3480,7 +3514,8 @@ async fn validate_catalog_on(conn: &mut PgConnection) -> Result<()> { .copied() .map(str::to_owned) .collect::>(); - let live_tables = live_scoped_tables_on(conn).await?; + let mut live_tables = live_scoped_tables_on(conn).await?; + live_tables.retain(|table| !PENDING_SCOPED_TABLES.contains(&table.as_str())); if live_tables != expected { let missing = expected .difference(&live_tables) @@ -3500,6 +3535,17 @@ async fn validate_catalog_on(conn: &mut PgConnection) -> Result<()> { Ok(()) } +/// 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() + .copied() + .filter(|table| live.contains(*table)) + .collect()) +} + async fn live_scoped_tables_on(conn: &mut PgConnection) -> Result> { let rows: Vec = sqlx::query_scalar( r#" @@ -3993,6 +4039,23 @@ fn bound_text(input: &str, max: usize) -> String { mod tests { use super::*; + /// Every table an approval may gain is one this release purges and + /// verifies, and every pending table may be gained after approval. + #[test] + fn approval_forward_tables_are_purged_and_cover_pending_tables() { + for table in APPROVAL_FORWARD_TABLES { + assert!( + EXPECTED_SCOPED_TABLES.contains(table) || PENDING_SCOPED_TABLES.contains(table), + "{table} is not purged by this release" + ); + } + for table in PENDING_SCOPED_TABLES { + assert!(APPROVAL_FORWARD_TABLES.contains(table), "{table}"); + assert!(!EXPECTED_SCOPED_TABLES.contains(table), "{table}"); + assert!(!PURGE_SCOPED_TABLES.contains(table), "{table}"); + } + } + #[test] fn scoped_table_exclusions_match_sql_during_transition() { let sql = @@ -8812,6 +8875,146 @@ DROP FUNCTION community_deletion_lock_key(UUID); .expect("count relay admin rows") } + /// A deletion inventoried before a later release's expand migration and + /// executed after it: each pending table is accepted absent and present, + /// purged for the target community only, and proven empty, while a table + /// the release does not know still fails closed. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn pending_scoped_tables_are_optional_purged_and_verified() { + let (_, scratch) = scratch_desired_state_database("deletion_pending").await; + let db = Db::new(&DbConfig { + database_url: scratch.url().to_owned(), + max_connections: 5, + min_connections: 0, + ..DbConfig::default() + }) + .await + .expect("connect scratch database"); + let store = db.deletion_store(); + store + .validate_catalog() + .await + .expect("pending tables absent"); + let (request, inventory) = inventoried_request(&db, &store).await; + 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(); + + // The expand migration lands after the request was inventoried. + for table in PENDING_SCOPED_TABLES { + sqlx::query(AssertSqlSafe(format!( + "CREATE TABLE {table} (community_id UUID NOT NULL)" + ))) + .execute(&db.pool) + .await + .expect("create pending table"); + for owner in [community, bystander] { + sqlx::query(AssertSqlSafe(format!( + "INSERT INTO {table} (community_id) VALUES ($1)" + ))) + .bind(owner) + .execute(&db.pool) + .await + .expect("seed pending table"); + } + } + store + .validate_catalog() + .await + .expect("pending tables present"); + 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 fails closed"); + assert!( + error + .to_string() + .contains("unknown=deletion_unknown_scoped"), + "{error}" + ); + sqlx::query("DROP TABLE deletion_unknown_scoped") + .execute(&db.pool) + .await + .expect("drop unknown table"); + + 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"); + let deleted = store.purge_postgres(&token).await.expect("purge postgres"); + for table in PENDING_SCOPED_TABLES { + assert_eq!(deleted.get(*table), Some(&1), "{table}"); + } + store + .mark_cache_purged(&token, serde_json::json!({"keys": 0})) + .await + .expect("cache"); + + // Verification covers the pending tables too: a straggler fails it. + for table in PENDING_SCOPED_TABLES { + let insert = format!("INSERT INTO {table} (community_id) VALUES ($1)"); + sqlx::query(AssertSqlSafe(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 pending table fails verification"); + assert!(error.to_string().contains(table), "{error}"); + let delete = format!("DELETE FROM {table} WHERE community_id = $1"); + sqlx::query(AssertSqlSafe(delete)) + .bind(community) + .execute(&db.pool) + .await + .expect("remove straggler"); + } + store + .verify_postgres_logically_deleted(&token) + .await + .expect("verify"); + for table in PENDING_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"); + } + } + /// Report-backed staff actions FK `moderation_reports`, and outbox rows FK /// their action. Purge must delete the community's report-backed and direct /// rows in FK order and leave other communities' rows alone. diff --git a/crates/buzz-deletion/src/lib.rs b/crates/buzz-deletion/src/lib.rs index 158681a96a..d5076f719d 100644 --- a/crates/buzz-deletion/src/lib.rs +++ b/crates/buzz-deletion/src/lib.rs @@ -1421,7 +1421,24 @@ fn validate_approved_schema( live: &buzz_db::deletion::SchemaManifest, frozen: &FrozenInventory, ) -> Result<()> { - if live.scoped_tables != frozen.schema.scoped_tables { + // The approved catalog binds exactly, with one bounded exception: an + // expand migration between approval and execution may add a table listed + // in APPROVAL_FORWARD_TABLES, which this binary purges and verifies. The + // frozen manifest and its digest are never rewritten. + let frozen_tables = frozen + .schema + .scoped_tables + .iter() + .collect::>(); + let live_tables = live + .scoped_tables + .iter() + .collect::>(); + let removed = !frozen_tables.is_subset(&live_tables); + let unlisted_addition = live_tables + .difference(&frozen_tables) + .any(|table| !buzz_db::deletion::APPROVAL_FORWARD_TABLES.contains(&table.as_str())); + if removed || unlisted_addition { return Err(permanent( "approved structural catalog drifted before fencing", )); @@ -1889,17 +1906,60 @@ mod postgres_tests { } } - async fn claimed_test_deletion(prefix: &str) -> (Db, Services, ClaimedDeletion) { - let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") + fn test_database_url() -> String { + std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) - .expect("BUZZ_TEST_DATABASE_URL or DATABASE_URL is required"); - let pool = sqlx::PgPool::connect(&database_url) + .expect("BUZZ_TEST_DATABASE_URL or DATABASE_URL is required") + } + + async fn claimed_test_deletion(prefix: &str) -> (Db, Services, ClaimedDeletion) { + let pool = sqlx::PgPool::connect(&test_database_url()) .await .expect("connect deletion engine test DB"); let db = Db::from_pool(pool); if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { db.migrate().await.expect("migrate deletion engine test DB"); } + claimed_test_deletion_in(db, prefix).await + } + + /// A migrated database of its own, named `{prefix}_{uuid}`, for a test + /// that changes the catalog: other tests would see the change as drift. + /// Drop it with [`drop_scratch_test_db`]. + async fn scratch_test_db(prefix: &str) -> (Db, String) { + let base_url = test_database_url(); + let name = format!("{prefix}_{}", Uuid::new_v4().simple()); + let admin = sqlx::PgPool::connect(&base_url) + .await + .expect("connect admin database"); + sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) + .execute(&admin) + .await + .expect("create scratch database"); + admin.close().await; + let base = &base_url[..base_url.rfind('/').expect("db url has a path segment")]; + let pool = sqlx::PgPool::connect(&format!("{base}/{name}")) + .await + .expect("connect scratch database"); + let db = Db::from_pool(pool); + db.migrate().await.expect("migrate scratch database"); + (db, name) + } + + async fn drop_scratch_test_db(db: Db, name: &str) { + db.pool().close().await; + let admin = sqlx::PgPool::connect(&test_database_url()) + .await + .expect("connect admin database"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "DROP DATABASE IF EXISTS {name} WITH (FORCE)" + ))) + .execute(&admin) + .await + .expect("drop scratch database"); + } + + async fn claimed_test_deletion_in(db: Db, prefix: &str) -> (Db, Services, ClaimedDeletion) { let store = db.deletion_store(); let host = format!("{prefix}-{}.example", Uuid::new_v4().simple()); let community = db @@ -2457,6 +2517,29 @@ mod postgres_tests { validate_approved_schema(&live, &decoded) .expect("legacy fence list is no longer structural"); + // Only a listed forward table may appear after approval. A required + // table the approval lacks is drift, and so is a removed frozen table. + let forward = buzz_db::deletion::APPROVAL_FORWARD_TABLES[0]; + let mut expanded = live.clone(); + expanded.scoped_tables.retain(|table| table != forward); + expanded.scoped_tables.push(forward.to_owned()); + let mut approved_before_expand = decoded.clone(); + approved_before_expand + .schema + .scoped_tables + .retain(|table| table != forward); + validate_approved_schema(&expanded, &approved_before_expand) + .expect("a listed forward table added after approval is not drift"); + let mut lacks_required = decoded.clone(); + lacks_required + .schema + .scoped_tables + .retain(|table| table != "workflows"); + assert!(validate_approved_schema(&live, &lacks_required).is_err()); + let mut removed = live.clone(); + removed.scoped_tables.retain(|table| table != "workflows"); + assert!(validate_approved_schema(&removed, &decoded).is_err()); + live.scoped_tables.push("unknown_tenant_table".to_string()); assert!(validate_approved_schema(&live, &decoded).is_err()); } @@ -2763,7 +2846,148 @@ mod postgres_tests { .expect("empty tenant prefixes verify clean"); } + /// A request approved before an expand migration adds the forward tables + /// 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. + 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")) + .expect("BUZZ_TEST_REDIS_URL or REDIS_URL is required"); + let services_with_infra = |mut services: Services| { + services.media = deletion_test_media_storage(); + services.redis = redis_connection(&redis_url).expect("connect Redis"); + services + }; + + // Each step changes the catalog, which a shared database would see. + let (scratch, scratch_name) = scratch_test_db("deletion_expand").await; + + // An unlisted addition fails before fencing. + let (db, services, claim) = + claimed_test_deletion_in(scratch.clone(), "deletion-unlisted").await; + let services = services_with_infra(services); + let request_id = claim.request.id; + sqlx::query("CREATE TABLE deletion_unlisted_scoped (community_id UUID NOT NULL)") + .execute(db.pool()) + .await + .expect("create unlisted table"); + let outcome = + execute_claim(&services, LoopMode::Run, claim, &CancellationToken::new()).await; + sqlx::query("DROP TABLE deletion_unlisted_scoped") + .execute(db.pool()) + .await + .expect("drop unlisted table"); + // The catalog check blocks it before the approval comparison runs. + let output = outcome.expect("run records the failure"); + assert_eq!(output.stage, DeletionStage::Approved); + let blocked = output + .blocked_reason + .expect("an unlisted addition blocks the request"); + assert!( + blocked.contains("unknown=deletion_unlisted_scoped"), + "{blocked}" + ); + let request = db + .deletion_store() + .get(request_id) + .await + .expect("load request"); + assert!(request.fence_generation.is_none()); + + // The forward tables appear after approval, with rows for the target + // and for a bystander. + let (db, services, claim) = + claimed_test_deletion_in(scratch.clone(), "deletion-straddle").await; + let services = services_with_infra(services); + let target = *claim.request.community_id.as_uuid(); + let bystander = *db + .ensure_configured_community(&format!( + "deletion-bystander-{}.example", + Uuid::new_v4().simple() + )) + .await + .expect("bystander community") + .id + .as_uuid(); + for table in buzz_db::deletion::PENDING_SCOPED_TABLES { + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE TABLE {table} (community_id UUID NOT NULL)" + ))) + .execute(db.pool()) + .await + .expect("create forward table"); + for community in [target, bystander] { + sqlx::query(sqlx::AssertSqlSafe(format!( + "INSERT INTO {table} (community_id) VALUES ($1)" + ))) + .bind(community) + .execute(db.pool()) + .await + .expect("seed forward 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) + ); + for table in buzz_db::deletion::PENDING_SCOPED_TABLES { + for (community, expected) in [(target, 0_i64), (bystander, 1)] { + let rows: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table} WHERE community_id = $1" + ))) + .bind(community) + .fetch_one(db.pool()) + .await + .expect("count forward rows"); + assert_eq!(rows, expected, "{table} {community}"); + } + } + + // An approval that froze the forward tables fails before fencing + // once they are gone. + let (db, services, claim) = + claimed_test_deletion_in(scratch.clone(), "deletion-removed").await; + let services = services_with_infra(services); + let request_id = claim.request.id; + for table in buzz_db::deletion::PENDING_SCOPED_TABLES { + sqlx::query(sqlx::AssertSqlSafe(format!("DROP TABLE {table}"))) + .execute(db.pool()) + .await + .expect("drop forward table"); + } + let output = execute_claim(&services, LoopMode::Run, claim, &CancellationToken::new()) + .await + .expect("run records the failure"); + assert_eq!(output.stage, DeletionStage::Approved); + let blocked = output + .blocked_reason + .expect("a removed frozen table blocks the request"); + assert!( + blocked.contains("approved structural catalog drifted"), + "{blocked}" + ); + let request = db + .deletion_store() + .get(request_id) + .await + .expect("load request"); + assert!(request.fence_generation.is_none()); + drop_scratch_test_db(scratch, &scratch_name).await; + } + mod external_infra_s3_tests { + #[tokio::test] + #[ignore = "requires Postgres, Redis and S3-compatible storage"] + async fn approval_before_an_expand_migration_completes() { + super::approval_before_an_expand_migration_completes().await; + } + #[tokio::test] #[ignore = "requires Postgres and S3-compatible storage"] async fn approved_stage_allows_post_inventory_row_churn_before_fencing() { diff --git a/docs/database.md b/docs/database.md index e7a4d30c4b..b573edec3c 100644 --- a/docs/database.md +++ b/docs/database.md @@ -109,7 +109,8 @@ in `crates/buzz-db/src/store/deletion.rs`). Two things still matter: `EXPECTED_SCOPED_TABLES`, fenced or not, fails it (`community deletion catalog drift (missing=…, unknown=…)`), and deletion fails closed for every community, not only the new table's. Listing the - table is enough to pass. + table passes once its release is deployed; a relay deployed before the + migration needs the table in `PENDING_SCOPED_TABLES` (see the checklist). - Desired-state bootstraps install only the legacy fences explicitly listed under `schema/triggers/`. They do not discover and fence new tables. Keep those existing backstops until their own retirement is verified; @@ -122,8 +123,15 @@ Do not add a trigger, or an entry in #### Checklist: adding a tenant-owned `community_id` table -All in the same PR: +First, ship a release that lists the table in `PENDING_SCOPED_TABLES` and +`APPROVAL_FORWARD_TABLES`, and deploy it to every relay, deletion executor and +operator CLI before the migration runs. Deletion then keeps working across the +migration, a mixed fleet and a rollback (see *What breaks the old relay*). +Then, all in the same PR: + +- [ ] The table moved from `PENDING_SCOPED_TABLES` to the required catalog + below, and kept in `APPROVAL_FORWARD_TABLES`. - [ ] Every writer of the table goes through community admission (`begin_community_write_transaction` or another constructor that returns `AdmittedTx`). Nothing writes the table outside it. @@ -141,6 +149,17 @@ All in the same PR: [crates/buzz-db/TESTING.md](../crates/buzz-db/TESTING.md)). Most tests use desired state, which builds the catalog differently. +An approved deletion binds the structural catalog frozen in its inventory. The +executor refuses, before fencing, an approval whose frozen tables are no longer +all live, or whose live catalog gained a table the approval did not freeze. +`APPROVAL_FORWARD_TABLES` is the one bounded exception: a live table outside +the frozen set is accepted only if it is on that list, which names only tables +the binary purges and verifies. The frozen manifest and digest are never +rewritten. An approval made before the expand migration therefore still +executes after it, and still purges the new table's rows. A table that is not +on the list is not covered by an older approval, even when it is in +`EXPECTED_SCOPED_TABLES`. + #### Checklist: adding a provenance-only table A table whose `community_id` only records which community a row came from, and @@ -364,7 +383,7 @@ before the contract have already committed, so an old pod that restarts hits | Add `CHECK`, `UNIQUE`, or a narrower index | Old writes violate it, or an old `ON CONFLICT` target no longer matches an index | Deploy writers that satisfy it, backfill, then add it. Add a `CHECK` as `NOT VALID`, then `VALIDATE CONSTRAINT` in a later step. Keep every index an old `ON CONFLICT` names until no deployed code uses it | | Add an enum value that new code writes | Old code fails to decode the unknown variant | Deploy readers that accept the value, then deploy writers that produce it | | Drop a column, table, index, trigger, function, or FK | Old code reads it or relies on its side effect | Contract step only, after the release that stops relying on it is fully deployed | -| Add a table with a `community_id` column | The old relay's exact-set deletion catalog check (`EXPECTED_SCOPED_TABLES`) sees an unknown table, so community deletion fails closed until the new release deploys. Serving is unaffected, apart from the auto-migration restart case in Rule 5 | Allowed. For a tenant-owned table, only after the desired-state change in Rule 1. Keep the gap between expand and deploy short, and do not run community deletion during it | +| Add a table with a `community_id` column | The old relay's exact-set deletion catalog check (`EXPECTED_SCOPED_TABLES`) sees an unknown table, so community deletion fails closed for every community until the new release deploys, and again after any rollback to it. Serving is unaffected, apart from the auto-migration restart case in Rule 5 | First ship a release that lists the table in `PENDING_SCOPED_TABLES` and deploy it everywhere; that release deletes communities with the table absent or present. Then migrate, then deploy the release that moves the table to `EXPECTED_SCOPED_TABLES`. The pending release becomes the rollback floor once the migration runs. For a tenant-owned table, only after the desired-state change in Rule 1 | | `SELECT *` or `RETURNING *` decoded by position | Column order differs between desired-state and migrated databases and changes when columns are added | Select named columns | #### Adding `NOT NULL` to a populated table