diff --git a/.pgschemaignore b/.pgschemaignore index 059350e198c..ef3938b4cf8 100644 --- a/.pgschemaignore +++ b/.pgschemaignore @@ -1,11 +1,12 @@ # pgschema reads this file from its working directory; every caller runs it # from the repository root. # -# The relay's partition manager creates dated `events` / `delivery_log` -# monthlies at runtime (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/ +# 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/ # declares stay managed by pgschema; keep the `!` exemptions below in sync with # them. [tables] diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7c58a5d87cb..6a25d266bb1 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -467,7 +467,7 @@ All database access. Uses `sqlx::query()` (runtime, not compile-time macros) — | `channel.rs` | Channel CRUD, membership management, role enforcement (transactional) | | `feed.rs` | `query_mentions` (INNER JOIN event_mentions), `query_needs_action`, `query_activity` | | `workflow.rs` | Full workflow/run/approval CRUD; SHA-256 hashed approval tokens | -| `partition.rs` | Monthly range partitioning for `events` and `delivery_log` tables: read-only catalog audit plus advisory-locked, time-bounded maintenance that creates uncovered months and advances an empty catch-all (`partition/maintenance.rs`) | +| `partition.rs` | Monthly range partitioning for the `events` table: read-only catalog audit plus advisory-locked, time-bounded maintenance that creates uncovered months and advances an empty catch-all (`partition/maintenance.rs`) | | `dm.rs` | DM channel management | | `reaction.rs` | Reaction storage and retrieval | | `thread.rs` | Thread/reply tracking | diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 597331b9d4f..29a0e6356ec 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -1552,6 +1552,7 @@ mod postgres_tests { ]; for table in crate::deletion::EXPECTED_SCOPED_TABLES .iter() + .chain(crate::deletion::RETIRING_SCOPED_TABLES) .filter(|table| !never_fenced.contains(table)) { assert!( @@ -3424,8 +3425,9 @@ mod postgres_tests { "reconcile did not attach both catch-alls: {declared_bounds:?}" ); - // The relay's default startup pass advances each catch-all into dated - // monthlies schema/partitions/ does not declare. + // 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. maintain_partitions( &pool, PARTITION_MANAGER_MONTHS_AHEAD, @@ -3442,13 +3444,17 @@ mod postgres_tests { "maintenance dropped or detached a catch-all: {advanced_bounds:?}" ); for (declared, advanced) in declared_bounds.iter().zip(&advanced_bounds) { - assert_ne!(declared, advanced, "catch-all did not advance"); + 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"); + } } let children: Vec<(String, String)> = sqlx::query_as( "SELECT p.relname::text, c.relname::text FROM pg_inherits i \ JOIN pg_class c ON c.oid = i.inhrelid \ JOIN pg_class p ON p.oid = i.inhparent \ - WHERE p.relname IN ('events', 'delivery_log')", + WHERE p.relname = 'events'", ) .fetch_all(&pool) .await @@ -3460,7 +3466,10 @@ mod postgres_tests { child.starts_with(&format!("{parent}_p2")) && !declared.contains(child) }) .collect(); - for (catch_all, bound) in &declared_bounds { + for (catch_all, bound) in declared_bounds + .iter() + .filter(|(catch_all, _)| catch_all == "events_p_future") + { // The first month the declared catch-all served, from its // `FOR VALUES FROM ('YYYY-MM-01 ...')` lower bound. let parent = catch_all diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 1e54275d81f..7b054e2b6d6 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -88,6 +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. pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "nip_fi_profile_heads", "api_tokens", @@ -99,7 +101,6 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "channels", "community_bans", "community_nip_fi_issuers", - "delivery_log", "event_mentions", "events", "git_repo_names", @@ -119,7 +120,6 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "relay_invites", "relay_members", "scheduled_workflow_fires", - "subscriptions", "thread_metadata", "users", "workflow_approvals", @@ -127,6 +127,26 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "workflows", ]; +/// Tenant tables a later contract migration drops. +/// +/// 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"]; + /// Tenant tables that a later release's expand migration adds. /// /// The catalog accepts each one present or absent; when present, the purge @@ -185,7 +205,6 @@ pub const PURGE_SCOPED_TABLES: &[&str] = &[ "media_uploaders", "media_publications", "moderation_reports", - "subscriptions", "api_tokens", "channel_members", "thread_metadata", @@ -196,7 +215,6 @@ pub const PURGE_SCOPED_TABLES: &[&str] = &[ "push_match_queue", "push_leases", "relay_invites", - "delivery_log", "artifact_heads", "artifact_revisions", "events", @@ -2362,8 +2380,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 pending = live_pending_tables_on(&mut tx).await?; - for table in pending.iter().chain(PURGE_SCOPED_TABLES) { + let optional = live_optional_tables_on(&mut tx).await?; + for table in optional.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()) @@ -2458,10 +2476,10 @@ impl DeletionStore { token.community_id ))); } - let pending = live_pending_tables_on(&mut tx).await?; + let optional = live_optional_tables_on(&mut tx).await?; let scoped = EXPECTED_SCOPED_TABLES .iter() - .chain(&pending) + .chain(&optional) .map(|table| (*table, format!("FROM {table} WHERE community_id = $1"))); let relay_admin = RELAY_ADMIN_TABLES .iter() @@ -3602,7 +3620,10 @@ 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())); + live_tables.retain(|table| { + !PENDING_SCOPED_TABLES.contains(&table.as_str()) + && !RETIRING_SCOPED_TABLES.contains(&table.as_str()) + }); if live_tables != expected { let missing = expected .difference(&live_tables) @@ -3622,12 +3643,14 @@ 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> { +/// 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> { let live = live_scoped_tables_on(conn).await?; Ok(PENDING_SCOPED_TABLES .iter() + .chain(RETIRING_SCOPED_TABLES) .copied() .filter(|table| live.contains(*table)) .collect()) @@ -4139,6 +4162,19 @@ 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(), @@ -4768,6 +4804,11 @@ 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); } @@ -4890,7 +4931,12 @@ 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"); - assert_eq!(inventory.scoped_tables.len(), EXPECTED_SCOPED_TABLES.len()); + let required = inventory + .scoped_tables + .iter() + .filter(|table| !RETIRING_SCOPED_TABLES.contains(&table.as_str())) + .count(); + assert_eq!(required, EXPECTED_SCOPED_TABLES.len()); assert!(inventory.fenced_tables.is_empty()); let lease = store .acquire_serving_write_lease( @@ -8887,9 +8933,16 @@ 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!( @@ -9636,6 +9689,233 @@ 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; + 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(); + (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"); + + // 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}"); + sqlx::query(AssertSqlSafe(format!( + "DELETE FROM {table} WHERE community_id = $1" + ))) + .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 { + assert!( + inventory + .schema + .scoped_tables + .iter() + .any(|frozen| frozen == table), + "{table} is frozen while it exists" + ); + } + + // 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}"); + } + 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 /// 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-db/src/store/partition.rs b/crates/buzz-db/src/store/partition.rs index cd5a5cd6b50..d2209c4dde1 100644 --- a/crates/buzz-db/src/store/partition.rs +++ b/crates/buzz-db/src/store/partition.rs @@ -1,5 +1,4 @@ -//! Read-only catalog audit and monthly partition manager for `events` and -//! `delivery_log`. +//! Read-only catalog audit and monthly partition manager for `events`. use std::collections::{HashMap, HashSet}; use std::time::{Duration, Instant}; @@ -20,7 +19,7 @@ pub use maintenance::{ }; /// Tables that may be partition-managed. The allowlist prevents DDL injection. -const PARTITIONED_TABLES: &[&str] = &["events", "delivery_log"]; +const PARTITIONED_TABLES: &[&str] = &["events"]; /// Maximum future-month horizon accepted by catalog audits and creation. /// @@ -42,7 +41,6 @@ const PARTITION_AUDIT_CONCURRENT_DROP_RETRIES: usize = 2; fn expected_partition_key(table: &str) -> Option<&'static str> { match table { "events" => Some("RANGE (created_at)"), - "delivery_log" => Some("RANGE (delivered_at)"), _ => None, } } @@ -2053,7 +2051,7 @@ mod tests { let mut incomplete = degraded_tables(); incomplete.pop(); let error = PartitionAuditError { - table: "delivery_log", + table: "events", error: "statement timeout".to_string(), }; for (tables, errors, outcome) in [ @@ -2405,38 +2403,32 @@ mod tests { } pub(in crate::store::partition) async fn seed_parents(pool: &PgPool) { - seed_parents_with_keys(pool, "created_at", "delivered_at").await; + seed_parents_with_keys(pool, "created_at").await; } - async fn seed_parents_with_keys(pool: &PgPool, events_key: &str, delivery_log_key: &str) { + async fn seed_parents_with_keys(pool: &PgPool, events_key: &str) { sqlx::query( "CREATE FUNCTION partition_test_trigger() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END $$", ) .execute(pool) .await .expect("create trigger function"); - for (table, column, partition_key) in [ - ("events", "created_at", events_key), - ("delivery_log", "delivered_at", delivery_log_key), - ] { - let create = format!( - "CREATE TABLE {table} (id BIGSERIAL, {column} TIMESTAMPTZ NOT NULL, \ - alternate_at TIMESTAMPTZ NOT NULL, \ - PRIMARY KEY ({column}, alternate_at, id)) PARTITION BY RANGE ({partition_key})" - ); - sqlx::query(sqlx::AssertSqlSafe(create)) - .execute(pool) - .await - .expect("create partitioned parent"); - let trigger = format!( - "CREATE TRIGGER partition_probe BEFORE INSERT ON {table} \ - FOR EACH ROW EXECUTE FUNCTION partition_test_trigger()" - ); - sqlx::query(sqlx::AssertSqlSafe(trigger)) - .execute(pool) - .await - .expect("create parent trigger"); - } + let create = format!( + "CREATE TABLE events (id BIGSERIAL, created_at TIMESTAMPTZ NOT NULL, \ + alternate_at TIMESTAMPTZ NOT NULL, \ + PRIMARY KEY (created_at, alternate_at, id)) PARTITION BY RANGE ({events_key})" + ); + sqlx::query(sqlx::AssertSqlSafe(create)) + .execute(pool) + .await + .expect("create partitioned parent"); + sqlx::query( + "CREATE TRIGGER partition_probe BEFORE INSERT ON events \ + FOR EACH ROW EXECUTE FUNCTION partition_test_trigger()", + ) + .execute(pool) + .await + .expect("create parent trigger"); } pub(in crate::store::partition) async fn create_child( @@ -2665,7 +2657,7 @@ mod tests { #[ignore = "requires Postgres"] async fn wrong_root_partition_key_never_proves_coverage() { let (pool, _scratch) = scratch_pool().await; - seed_parents_with_keys(&pool, "alternate_at", "delivered_at").await; + seed_parents_with_keys(&pool, "alternate_at").await; for table in PARTITIONED_TABLES { create_child( &pool, @@ -2693,13 +2685,6 @@ mod tests { assert!(!events.serving_safe); assert!(events.coverage_leaves.is_empty()); assert_eq!(events.children[0].kind, PartitionChildKind::Anomalous); - let delivery_log = audit - .tables - .iter() - .find(|table| table.table == "delivery_log") - .expect("delivery_log audit"); - assert!(delivery_log.partition_key_valid); - assert!(delivery_log.serving_safe); } #[tokio::test] @@ -2737,15 +2722,6 @@ mod tests { && leaf.name == "events_p_future" && leaf.root_child_schema == schema })); - let delivery_log = audit - .tables - .iter() - .find(|table| table.table == "delivery_log") - .expect("delivery_log audit"); - assert_eq!(delivery_log.nonempty_catch_all_count(), 0); - assert!(delivery_log.children.iter().any(|child| { - child.name == "delivery_log_p_future" && child.catch_all_nonempty == Some(false) - })); } #[tokio::test] @@ -2828,22 +2804,6 @@ mod tests { "MAXVALUE", ) .await; - create_child( - &pool, - "delivery_log", - "delivery_log_p_past", - "MINVALUE", - "'2026-09-01'", - ) - .await; - create_child( - &pool, - "delivery_log", - "delivery_log_p_future", - "'2026-09-01'", - "MAXVALUE", - ) - .await; sqlx::query(sqlx::AssertSqlSafe(format!( "ALTER TABLE ONLY {}.{} DISABLE TRIGGER partition_probe", quote_identifier(&second_schema), @@ -2906,7 +2866,7 @@ mod tests { #[tokio::test] #[ignore = "requires Postgres"] - async fn report_retains_successful_table_when_another_table_errors() { + async fn report_surfaces_audit_error_for_unreadable_managed_table() { let (pool, scratch) = scratch_pool().await; let schema = scratch.name.as_str(); seed_fresh_layout(&pool).await; @@ -2915,15 +2875,12 @@ mod tests { .execute(&scratch.admin) .await .expect("create restricted audit role"); - for statement in [ - format!("GRANT USAGE ON SCHEMA {schema} TO {role}"), - format!("GRANT SELECT ON {schema}.events_p_future TO {role}"), - ] { - sqlx::query(sqlx::AssertSqlSafe(statement)) - .execute(&scratch.admin) - .await - .expect("grant restricted audit access"); - } + sqlx::query(sqlx::AssertSqlSafe(format!( + "GRANT USAGE ON SCHEMA {schema} TO {role}" + ))) + .execute(&scratch.admin) + .await + .expect("grant restricted audit access"); let url = crate::test_support::database_url(); let role_schema = schema.to_owned(); let role_name = role.clone(); @@ -2947,12 +2904,12 @@ mod tests { .expect("connect restricted audit pool"); let report = audit_partition_catalog_report_at(&restricted, 0, fixed_now()).await; - assert_eq!(report.tables.len(), 1); - assert_eq!(report.tables[0].table, "events"); + assert!(report.tables.is_empty()); assert_eq!(report.errors.len(), 1); - assert_eq!(report.errors[0].table, "delivery_log"); + assert_eq!(report.errors[0].table, "events"); assert!(report.errors[0].error.contains("permission denied")); assert!(!report.serving_safe()); + assert_eq!(report.outcome(), PartitionAuditOutcome::Error); restricted.close().await; } @@ -3211,21 +3168,6 @@ mod tests { && leaf.catch_all_nonempty.is_none() && leaf.default_nonempty == Some(true) })); - let delivery_log = audit - .tables - .iter() - .find(|table| table.table == "delivery_log") - .expect("delivery_log audit"); - assert_eq!(delivery_log.nonempty_default_count(), 0); - assert!(delivery_log.children.iter().any(|child| { - child.name == "delivery_log_default" && child.default_nonempty == Some(false) - })); - assert!(delivery_log.coverage_leaves.iter().any(|leaf| { - leaf.name == "delivery_log_default" - && leaf.is_default - && leaf.default_routed - && leaf.default_nonempty == Some(false) - })); let recorder = metrics_util::debugging::DebuggingRecorder::new(); let snapshotter = recorder.snapshotter(); @@ -3260,40 +3202,39 @@ mod tests { async fn parent_default_does_not_mask_gap_below_explicit_sibling() { let (pool, _scratch) = scratch_pool().await; seed_parents(&pool).await; - for (table, column) in [("events", "created_at"), ("delivery_log", "delivered_at")] { - create_child( - &pool, - table, - &format!("{table}_p_past"), - "MINVALUE", - "'2026-09-01'", - ) - .await; - let nested = format!("{table}_nested"); - create_nested_child( - &pool, - table, - &nested, - column, - "'2026-09-01'", - "'2026-10-01'", - ) - .await; - create_child( - &pool, - &nested, - &format!("{table}_nested_late"), - "'2026-09-20'", - "'2026-10-01'", - ) - .await; - sqlx::query(sqlx::AssertSqlSafe(format!( - "CREATE TABLE {table}_default PARTITION OF {table} DEFAULT" - ))) - .execute(&pool) - .await - .expect("create parent default partition"); - } + let (table, column) = ("events", "created_at"); + create_child( + &pool, + table, + &format!("{table}_p_past"), + "MINVALUE", + "'2026-09-01'", + ) + .await; + let nested = format!("{table}_nested"); + create_nested_child( + &pool, + table, + &nested, + column, + "'2026-09-01'", + "'2026-10-01'", + ) + .await; + create_child( + &pool, + &nested, + &format!("{table}_nested_late"), + "'2026-09-20'", + "'2026-10-01'", + ) + .await; + sqlx::query(sqlx::AssertSqlSafe(format!( + "CREATE TABLE {table}_default PARTITION OF {table} DEFAULT" + ))) + .execute(&pool) + .await + .expect("create parent default partition"); let audit = audit_partition_catalog_at(&pool, 0, fixed_now()) .await @@ -3324,13 +3265,6 @@ mod tests { .execute(&pool) .await .is_err()); - assert!(sqlx::query( - "INSERT INTO delivery_log (delivered_at, alternate_at) \ - VALUES ('2026-09-15', '2026-09-15')", - ) - .execute(&pool) - .await - .is_err()); } #[tokio::test] @@ -3489,34 +3423,33 @@ mod tests { let (pool, scratch) = scratch_pool().await; let schema = scratch.name.as_str(); seed_parents(&pool).await; - for (table, column) in [("events", "created_at"), ("delivery_log", "delivered_at")] { - let nested = format!("{table}_nested"); - create_nested_child( - &pool, - table, - &nested, - column, - "'2026-09-01'", - "'2026-10-01'", - ) - .await; - create_child( - &pool, - &nested, - &format!("{table}_nested_first"), - "'2026-09-01'", - "'2026-09-15'", - ) - .await; - create_child( - &pool, - &nested, - &format!("{table}_nested_second"), - "'2026-09-15'", - "'2026-10-01'", - ) - .await; - } + let (table, column) = ("events", "created_at"); + let nested = format!("{table}_nested"); + create_nested_child( + &pool, + table, + &nested, + column, + "'2026-09-01'", + "'2026-10-01'", + ) + .await; + create_child( + &pool, + &nested, + &format!("{table}_nested_first"), + "'2026-09-01'", + "'2026-09-15'", + ) + .await; + create_child( + &pool, + &nested, + &format!("{table}_nested_second"), + "'2026-09-15'", + "'2026-10-01'", + ) + .await; let healthy = audit_partition_catalog_at(&pool, 0, fixed_now()) .await @@ -3665,17 +3598,16 @@ mod tests { async fn nested_children_without_leaves_do_not_prove_coverage() { let (pool, _scratch) = scratch_pool().await; seed_parents(&pool).await; - for (table, column) in [("events", "created_at"), ("delivery_log", "delivered_at")] { - create_nested_child( - &pool, - table, - &format!("{table}_nested"), - column, - "'2026-09-01'", - "'2026-10-01'", - ) - .await; - } + let (table, column) = ("events", "created_at"); + create_nested_child( + &pool, + table, + &format!("{table}_nested"), + column, + "'2026-09-01'", + "'2026-10-01'", + ) + .await; let before = catalog_snapshot(&pool).await; let audit = audit_partition_catalog_at(&pool, 0, fixed_now()) @@ -3696,26 +3628,25 @@ mod tests { async fn nested_descendant_leaves_prove_coverage_but_remain_degraded() { let (pool, _scratch) = scratch_pool().await; seed_parents(&pool).await; - for (table, column) in [("events", "created_at"), ("delivery_log", "delivered_at")] { - let nested = format!("{table}_nested"); - create_nested_child( - &pool, - table, - &nested, - column, - "'2026-09-01'", - "'2026-10-01'", - ) - .await; - create_child( - &pool, - &nested, - &format!("{table}_nested_leaf"), - "'2026-09-01'", - "'2026-10-01'", - ) - .await; - } + let (table, column) = ("events", "created_at"); + let nested = format!("{table}_nested"); + create_nested_child( + &pool, + table, + &nested, + column, + "'2026-09-01'", + "'2026-10-01'", + ) + .await; + create_child( + &pool, + &nested, + &format!("{table}_nested_leaf"), + "'2026-09-01'", + "'2026-10-01'", + ) + .await; let before = catalog_snapshot(&pool).await; let audit = audit_partition_catalog_at(&pool, 0, fixed_now()) @@ -3737,26 +3668,25 @@ mod tests { async fn occupied_nested_catch_all_is_reported_on_leaf_and_root_child() { let (pool, _scratch) = scratch_pool().await; seed_parents(&pool).await; - for (table, column) in [("events", "created_at"), ("delivery_log", "delivered_at")] { - let nested = format!("{table}_nested"); - create_nested_child( - &pool, - table, - &nested, - column, - "'2026-09-01'", - "'2026-10-01'", - ) - .await; - create_child( - &pool, - &nested, - &format!("{table}_nested_future"), - "'2026-09-01'", - "MAXVALUE", - ) - .await; - } + let (table, column) = ("events", "created_at"); + let nested = format!("{table}_nested"); + create_nested_child( + &pool, + table, + &nested, + column, + "'2026-09-01'", + "'2026-10-01'", + ) + .await; + create_child( + &pool, + &nested, + &format!("{table}_nested_future"), + "'2026-09-01'", + "MAXVALUE", + ) + .await; sqlx::query( "INSERT INTO events (created_at, alternate_at) \ VALUES ('2026-09-15', '2026-09-15')", @@ -3785,15 +3715,6 @@ mod tests { && !leaf.is_default && leaf.catch_all_nonempty == Some(true) })); - let delivery_log = audit - .tables - .iter() - .find(|table| table.table == "delivery_log") - .expect("delivery_log audit"); - assert_eq!(delivery_log.nonempty_catch_all_count(), 0); - assert!(delivery_log.coverage_leaves.iter().any(|leaf| { - leaf.name == "delivery_log_nested_future" && leaf.catch_all_nonempty == Some(false) - })); } #[tokio::test] diff --git a/crates/buzz-db/src/store/partition/maintenance.rs b/crates/buzz-db/src/store/partition/maintenance.rs index cf624d266ae..d7b08216c0a 100644 --- a/crates/buzz-db/src/store/partition/maintenance.rs +++ b/crates/buzz-db/src/store/partition/maintenance.rs @@ -1,4 +1,4 @@ -//! Serialized, bounded partition DDL for `events` and `delivery_log`. +//! Serialized, bounded partition DDL for `events`. //! //! The manager issues only two kinds of change: creating a month that no //! partition covers, and replacing an empty right-edge catch-all with diff --git a/crates/buzz-db/src/store/partition/maintenance_tests.rs b/crates/buzz-db/src/store/partition/maintenance_tests.rs index 1de67c68c66..b407432fec6 100644 --- a/crates/buzz-db/src/store/partition/maintenance_tests.rs +++ b/crates/buzz-db/src/store/partition/maintenance_tests.rs @@ -410,7 +410,7 @@ mod postgres_tests { }; use crate::test_support::ScratchDb; - /// The repaired incident layout for both managed parents, optionally with + /// The repaired incident layout for the managed parent, optionally with /// outgoing foreign keys to a `communities` counterpart. async fn seed_repaired_layout(pool: &PgPool, with_foreign_keys: bool) { seed_parents(pool).await; @@ -621,7 +621,6 @@ mod postgres_tests { "GRANT INSERT, SELECT (id) ON events TO {}", quote_identifier(&writer) ), - "GRANT SELECT ON delivery_log TO PUBLIC".to_string(), "CREATE TABLE unrelated (id BIGINT)".to_string(), ] { execute_ddl(&mut pool.acquire().await.unwrap(), statement) @@ -670,17 +669,11 @@ mod postgres_tests { for privilege in ["INSERT", "UPDATE", "SELECT WITH GRANT OPTION"] { assert!(!can(reader.clone(), "events_p2026_09".into(), privilege).await); } - for relation in [ - "events_p2026_09", - "events_p_past", - "delivery_log_p_past", - "unrelated", - ] { + for relation in ["events_p2026_09", "events_p_past", "unrelated"] { assert!(!can(writer.clone(), relation.into(), "SELECT").await); } assert!(!can(reader.clone(), "events_p_past".into(), "SELECT").await); assert!(!can(reader.clone(), "unrelated".into(), "SELECT").await); - assert!(can(writer.clone(), "delivery_log_p2026_09".into(), "SELECT").await); // The next rotation uses the current parent ACL, not a cached reader list. for statement in [ @@ -709,10 +702,6 @@ mod postgres_tests { assert!(!can(writer.clone(), relation.into(), "INSERT").await); assert!(!can(reader.clone(), relation.into(), "SELECT").await); } - for relation in ["delivery_log_p2026_10", "delivery_log_p_future"] { - assert!(can(reader.clone(), relation.into(), "SELECT").await); - assert!(!can(reader.clone(), relation.into(), "INSERT").await); - } let before = catalog_snapshot(&pool).await; maintain_partitions_at(&pool, 1, ADVANCE, fixed_now()) .await @@ -720,6 +709,101 @@ mod postgres_tests { assert_eq!(catalog_snapshot(&pool).await, before); } + /// `events` is the only managed parent, so this is the one positive + /// PUBLIC-grant case: a PUBLIC SELECT on the parent reaches the monthly + /// children maintenance creates and the catch-all it replaces, read-only. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn cluster_global_public_parent_reader_reaches_new_monthlies_and_replaced_catch_all() { + use crate::store::partition::quote_identifier; + + let (pool, scratch) = scratch_pool().await; + seed_parents(&pool).await; + // Dropped with the scratch schema: its cleanup removes roles named + // `{schema}_*`. + let outsider = format!("{}_public_outsider", scratch.name); + for statement in [ + format!("CREATE ROLE {} NOLOGIN", quote_identifier(&outsider)), + format!( + "GRANT USAGE ON SCHEMA {} TO {}", + scratch.name, + quote_identifier(&outsider) + ), + "GRANT SELECT ON events TO PUBLIC".to_string(), + "CREATE TABLE unrelated (id BIGINT)".to_string(), + ] { + execute_ddl(&mut pool.acquire().await.unwrap(), statement) + .await + .unwrap(); + } + create_child(&pool, "events", "events_p_past", "MINVALUE", "'2026-09-01'").await; + + let can = |relation: &'static str, privilege: &'static str| { + let pool = pool.clone(); + let outsider = outsider.clone(); + async move { + sqlx::query_scalar::<_, bool>("SELECT has_table_privilege($1, $2, $3)") + .bind(outsider) + .bind(relation) + .bind(privilege) + .fetch_one(&pool) + .await + .unwrap() + } + }; + + // Monthly creation. + maintain_partitions_at(&pool, 0, CREATE_ONLY, fixed_now()) + .await + .expect("create uncovered September"); + let mut direct_read = pool.begin().await.unwrap(); + execute_ddl( + &mut direct_read, + format!("SET LOCAL ROLE {}", quote_identifier(&outsider)), + ) + .await + .unwrap(); + sqlx::query("SELECT * FROM events_p2026_09 LIMIT 0") + .execute(&mut *direct_read) + .await + .expect("an unrelated role can read the new monthly through PUBLIC"); + direct_read.rollback().await.unwrap(); + assert!(can("events_p2026_09", "SELECT").await); + + // Catch-all replacement. + create_child( + &pool, + "events", + "events_p_future", + "'2026-10-01'", + "MAXVALUE", + ) + .await; + assert!(!can("events_p_future", "SELECT").await); + maintain_partitions_at(&pool, 1, ADVANCE, fixed_now()) + .await + .expect("replace catch-all and grant PUBLIC"); + for relation in ["events_p2026_10", "events_p_future"] { + assert!(can(relation, "SELECT").await, "{relation} SELECT"); + } + + // Read-only, and only where maintenance created the child. + for relation in ["events_p2026_09", "events_p2026_10", "events_p_future"] { + for privilege in [ + "INSERT", + "UPDATE", + "DELETE", + "TRUNCATE", + "SELECT WITH GRANT OPTION", + ] { + assert!(!can(relation, privilege).await, "{relation} {privilege}"); + } + } + for relation in ["events_p_past", "unrelated"] { + assert!(!can(relation, "SELECT").await, "{relation} SELECT"); + } + } + #[tokio::test] #[ignore = "requires Postgres"] async fn cluster_global_reader_grant_failure_rolls_back_partition_replacement() { @@ -784,8 +868,7 @@ mod postgres_tests { assert!( matches!(result, Err(DbError::InvalidData(ref message)) if message.contains("events operator_required") - && message.contains("events_p_future_next contains rows") - && !message.contains("delivery_log")), + && message.contains("events_p_future_next contains rows")), "{result:?}" ); assert!(elapsed < std::time::Duration::from_secs(1), "{elapsed:?}"); @@ -819,11 +902,10 @@ mod postgres_tests { assert!( matches!(result, Err(DbError::InvalidData(ref message)) - if message.contains("events lock_timeout") - && message.contains("delivery_log lock_timeout")), + if message.contains("events lock_timeout")), "{result:?}" ); - // NOWAIT: no 2s wait per table while a counterpart writer is active. + // NOWAIT: no 2s wait while a counterpart writer is active. assert!(elapsed < std::time::Duration::from_secs(1), "{elapsed:?}"); assert_eq!(catalog_snapshot(&pool).await, before); @@ -975,8 +1057,7 @@ mod postgres_tests { matches!(result, Err(DbError::InvalidData(ref message)) if message.contains("events lock_timeout") && message.contains("could not obtain lock on relation") - && message.contains(r#".reviewers""#) - && !message.contains("delivery_log")), + && message.contains(r#".reviewers""#)), "{result:?}" ); @@ -995,8 +1076,7 @@ mod postgres_tests { fn refused_events_only(result: &Result, reason: &str) -> bool { matches!(result, Err(DbError::InvalidData(message)) if message.contains("events operator_required") - && message.contains(reason) - && !message.contains("delivery_log")) + && message.contains(reason)) } #[tokio::test] @@ -1139,13 +1219,17 @@ mod postgres_tests { async fn deadlock_victim_is_classified_as_a_lock_timeout() { let (pool, _scratch) = scratch_pool().await; seed_parents(&pool).await; + sqlx::query("CREATE TABLE deadlock_peer (id BIGINT)") + .execute(&pool) + .await + .expect("create deadlock peer"); let mut first = hold_lock(&pool, "LOCK TABLE ONLY events IN ACCESS EXCLUSIVE MODE").await; let mut second = hold_lock( &pool, - "LOCK TABLE ONLY delivery_log IN ACCESS EXCLUSIVE MODE", + "LOCK TABLE ONLY deadlock_peer IN ACCESS EXCLUSIVE MODE", ) .await; - let first_waits = sqlx::query("LOCK TABLE ONLY delivery_log IN ACCESS EXCLUSIVE MODE") + let first_waits = sqlx::query("LOCK TABLE ONLY deadlock_peer IN ACCESS EXCLUSIVE MODE") .execute(&mut *first); let second_waits = async { tokio::time::sleep(std::time::Duration::from_millis(100)).await; @@ -1175,9 +1259,10 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] - async fn parent_contention_times_out_without_blocking_the_other_table() { + async fn parent_contention_times_out_and_leaves_the_catalog_unchanged() { let (pool, _scratch) = scratch_pool().await; seed_repaired_layout(&pool, true).await; + let before = catalog_snapshot(&pool).await; let holder = hold_lock(&pool, "LOCK TABLE ONLY events IN ACCESS SHARE MODE").await; let result = maintain(&pool).await; @@ -1185,9 +1270,10 @@ mod postgres_tests { assert!( matches!(result, Err(DbError::InvalidData(ref message)) - if message.contains("events lock_timeout") && !message.contains("delivery_log")), + if message.contains("events lock_timeout")), "{result:?}" ); + assert_eq!(catalog_snapshot(&pool).await, before); let audit = audit_partition_catalog_at(&pool, PARTITION_MANAGER_MONTHS_AHEAD, fixed_now()) .await .expect("audit"); @@ -1196,16 +1282,8 @@ mod postgres_tests { .children .iter() .any(|child| child.name == "events_p_future_next")); - let delivery_log = audit - .tables - .iter() - .filter(|t| t.table == "delivery_log") - .cloned() - .collect::>(); - assert_advanced(&PartitionAudit { - audited_at: audit.audited_at, - tables: delivery_log, - }); + + assert_advanced(&maintain(&pool).await.expect("advance after release")); } #[tokio::test] @@ -1348,8 +1426,7 @@ mod postgres_tests { assert!( matches!(result, Err(DbError::InvalidData(ref message)) if message.contains("events operator_required") - && message.contains("child-only triggers (catch_all_only)") - && !message.contains("delivery_log")), + && message.contains("child-only triggers (catch_all_only)")), "{result:?}" ); let after = catalog_snapshot(&pool).await; @@ -1560,7 +1637,7 @@ mod postgres_tests { assert!(after .iter() .any(|(name, ..)| name == "events_p_future_next")); - assert_ne!(after, before, "delivery_log still advances"); + assert_eq!(after, before, "a refused events layout is left untouched"); } /// Audits taken in a freshly migrated database before and after its first passes. diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/operations.rs b/crates/buzz-db/src/store/user_deletion/account_batches/operations.rs index 403a77795f8..2c1b590f2ee 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/operations.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/operations.rs @@ -19,7 +19,6 @@ impl Operation { "events" => ("created_at,id", "(created_at,id)>(($3->>'created_at')::timestamptz,decode($3->>'id','hex'))"), "event_mentions" => ("pubkey_hex,event_id", "(pubkey_hex,event_id)>($3->>'pubkey_hex',decode($3->>'event_id','hex'))"), "push_match_queue" => ("event_id", "event_id>decode($3->>'event_id','hex')"), - "delivery_log" => ("delivered_at,id", "(delivered_at,id)>(($3->>'delivered_at')::timestamptz,($3->>'id')::bigint)"), "operator_listener_pubkeys" => ("listener_pubkey,target_pubkey", "(listener_pubkey,target_pubkey)>(decode($3->>'listener_pubkey','hex'),decode($3->>'target_pubkey','hex'))"), "channel_members" => ("channel_id,pubkey", "(channel_id,pubkey)>(($3->>'channel_id')::uuid,decode($3->>'pubkey','hex'))"), "join_policy_acceptances" => ("pubkey,policy_version", "(pubkey,policy_version)>($3->>'pubkey',$3->>'policy_version')"), @@ -127,9 +126,6 @@ pub(super) const OPERATIONS: &[Operation] = &[ "jsonb_build_object('event_id',encode(event_id,'hex'))", "event_id=decode($3->>'event_id','hex')"), delete("push_wake_outbox", personal_event_copy!(), ID_KEY, ID_MATCH), delete("operator_listener_outbox", personal_event_copy!(), ID_KEY, ID_MATCH), - delete("delivery_log", personal_event_copy!(), - "jsonb_build_object('delivered_at',delivered_at,'id',id)", - "delivered_at=($3->>'delivered_at')::timestamptz AND id=($3->>'id')::bigint"), delete("events", personal_events!(), "jsonb_build_object('created_at',created_at,'id',encode(id,'hex'))", "created_at=($3->>'created_at')::timestamptz AND id=decode($3->>'id','hex')"), diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/expansion_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/expansion_postgres_tests.rs index 334b5c59668..ffe5c30119c 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/expansion_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/expansion_postgres_tests.rs @@ -174,18 +174,11 @@ async fn personal_events_revisions_copies_and_community_feedback_are_removed() { .await .unwrap(); sqlx::query("INSERT INTO operator_listener_outbox(listener_pubkey,target_pubkey,community_id,event_id,event_kind,event_created_at) SELECT decode($1,'hex'),pubkey,community_id,id,kind,created_at FROM events").bind(ACTOR).execute(&f.pool).await.unwrap(); - sqlx::query( - "INSERT INTO delivery_log(community_id,event_id) SELECT community_id,id FROM events", - ) - .execute(&f.pool) - .await - .unwrap(); let tables = [ "events", "event_mentions", "push_match_queue", "operator_listener_outbox", - "delivery_log", "product_feedback", "parameterized_event_watermarks", ]; diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs index efde44e1316..43b7ed4560f 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs @@ -185,18 +185,6 @@ async fn owned_agents_share_bounded_batches_and_preserve_other_owners_and_commun for (index, author) in authors.into_iter().enumerate() { let key = author.public_key().to_bytes(); let id = &first_ids[index]; - let sub = format!("sub-{index}"); - sqlx::query( - "INSERT INTO subscriptions (community_id,id,owner_pubkey) VALUES ($1,$2,$3)", - ) - .bind(community.as_uuid()) - .bind(&sub) - .bind(key.as_slice()) - .execute(&pool) - .await - .unwrap(); - sqlx::query("INSERT INTO delivery_log (community_id,subscription_id,event_id) VALUES ($1,$2,$3)") - .bind(community.as_uuid()).bind(&sub).bind(&first_ids[3]).execute(&pool).await.unwrap(); sqlx::query("INSERT INTO reactions (community_id,event_created_at,event_id,pubkey,emoji) VALUES ($1,to_timestamp($2),$3,$4,'+')") .bind(community.as_uuid()).bind(timestamp.as_secs() as f64).bind(&first_ids[3]) .bind(key.as_slice()).execute(&pool).await.unwrap(); @@ -237,8 +225,6 @@ async fn owned_agents_share_bounded_batches_and_preserve_other_owners_and_commun "events", "event_mentions", "reactions", - "subscriptions", - "delivery_log", "push_leases", "push_match_queue", "push_wake_outbox", @@ -368,11 +354,6 @@ async fn owned_agents_share_bounded_batches_and_preserve_other_owners_and_commun !selected.contains(&hex_field("event_id")) } "reactions" => !owned("pubkey"), - "subscriptions" => !owned("owner_pubkey"), - "delivery_log" => { - !["sub-0", "sub-1"].contains(&row["subscription_id"].as_str().unwrap()) - && !selected.contains(&hex_field("event_id")) - } "push_leases" | "push_wake_outbox" => !owned("author"), "operator_listener_outbox" => { !owned("target_pubkey") && !owned("listener_pubkey") diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/copies_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/copies_postgres_tests.rs deleted file mode 100644 index 2c996fcba02..00000000000 --- a/crates/buzz-db/src/store/user_deletion/content_batches/copies_postgres_tests.rs +++ /dev/null @@ -1,199 +0,0 @@ -use super::scrub_postgres_tests::{options, setup, PauseAfterPlan}; -use super::*; -use crate::user_deletion::ExecutionMode; -use nostr::{EventBuilder, Kind}; - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn event_batch_deletion_preserves_large_unrelated_delivery_history() { - let (db, c, _, alice, _) = setup().await; - for n in 0..100 { - let event = EventBuilder::new(Kind::Custom(1063), format!("personal metadata {n}")) - .sign_with_keys(&alice) - .unwrap(); - db.insert_event(c, &event, None).await.unwrap(); - } - // Event IDs have no delivery-log index. A per-event dependency probe scans - // this unrelated history 100 times and exceeds the executor's 3s timeout. - sqlx::query( - "INSERT INTO delivery_log(community_id,subscription_id,event_id,error_message) - SELECT $1,'unrelated',decode(md5(g::text)||md5(g::text),'hex'),repeat('x',128) - FROM generate_series(1,500000) g", - ) - .bind(c.as_uuid()) - .execute(db.pool()) - .await - .unwrap(); - // Many tiny tenants make generic-plan estimates underestimate this tenant. - // A plain IN semi join can compare every log to every event after ANALYZE. - sqlx::query( - "WITH tenants AS ( - INSERT INTO communities(id,host) - SELECT gen_random_uuid(),'delivery-'||g||'.example' - FROM generate_series(1,9999) g RETURNING id - ) INSERT INTO delivery_log(community_id,event_id) - SELECT id,decode(repeat('ff',32),'hex') FROM tenants", - ) - .execute(db.pool()) - .await - .unwrap(); - sqlx::query("ANALYZE delivery_log") - .execute(db.pool()) - .await - .unwrap(); - let pool = sqlx::postgres::PgPoolOptions::new() - .connect_with( - (*db.pool().connect_options()) - .clone() - .options([("plan_cache_mode", "force_generic_plan")]), - ) - .await - .unwrap(); - let db = crate::Db::from_pool(pool); - let mut opts = options(c, &alice); - opts.batch_size = 100; - for (mode, expected) in [ - (ExecutionMode::ReadOnly, 100), - (ExecutionMode::Delete, 100), - (ExecutionMode::Delete, 0), - ] { - let result = db - .user_deletion_store() - .run_message_batches(&opts, mode, None, &mut Vec::new()) - .await - .unwrap(); - assert_eq!(result.items, expected); - } - let events: i64 = sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1") - .bind(c.as_uuid()) - .fetch_one(db.pool()) - .await - .unwrap(); - assert_eq!(events, 0); - let logs: i64 = sqlx::query_scalar("SELECT count(*) FROM delivery_log WHERE community_id=$1") - .bind(c.as_uuid()) - .fetch_one(db.pool()) - .await - .unwrap(); - assert_eq!(logs, 500_000); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "requires Postgres"] -async fn historical_file_publications_and_late_delivery_copies_follow_source_scope() { - let (db, c, _, alice, bob) = setup().await; - let other = db - .ensure_configured_community(&format!("copies-{}.example", Uuid::new_v4())) - .await - .unwrap() - .id; - let source = EventBuilder::new(Kind::Custom(1063), "personal file description") - .sign_with_keys(&alice) - .unwrap(); - let survivor = EventBuilder::new(Kind::Custom(1063), "another publisher's description") - .sign_with_keys(&bob) - .unwrap(); - for community in [c, other] { - db.ensure_user(community, bob.public_key().as_bytes()) - .await - .unwrap(); - db.insert_event(community, &source, None).await.unwrap(); - db.insert_event(community, &survivor, None).await.unwrap(); - sqlx::query( - "INSERT INTO subscriptions(community_id,id,owner_pubkey) VALUES($1,'survivor',$2)", - ) - .bind(community.as_uuid()) - .bind(bob.public_key().as_bytes().as_slice()) - .execute(db.pool()) - .await - .unwrap(); - } - let (planned_tx, planned_rx) = tokio::sync::oneshot::channel(); - let (resume_tx, resume_rx) = std::sync::mpsc::channel(); - let store = db.user_deletion_store(); - let opts = options(c, &alice); - let task = tokio::spawn(async move { - let mut writer = PauseAfterPlan { - record: "delete_start", - line: Vec::new(), - planned: Some(planned_tx), - resume: resume_rx, - }; - store - .run_message_batches(&opts, ExecutionMode::Delete, None, &mut writer) - .await - }); - planned_rx.await.unwrap(); - for community in [c, other] { - for event in [&source, &survivor] { - sqlx::query("INSERT INTO delivery_log(community_id,subscription_id,event_id,error_message) VALUES($1,'survivor',$2,'copied payload')") - .bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()) - .execute(db.pool()).await.unwrap(); - } - } - resume_tx.send(()).unwrap(); - let error = task.await.unwrap().unwrap_err(); - assert!( - error.to_string().contains("new dependent records"), - "{error}" - ); - let exists: bool = - sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND id=$2)") - .bind(c.as_uuid()) - .bind(source.id.as_bytes().as_slice()) - .fetch_one(db.pool()) - .await - .unwrap(); - assert!( - exists, - "source must survive until all dependent logs can be planned" - ); - for mode in [ExecutionMode::ReadOnly, ExecutionMode::Delete] { - let result = db - .user_deletion_store() - .run_message_batches(&options(c, &alice), mode, None, &mut Vec::new()) - .await - .unwrap(); - assert_eq!(result.items, 2); - } - for (community, expected) in [(c, 1_i64), (other, 2)] { - for table in ["events", "delivery_log"] { - let count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( - "SELECT count(*) FROM {table} WHERE community_id=$1" - ))) - .bind(community.as_uuid()) - .fetch_one(db.pool()) - .await - .unwrap(); - assert_eq!(count, expected, "{table}"); - } - let subscriptions: i64 = - sqlx::query_scalar("SELECT count(*) FROM subscriptions WHERE community_id=$1") - .bind(community.as_uuid()) - .fetch_one(db.pool()) - .await - .unwrap(); - assert_eq!(subscriptions, 1); - } - let preserved: String = - sqlx::query_scalar("SELECT content FROM events WHERE community_id=$1 AND id=$2") - .bind(c.as_uuid()) - .bind(survivor.id.as_bytes().as_slice()) - .fetch_one(db.pool()) - .await - .unwrap(); - assert_eq!(preserved, survivor.content); - assert_eq!( - db.user_deletion_store() - .run_message_batches( - &options(c, &alice), - ExecutionMode::Delete, - None, - &mut Vec::new() - ) - .await - .unwrap() - .items, - 0 - ); -} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs index eef9cab3101..d4752e0a4aa 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs @@ -103,12 +103,10 @@ pub(super) fn selection(item: &Value) -> Result<(&'static str, &'static str)> { Some("push_match_queue") => ("push_match_queue", "event_id=decode($2->>'event_id','hex')"), Some("push_wake_outbox") => ("push_wake_outbox", "id=($2->>'id')::uuid"), Some("operator_listener_outbox") => ("operator_listener_outbox", "id=($2->>'id')::uuid"), - Some("delivery_log") => ("delivery_log", "id=($2->>'id')::bigint AND delivered_at=($2->>'delivered_at')::timestamptz"), Some("workflows") => ("workflows", "id=($2->>'id')::uuid"), Some("workflow_runs") => ("workflow_runs", "id=($2->>'id')::uuid"), Some("workflow_approvals") => ("workflow_approvals", "token=decode($2->>'token','hex')"), Some("scheduled_workflow_fires") => ("scheduled_workflow_fires", "workflow_id=($2->>'workflow_id')::uuid AND scheduled_for=($2->>'scheduled_for')::timestamptz"), - Some("subscriptions") => ("subscriptions", "id=$2->>'id'"), Some("push_leases") => ("push_leases", "author=decode($2->>'author','hex') AND installation_id=$2->>'installation_id'"), _ => return Err(invalid("unknown internal batch table")), }) diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/files_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/files_postgres_tests.rs new file mode 100644 index 00000000000..3e48f7ce054 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/content_batches/files_postgres_tests.rs @@ -0,0 +1,65 @@ +use super::scrub_postgres_tests::{options, setup}; +use super::*; +use crate::user_deletion::ExecutionMode; +use nostr::{EventBuilder, Kind}; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn historical_file_publications_follow_source_scope() { + let (db, c, _, alice, bob) = setup().await; + let other = db + .ensure_configured_community(&format!("files-{}.example", Uuid::new_v4())) + .await + .unwrap() + .id; + let source = EventBuilder::new(Kind::Custom(1063), "personal file description") + .sign_with_keys(&alice) + .unwrap(); + let survivor = EventBuilder::new(Kind::Custom(1063), "another publisher's description") + .sign_with_keys(&bob) + .unwrap(); + for community in [c, other] { + db.ensure_user(community, bob.public_key().as_bytes()) + .await + .unwrap(); + db.insert_event(community, &source, None).await.unwrap(); + db.insert_event(community, &survivor, None).await.unwrap(); + } + for mode in [ExecutionMode::ReadOnly, ExecutionMode::Delete] { + let result = db + .user_deletion_store() + .run_message_batches(&options(c, &alice), mode, None, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(result.items, 1); + } + for (community, expected) in [(c, 1_i64), (other, 2)] { + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1") + .bind(community.as_uuid()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(count, expected); + } + let preserved: String = + sqlx::query_scalar("SELECT content FROM events WHERE community_id=$1 AND id=$2") + .bind(c.as_uuid()) + .bind(survivor.id.as_bytes().as_slice()) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(preserved, survivor.content); + assert_eq!( + db.user_deletion_store() + .run_message_batches( + &options(c, &alice), + ExecutionMode::Delete, + None, + &mut Vec::new() + ) + .await + .unwrap() + .items, + 0 + ); +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs index 8e96de7f6bb..0a58c51c7e1 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs @@ -14,7 +14,7 @@ fn tables(batch: &Value) -> Result> { // A batch can straddle selection pages, with an event from the previous // page preceding the next page's side rows. Always remove dependants first. tables.sort_by_key(|table| match *table { - "subscriptions" | "push_leases" | "workflows" => 1, + "push_leases" | "workflows" => 1, "events" => 2, _ => 0, }); @@ -147,7 +147,6 @@ async fn children( table: &str, ) -> Result<()> { let dependent = match table { - "subscriptions" => "EXISTS(SELECT 1 FROM delivery_log WHERE community_id=$1 AND subscription_id=w.row_key->>'id')", "push_leases" => "EXISTS(SELECT 1 FROM push_wake_outbox WHERE community_id=$1 AND author=decode(w.row_key->>'author','hex') AND installation_id=w.row_key->>'installation_id')", "events" => "EXISTS(SELECT 1 FROM event_mentions WHERE community_id=$1 AND event_id=decode(w.row_key->>'id','hex')) OR EXISTS(SELECT 1 FROM push_match_queue WHERE community_id=$1 AND event_id=decode(w.row_key->>'id','hex')) @@ -167,23 +166,6 @@ async fn children( .bind(number) .fetch_one(&mut *conn) .await?; - // Delivery logs have no event-ID index. Probe the whole batch as a set so - // unrelated history is not scanned again for every selected event. IS TRUE - // keeps membership as a hashed subplan instead of a nested-loop semi join - // when tenant or temporary-worklist estimates are too small. - let remains = remains - || (table == "events" - && sqlx::query_scalar::<_, bool>( - "SELECT EXISTS(SELECT 1 FROM delivery_log d - WHERE d.community_id=$1 AND (d.event_id IN ( - SELECT decode(w.row_key->>'id','hex') FROM content_batch_work w - WHERE w.table_name=$2 AND w.batch=$3)) IS TRUE)", - ) - .bind(community) - .bind(table) - .bind(number) - .fetch_one(&mut *conn) - .await?); if remains { return Err(invalid( "new dependent records appeared; current batch rolled back; rerun to plan them", @@ -268,7 +250,6 @@ pub(super) async fn verify_remaining( let relay = start["trusted_relay_pubkey"].as_str(); let query = format!("WITH authored AS ({}) SELECT EXISTS(SELECT 1 FROM authored WHERE kind=ANY($4)) OR EXISTS(SELECT 1 FROM reactions WHERE community_id=$1 AND pubkey=ANY($2)) - OR EXISTS(SELECT 1 FROM subscriptions WHERE community_id=$1 AND owner_pubkey=ANY($2)) OR EXISTS(SELECT 1 FROM push_leases WHERE community_id=$1 AND author=ANY($2)) OR EXISTS(SELECT 1 FROM push_wake_outbox WHERE community_id=$1 AND author=ANY($2)) OR EXISTS(SELECT 1 FROM operator_listener_outbox WHERE community_id=$1 AND (target_pubkey=ANY($2) OR listener_pubkey=ANY($2)))",include_str!("authored.sql")); diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs index 039909a4be6..3a1fdf1a853 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs @@ -246,9 +246,9 @@ async fn plan( "excluded_agents": excluded_agents, "target_pubkeys": target_pubkeys, "trusted_relay_pubkey": relay, "included_event_kinds": KINDS, "batch_size": options.batch_size, "max_items": options.max_items, - "scope": "user- and owned-agent-attributed events (including persona, team, emoji and project definitions), trusted-relay private hidden-DM snapshots, reactions, owned subscriptions and notification delivery; unused owned workflows and recorded personal workflow inputs/notes", + "scope": "user- and owned-agent-attributed events (including persona, team, emoji and project definitions), trusted-relay private hidden-DM snapshots, reactions and notification delivery; unused owned workflows and recorded personal workflow inputs/notes", "hidden_dm_selection": "kind 30622 requires a trusted relay signer, no channel, and exactly one matching canonical d/p viewer; ambiguous or untrusted snapshots are not selected", - "preserved": "other users' events and reactions; member repositories; workflow history except recorded personal trigger inputs and approval notes; other owners' delivery logs unrelated to selected events", + "preserved": "other users' events and reactions; member repositories; workflow history except recorded personal trigger inputs and approval notes", "relay_attribution": if relay.is_some() { "enabled" } else { "not included; supply --relay-pubkey for relay-authored history" }, "execution": "preview only; --delete prints and commits batches after execution checks", "thread_repairs": "reported separately from row items; metadata mutations are not expanded", @@ -376,7 +376,7 @@ mod private_state_postgres_tests; mod workflow_postgres_tests; #[cfg(test)] -mod copies_postgres_tests; +mod files_postgres_tests; #[cfg(test)] mod schedule_postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs b/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs index c2055e49d59..c573ad02909 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs @@ -10,21 +10,6 @@ pub(super) async fn plan( let reason = json!({"type": "owned_resource"}); // Workflow state can contain another user's approvals or work. Leave it // intact in this initial ownership-only content pass. - rows( - conn, - output, - "delivery_log", - "SELECT jsonb_build_object('delivered_at',delivered_at,'id',id) AS row_key, - NULL::text AS warning FROM delivery_log WHERE community_id=$1 AND subscription_id IN - (SELECT id FROM subscriptions WHERE community_id=$1 AND owner_pubkey=ANY($2::bytea[]))", - targets, - &reason, - "would_delete", - ) - .await?; - rows(conn, output, "subscriptions", "SELECT jsonb_build_object('id',id) AS row_key, - NULL::text AS warning FROM subscriptions WHERE community_id=$1 AND owner_pubkey=ANY($2::bytea[])", - targets, &reason, "would_delete").await?; rows(conn, output, "push_wake_outbox", "SELECT jsonb_build_object('id',id) AS row_key, CASE WHEN lease_until>transaction_timestamp() THEN 'delivery worker is active' END AS warning FROM push_wake_outbox WHERE community_id=$1 AND author=ANY($2::bytea[])", diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs index 3f9ef7a1efb..e8dce7e25c7 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/postgres_tests.rs @@ -97,28 +97,6 @@ async fn preview_delete_and_retry_preserve_other_users_contributions() { .execute(&pool) .await .unwrap(); - for (name, author) in [ - ("alice-sub", &alice), - ("agent-sub", &agent), - ("bob-sub", &bob), - ] { - sqlx::query("INSERT INTO subscriptions (community_id,id,owner_pubkey) VALUES ($1,$2,$3)") - .bind(community.as_uuid()) - .bind(name) - .bind(author.public_key().as_bytes().as_slice()) - .execute(&pool) - .await - .unwrap(); - sqlx::query( - "INSERT INTO delivery_log (community_id,subscription_id,event_id) VALUES ($1,$2,$3)", - ) - .bind(community.as_uuid()) - .bind(name) - .bind(original.id.as_bytes().as_slice()) - .execute(&pool) - .await - .unwrap(); - } for event in std::iter::once(&original) .chain(authored.iter().skip(1)) .chain(&preserved) @@ -236,16 +214,6 @@ async fn preview_delete_and_retry_preserve_other_users_contributions() { .await .unwrap(); assert_eq!(reaction_authors, vec![bob.public_key().as_bytes().to_vec()]); - let deliveries: Vec = - sqlx::query_scalar("SELECT subscription_id FROM delivery_log WHERE community_id=$1") - .bind(community.as_uuid()) - .fetch_all(&pool) - .await - .unwrap(); - assert!( - deliveries.is_empty(), - "copies of the erased source must go too" - ); let reply_count: i32 = sqlx::query_scalar( "SELECT reply_count FROM thread_metadata WHERE community_id=$1 AND event_id=$2", ) diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs index dacda7b40fa..51e91ee4943 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/private_state_postgres_tests.rs @@ -58,14 +58,6 @@ async fn private_dm_snapshot_cleanup_checks_subject_signer_and_resumes_without_s let a = alice.public_key().to_hex(); let b = bob.public_key().to_hex(); let g = agent.public_key().to_hex(); - sqlx::query( - "INSERT INTO subscriptions (community_id,id,owner_pubkey) VALUES ($1,'surviving',$2)", - ) - .bind(community.as_uuid()) - .bind(bob.public_key().as_bytes().as_slice()) - .execute(db.pool()) - .await - .unwrap(); let mut selected = HashSet::new(); let cases = [ (&relay, vec![("d", &a), ("p", &a)], None, true), @@ -100,12 +92,6 @@ async fn private_dm_snapshot_cleanup_checks_subject_signer_and_resumes_without_s if delete { selected.insert(event.id.to_hex()); } - // Logs in either community and under a surviving subscription must - // follow only the selected private snapshot, not its claimed subject. - for c in [community, other] { - sqlx::query("INSERT INTO delivery_log (community_id,subscription_id,event_id,error_message) VALUES ($1,'surviving',$2,'historical private delivery')") - .bind(c.as_uuid()).bind(event.id.as_bytes().as_slice()).execute(db.pool()).await.unwrap(); - } if index == 0 { sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") .bind(community.as_uuid()) @@ -146,11 +132,9 @@ async fn private_dm_snapshot_cleanup_checks_subject_signer_and_resumes_without_s let tables = [ "events", "event_mentions", - "delivery_log", "channels", "channel_members", "users", - "subscriptions", ]; let mut before = Vec::new(); let mut foreign = Vec::new(); diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs b/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs index 70690908a7e..418bea35e4b 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/rows.rs @@ -81,19 +81,6 @@ pub(super) async fn event_rows( ) .await?; } - // Capture copies under surviving subscriptions before erasing the source. - rows( - conn, - output, - "delivery_log", - "SELECT jsonb_build_object('delivered_at',delivered_at,'id',id) AS row_key, - NULL::text AS warning FROM delivery_log - WHERE community_id=$1 AND event_id=ANY($2::bytea[])", - &ids, - &reason, - "would_delete", - ) - .await?; Ok(()) } diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs index de3d86a1646..f73066410db 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/scrub_postgres_tests.rs @@ -99,7 +99,7 @@ async fn batch_crossing_selection_pages_removes_side_rows_before_events() { let before = row(&db, c, &survivor).await; // This item offsets the event batches by one. Batch two starts with the // last event of page one, followed by page two's side row and event. - sqlx::query("INSERT INTO subscriptions (community_id,id,owner_pubkey) VALUES ($1,'offset',$2)") + sqlx::query("INSERT INTO push_leases (community_id,author,installation_id,source_event_id,source_created_at,generation,active,expires_at) VALUES ($1,$2,'offset',decode(repeat('00',32),'hex'),0,1,false,0)") .bind(c.as_uuid()) .bind(alice.public_key().as_bytes().as_slice()) .execute(db.pool()) diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs index 6255115b9ed..3548729ff5e 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs @@ -103,7 +103,6 @@ pub(super) async fn dependencies(conn: &mut PgConnection, scope: &Scope) -> Resu for (table, selector) in [ ("api_tokens","owner_pubkey=ANY($2::bytea[])"), ("workflows","owner_pubkey=ANY($2::bytea[])"), - ("subscriptions","owner_pubkey=ANY($2::bytea[])"), ("channel_members","pubkey=ANY($2::bytea[])"), ("relay_members","pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)"), ("events","pubkey=ANY($2::bytea[]) AND kind NOT IN (0,10100,30177,30179,9035,9036,30617,30618)"), diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs index 5d551cf0f33..6a195cbe440 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs @@ -63,7 +63,6 @@ pub(super) const CHILDREN: &[Table] = &[ Table { name:"push_match_queue", key:"jsonb_build_object('event_id',t.event_id)", identity:"event_id=($2->>'event_id')::bytea", selector:"t.event_id=ANY($3::bytea[])" }, Table { name:"push_wake_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" }, Table { name:"operator_listener_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" }, - Table { name:"delivery_log", key:"jsonb_build_object('id',t.id,'delivered_at',t.delivered_at)", identity:"id=($2->>'id')::bigint AND delivered_at=($2->>'delivered_at')::timestamptz", selector:"t.event_id=ANY($3::bytea[])" }, ]; pub(super) async fn collect( diff --git a/crates/buzz-deletion/src/lib.rs b/crates/buzz-deletion/src/lib.rs index d5076f719d2..40a584a44b5 100644 --- a/crates/buzz-deletion/src/lib.rs +++ b/crates/buzz-deletion/src/lib.rs @@ -1421,10 +1421,12 @@ fn validate_approved_schema( live: &buzz_db::deletion::SchemaManifest, frozen: &FrozenInventory, ) -> Result<()> { - // The approved catalog binds exactly, with one bounded exception: an + // 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. The - // frozen manifest and its digest are never rewritten. + // 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 + // and its digest are never rewritten. let frozen_tables = frozen .schema .scoped_tables @@ -1434,7 +1436,9 @@ fn validate_approved_schema( .scoped_tables .iter() .collect::>(); - let removed = !frozen_tables.is_subset(&live_tables); + let removed = frozen_tables + .difference(&live_tables) + .any(|table| !buzz_db::deletion::RETIRING_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())); @@ -1891,6 +1895,69 @@ 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. + #[test] + fn approved_schema_tolerates_only_retiring_tables_vanishing() { + use buzz_db::deletion::{SchemaManifest, EXPECTED_SCOPED_TABLES, RETIRING_SCOPED_TABLES}; + + let manifest = |tables: &[String]| SchemaManifest { + scoped_tables: tables.to_vec(), + row_counts: std::collections::BTreeMap::new(), + fenced_tables: Vec::new(), + }; + let required: Vec = EXPECTED_SCOPED_TABLES + .iter() + .map(|table| (*table).to_owned()) + .collect(); + let mut with_retiring = required.clone(); + with_retiring.extend( + RETIRING_SCOPED_TABLES + .iter() + .map(|table| (*table).to_owned()), + ); + let frozen = FrozenInventory { + schema: manifest(&with_retiring), + 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 + .iter() + .filter(|table| table.as_str() != *kept) + .cloned() + .collect(); + validate_approved_schema(&manifest(&partial), &frozen) + .expect("one retiring table dropped after approval"); + } + + // A required table that is gone is drift, with or without the + // retiring tables beside it. + for live in [&with_retiring, &required] { + let missing: Vec = live + .iter() + .filter(|table| table.as_str() != "workflows") + .cloned() + .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. + 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 { + schema: manifest(&required), + storage: frozen.storage.clone(), + }; + assert!(validate_approved_schema(&manifest(&with_retiring), &without_retiring).is_err()); + } + fn empty_storage_manifest(community: buzz_core::CommunityId) -> StorageManifest { StorageManifest { version: 4, @@ -2517,6 +2584,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"); + // 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]; @@ -2850,6 +2926,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. + /// 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")) @@ -2978,6 +3055,51 @@ mod postgres_tests { .await .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/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index 3d233bc25c9..b69a4e30d71 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -2751,18 +2751,16 @@ mod tests { assert_eq!(aggregate_audit_failures(&counters), 1); // Each per-table attempt, including the one inside maintenance, still has // its own error outcome. - for table in ["events", "delivery_log"] { - let errors: u64 = counters - .iter() - .filter(|(name, labels, _)| { - name == "buzz_partition_audit_runs_total" - && labels.contains(&("table".to_string(), table.to_string())) - && labels.contains(&("outcome".to_string(), "error".to_string())) - }) - .map(|(_, _, value)| value) - .sum(); - assert_eq!(errors, 2, "{table}"); - } + let errors: u64 = counters + .iter() + .filter(|(name, labels, _)| { + name == "buzz_partition_audit_runs_total" + && labels.contains(&("table".to_string(), "events".to_string())) + && labels.contains(&("outcome".to_string(), "error".to_string())) + }) + .map(|(_, _, value)| value) + .sum(); + assert_eq!(errors, 2, "events"); } #[test] diff --git a/crates/buzz-relay/src/metrics.rs b/crates/buzz-relay/src/metrics.rs index feaf1baeb09..1b105d925b8 100644 --- a/crates/buzz-relay/src/metrics.rs +++ b/crates/buzz-relay/src/metrics.rs @@ -1569,7 +1569,7 @@ mod partition_alert_tests { const RUNS: &str = "buzz_partition_audit_runs_total"; const LAST_SUCCESS: &str = "buzz_partition_audit_last_success_timestamp_seconds"; - const MANAGED_TABLES: [&str; 2] = ["delivery_log", "events"]; + const MANAGED_TABLES: [&str; 1] = ["events"]; /// Sample value by `table` label for every sample of `metric` in a scrape. /// Counters with several `outcome` labels keep the last sample per table. diff --git a/docs/database.md b/docs/database.md index 0da31197880..3fe2271714c 100644 --- a/docs/database.md +++ b/docs/database.md @@ -148,6 +148,19 @@ 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`. +#### 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. + #### Checklist: adding a provenance-only table A table whose `community_id` only records which community a row came from, and diff --git a/docs/operator-user-account-cleanup.md b/docs/operator-user-account-cleanup.md index 10147496f84..c136e3a2dec 100644 --- a/docs/operator-user-account-cleanup.md +++ b/docs/operator-user-account-cleanup.md @@ -57,7 +57,7 @@ Global mode and community mode are mutually exclusive. | Community | Target-owned tokens, created invitations, all channel/community memberships (including removed rows), policy acceptances, allowlist entries, read frontiers and read-account rows. Existing nullable attribution clears preserve other owners' records and revocation/removal state. | | Community feedback | Delete the target's submitted feedback in that community, including its body and tags. | | Personal events | Delete all stored versions, including soft-deleted revisions, of directly authored kinds **3, 10000, 10001, 10002, 10003, 10030, 30000, 30003, 30315, 30078**. These cover contacts, mute/pin/bookmark/follow lists, relay preferences, personal emoji lists, status and application/read state. | -| Personal-event copies | Before deleting source events, delete matching mention-index rows, push-match jobs, push-wake outbox rows, listener outbox rows and delivery logs in the same community. Other people's signed references and reactions are preserved. | +| Personal-event copies | Before deleting source events, delete matching mention-index rows, push-match jobs, push-wake outbox rows and listener outbox rows in the same community. Other people's signed references and reactions are preserved. | | Global | Delete the selected key's database operator/moderator role, listener registrations in either listener or target position, and submitted feedback across communities and with NULL community. | Role revocation and its audit row commit together using the existing roster @@ -128,7 +128,7 @@ relay-signed membership notices, infer device ownership, or prove repository owner/delegated access has been revoked. It does not delete shared emoji sets, profiles, messages, repository events or unknown personal event kinds. Those require their named handler or an attribution/reconciliation implementation. -Target notification subscriptions and push leases belong to content cleanup; +Target push leases belong to content cleanup; capture any device attribution before that handler removes the source links. The existing `archived_identities.replaced_by` clear is still present; moving it diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index 57ae30ebb53..abe65702acd 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -35,9 +35,8 @@ rows. DM conversations, other participants' preferences and encrypted message copies are not selected by this rule. Content cleanup also removes signed file-metadata publications (kind 1063), -without deleting referenced blobs. Delivery logs under surviving subscriptions -follow every selected source event, including events reduced to tombstones. -Mentions and pending delivery rows are removed before their source events. +without deleting referenced blobs. Mentions and pending delivery rows are +removed before their source events. Workflow cleanup deletes owned definitions with no runs, approvals or linked schedule history, removing each definition and its unused schedule claims in the same transaction. diff --git a/docs/partition-catalog-monitoring.md b/docs/partition-catalog-monitoring.md index 3759a191d59..a26545a65aa 100644 --- a/docs/partition-catalog-monitoring.md +++ b/docs/partition-catalog-monitoring.md @@ -1,6 +1,6 @@ # Partition catalog monitoring -The relay audits the `events` and `delivery_log` partition catalogs at startup +The relay audits the `events` partition catalog at startup and every `BUZZ_PARTITION_AUDIT_INTERVAL_SECS` (default 900 seconds). Results are diagnostic only. They appear in `/_status.partition_catalog` and in the metrics below, and they never change `/_readiness` or `/_liveness`. Alert on them; do not @@ -68,7 +68,7 @@ timestamp disappears only when audits stop running for longer than the idle timeout; the other per-table gauges can be evicted during sustained failures. Counters are not idle-evicted while the process runs. The relay exports every -run outcome for both managed tables, and the failure counter, at 0 when its +run outcome for each managed table, and the failure counter, at 0 when its metrics exporter starts, so `increase()` counts the first failure and the first run with a new outcome: diff --git a/docs/profile-cleanup.md b/docs/profile-cleanup.md index 11d33ddf713..6f46ce55396 100644 --- a/docs/profile-cleanup.md +++ b/docs/profile-cleanup.md @@ -60,7 +60,7 @@ a successful partial preview. SQL statements have a 30-second timeout and locks a three-second timeout; large accounts can require a separately reviewed plan. Before mutations, the command rejects remaining credentials, memberships, -workflows, subscriptions, non-profile authored content other than repository +workflows, non-profile authored content other than repository announcements/state (30617/30618), and unresolved archive references. Repository events and name mappings remain intact and do not block identity removal. It retains replay watermarks, deletion fences, requests, approvals,