diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 8a5c0879fa9..597331b9d4f 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -879,7 +879,19 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 101); + assert_eq!(migrations.len(), 104); + assert_eq!(migrations[103].version, 104); + let event_table_drops = strip_sql_comments(migrations[103].sql.as_str()); + assert!(event_table_drops + .contains("LOCK TABLE events, delivery_log, communities IN ACCESS EXCLUSIVE MODE;")); + assert!(event_table_drops.contains("DROP CONSTRAINT events_community_id_fkey;")); + assert_eq!(migrations[102].version, 103); + assert!(strip_sql_comments(migrations[102].sql.as_str()) + .contains("ALTER TABLE users DROP CONSTRAINT users_community_id_fkey;")); + assert_eq!(migrations[101].version, 102); + assert!(strip_sql_comments(migrations[101].sql.as_str()).contains( + "ALTER TABLE join_policy_acceptances DROP CONSTRAINT join_policy_acceptances_community_id_pubkey_fkey;" + )); assert_eq!(migrations[100].version, 101); assert!(strip_sql_comments(migrations[100].sql.as_str()) .contains("DROP CONSTRAINT IF EXISTS push_gateway_delegations_installation_id_fkey")); @@ -1843,6 +1855,23 @@ mod postgres_tests { ); } + /// pgschema cannot drop a foreign key from a partitioned table, so the + /// launcher that reuses its database drops those keys before apply. + #[test] + fn partitioned_foreign_key_drop_runs_before_reused_apply() { + let launcher = include_str!("../../../../scripts/start-relay-for-tests.sh"); + let drop_at = launcher + .find("scripts/drop-partitioned-foreign-keys.sql") + .expect("start-relay-for-tests.sh runs scripts/drop-partitioned-foreign-keys.sql"); + let apply_at = launcher + .find("./bin/pgschema apply") + .expect("start-relay-for-tests.sh runs pgschema apply"); + assert!( + drop_at < apply_at, + "start-relay-for-tests.sh must drop the partitioned foreign keys before pgschema apply" + ); + } + /// The reconcile script repairs `events_pkey` after every apply, and /// `start-relay-for-tests.sh` runs the same repair before apply so a reused /// database reconciled before the repair existed can still be applied. @@ -2440,6 +2469,41 @@ mod postgres_tests { strings } + /// Drop foreign-key elements and inline `REFERENCES` clauses from a + /// normalized `CREATE TABLE`. + fn without_foreign_keys(table: &str) -> String { + let open = table.find('(').expect("table body"); + let close = find_matching_paren(table, open).expect("table body end"); + let elements: Vec = split_top_level_csv(&table[open + 1..close]) + .into_iter() + .filter(|element| !element.starts_with("foreign key")) + .map(|element| { + let Some(start) = element.find(" references ") else { + return element; + }; + let paren = start + element[start..].find('(').expect("referenced columns"); + let mut end = find_matching_paren(&element, paren).expect("columns end") + 1; + for action in [ + " on delete cascade", + " on delete set null", + " on delete restrict", + " on delete no action", + ] { + if element[end..].starts_with(action) { + end += action.len(); + } + } + format!("{}{}", &element[..start], &element[end..]) + }) + .collect(); + format!( + "{}({}){}", + &table[..open], + elements.join(", "), + &table[close + 1..] + ) + } + fn surface(sql: &str) -> DeletionSurface { let mut surface = DeletionSurface::default(); for statement in split_sql_statements(sql) { @@ -2511,9 +2575,11 @@ mod postgres_tests { .tables .get(table) .unwrap_or_else(|| panic!("schema.sql is missing deletion table {table}")); + // 0102-0104 dropped every foreign key; the rest must not drift. if table != "community_deletion_requests" && table != "community_deletion_approvals" { assert_eq!( - in_schema, definition, + without_foreign_keys(in_schema), + without_foreign_keys(definition), "schema.sql definition of {table} drifted from migration 0029" ); } @@ -2526,19 +2592,15 @@ mod postgres_tests { .tables .get("community_deletion_approvals") .expect("schema.sql approval table"); - for invariant in [ - "inventory_digest bytea not null check (length(inventory_digest) = 32)", - "foreign key (request_id, community_id, inventory_digest) references community_deletion_requests(id, community_id, inventory_digest) on delete restrict", - ] { - assert!( - migration_approval_table.contains(invariant), - "0029 deletion approvals are missing {invariant}" - ); - assert!( - schema_approval_table.contains(invariant), - "schema.sql deletion approvals are missing {invariant}" - ); - } + let invariant = "inventory_digest bytea not null check (length(inventory_digest) = 32)"; + assert!( + migration_approval_table.contains(invariant), + "0029 deletion approvals are missing {invariant}" + ); + assert!( + schema_approval_table.contains(invariant), + "schema.sql deletion approvals are missing {invariant}" + ); let migration_request_table = migration .tables .get("community_deletion_requests") @@ -2668,13 +2730,17 @@ mod postgres_tests { .as_str(); assert!(through_message.contains("DROP COLUMN threads_through_timestamp")); for (table, definition) in personal.tables { + // `without_foreign_keys` also normalizes spacing, so apply it to both. let in_schema = schema.tables.get(&table).map(|schema_definition| { + let schema_definition = without_foreign_keys(schema_definition); if table == "personal_read_accounts" { schema_definition.replacen(started_at_column, "", 1) } else { - schema_definition.clone() + schema_definition } }); + // 0102 dropped the foreign keys that 0056 created. + let definition = without_foreign_keys(&definition); let definition = if table == "personal_read_frontiers" { definition.replacen(threads_through_column, through_message_column, 1) } else { @@ -3152,6 +3218,30 @@ mod postgres_tests { migration and schema.sql must both use a representable shape." ); } + // docs/database.md Rule 2: 0102-0104 dropped every foreign key, and + // schema/ declares none, so neither bootstrap path has one. + async fn foreign_keys(pool: &PgPool) -> Vec<(String, String)> { + sqlx::query_as( + "SELECT con.conrelid::regclass::text, con.conname::text \ + FROM pg_constraint con \ + JOIN pg_namespace n ON n.oid = con.connamespace \ + WHERE n.nspname = 'public' AND con.contype = 'f' \ + ORDER BY 1, 2", + ) + .fetch_all(pool) + .await + .expect("read foreign keys") + } + assert_eq!( + foreign_keys(&desired).await, + Vec::new(), + "desired state has a foreign key" + ); + assert_eq!( + foreign_keys(&migrated).await, + Vec::new(), + "migrations leave a foreign key" + ); async fn media_edit_index(pool: &PgPool) -> (String, String, String) { sqlx::query_as("SELECT pg_get_indexdef(indexrelid),indoption::text,pg_get_expr(indexprs,indrelid) FROM pg_index WHERE indexrelid='public.idx_events_media_edit_target'::regclass AND indisvalid AND indisready AND indislive") .fetch_one(pool).await.expect("valid media edit index") diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index 233660c9d61..c294c9f0271 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -1375,8 +1375,8 @@ async fn lock_channel_row( lock_channel_ttl(tx, channel_id, ttl).await?; // `FOR NO KEY UPDATE`, like a huddle join: it orders this write against // every other settings write and a huddle join, but not against a - // `KEY SHARE` lock on the channel (a membership INSERT's foreign key while - // it exists, `insert_auto_membership`'s channel check). + // `KEY SHARE` lock on the channel (`insert_auto_membership`'s channel + // check). let (previous_visibility, archived, listed): (String, bool, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!( "SELECT visibility::text, archived_at IS NOT NULL, {LISTED_CHANNEL_SQL} FROM channels \ diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 64dfd3bc670..00d89ddb0b5 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -307,8 +307,8 @@ pub async fn lock_channel_memberships_in_transaction<'tx>( /// rolls back, so a join cannot commit into a channel archived concurrently. /// `FOR UPDATE` would invert the lock order against a membership writer that /// key-share locks `channels` after taking the advisory membership lock -/// ([`ChannelMembershipLocks::insert_auto_membership`]'s channel check, and a -/// membership INSERT's foreign key while it exists); `FOR NO KEY UPDATE` still +/// ([`ChannelMembershipLocks::insert_auto_membership`]'s channel check); +/// `FOR NO KEY UPDATE` still /// blocks archive (a non-key update) and a delete, but is compatible with /// `KEY SHARE`. Re-reading under the lock is safe: the caller already holds it. pub async fn lock_channel_archived_at_in_transaction( diff --git a/crates/buzz-db/src/store/community.rs b/crates/buzz-db/src/store/community.rs index 5d01ae30ad8..a7cbead4113 100644 --- a/crates/buzz-db/src/store/community.rs +++ b/crates/buzz-db/src/store/community.rs @@ -823,7 +823,7 @@ impl Db { /// Locks the community row before reading ownership so a concurrent owner /// transfer, whose `FOR NO KEY UPDATE` conflicts with this one, has one /// serial order with the archive. The weaker lock lets the archive - /// proceed past foreign-key child inserts' `FOR KEY SHARE`. A single + /// proceed past reference checks' `FOR KEY SHARE`. A single /// `UPDATE ... FROM relay_members` would keep its pre-lock ownership /// snapshot after waiting and could archive the new owner's community on /// the old owner's assertion. @@ -1601,8 +1601,8 @@ mod postgres_tests { .expect("restored community state")); } - /// Foreign-key child inserts hold `FOR KEY SHARE` on the community row for - /// their whole transaction. Archive and the lifecycle fences must not queue + /// Reference checks hold `FOR KEY SHARE` on the community row for their + /// whole transaction. Archive and the lifecycle fences must not queue /// behind them, or a busy community stalls the operator archive and /// revalidation and conn-control on every pod. `FOR UPDATE` would block /// here; `FOR NO KEY UPDATE` must not. diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 490d53cf6ad..1e54275d81f 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -70,8 +70,7 @@ pub const CONTROL_PLANE_TABLES: &[&str] = &[ /// Each entry is `(table, row source)`; the row source binds the community as /// `$1` and is prefixed with `DELETE`, `SELECT count(*)`, or `SELECT EXISTS`. /// Rows go child before parent: outbox rows before their actions, and both -/// before `moderation_reports`. That order also satisfies the foreign keys -/// while they exist; it is not needed once they are dropped. +/// before `moderation_reports`. pub const RELAY_ADMIN_TABLES: &[(&str, &str)] = &[ ( "relay_admin_outbox", @@ -171,10 +170,9 @@ const EXCLUDED_SCOPED_TABLES: &[&str] = &[ "operator_listener_outbox", ]; -/// Tables the PostgreSQL purge deletes from, child before parent. The order -/// satisfies the foreign keys while they exist; once they are dropped it does -/// not matter, but the list must stay complete ([`EXPECTED_SCOPED_TABLES`] -/// gates it). +/// Tables the PostgreSQL purge deletes from, child before parent. No foreign +/// key needs the order, but the list must stay complete +/// ([`EXPECTED_SCOPED_TABLES`] gates it). pub const PURGE_SCOPED_TABLES: &[&str] = &[ "nip_fi_profile_heads", "personal_read_frontiers", @@ -917,7 +915,7 @@ impl DeletionStore { } let mut tx = self.pool.begin().await?; // Keep resolution and admission together, including when a caller pins - // the immutable ID. NO KEY UPDATE permits the legacy request FK check. + // the immutable ID. NO KEY UPDATE permits `FOR KEY SHARE` reference checks. let target: Option = sqlx::query_scalar( "SELECT id FROM communities WHERE ($1::text IS NULL OR lower(host) = lower($1)) @@ -7461,20 +7459,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); assert_eq!(current_schema.scoped_tables, inventory.schema.scoped_tables); assert_eq!(current_schema.fenced_tables, inventory.schema.fenced_tables); - let mismatched_insert = sqlx::query( - "INSERT INTO community_deletion_approvals \ - (request_id, community_id, inventory_digest, approved_by) \ - VALUES ($1, $2, $3, 'tampered')", - ) - .bind(request.id) - .bind(*request.community_id.as_uuid()) - .bind(vec![0_u8; 32]) - .execute(&db.pool) - .await; - assert!( - mismatched_insert.is_err(), - "a mismatched approval must be unrepresentable" - ); let approved = store .approve(request.id, "approver-a", Some("reviewed")) .await @@ -7494,43 +7478,81 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); approved.inventory_digest, Some(hex::encode(inventory.digest().unwrap())) ); - let mismatched_approval = sqlx::query( + // No foreign key binds the approval to the request digest. Every claim + // and lease check joins on it instead, so a tampered digest on either + // side grants nothing. + let digest = inventory.digest().unwrap(); + let tampers = [ "UPDATE community_deletion_approvals SET inventory_digest = $2 WHERE request_id = $1", - ) - .bind(request.id) - .bind(vec![0_u8; 32]) - .execute(&db.pool) - .await; - assert!( - mismatched_approval.is_err(), - "approval digest must remain database-bound to the frozen request digest" - ); - // PostgreSQL sends this rejection before it rolls the statement back - // and releases the request row lock, and sqlx returns on the error. - // The claim below uses SKIP LOCKED on another pooled connection, so - // finish a round trip on this connection before claiming. - let mut tamper_conn = db.pool.acquire().await.expect("acquire tamper connection"); - let mismatched_request = sqlx::query( "UPDATE community_deletion_requests SET inventory_digest = $2 WHERE id = $1", - ) - .bind(request.id) - .bind(vec![1_u8; 32]) - .execute(&mut *tamper_conn) - .await; - assert!( - mismatched_request.is_err(), - "the frozen request digest must remain bound to its approval" - ); - sqlx::query("SELECT 1") - .execute(&mut *tamper_conn) - .await - .expect("rejected update has rolled back"); - drop(tamper_conn); - assert!(store + ]; + let set_digest = |sql: &'static str, value: Vec| { + sqlx::query(sql) + .bind(request.id) + .bind(value) + .execute(&db.pool) + }; + for sql in tampers { + set_digest(sql, vec![0_u8; 32]) + .await + .expect("tamper digest"); + assert!( + store + .claim_specific(request.id, "executor-a", DEFAULT_LEASE_DURATION) + .await + .expect("claim with a mismatched digest") + .is_none(), + "a mismatched digest must not authorize a claim: {sql}" + ); + set_digest(sql, digest.clone()) + .await + .expect("restore digest"); + } + let claim = store .claim_specific(request.id, "executor-a", DEFAULT_LEASE_DURATION) .await .expect("claim approved") - .is_some()); + .expect("matching digests authorize a claim"); + + // An executor that already holds the lease loses it the same way, and + // the failed calls leave the lease and stage as they were. + for sql in tampers { + let held = store.get(request.id).await.expect("held lease"); + set_digest(sql, vec![0_u8; 32]) + .await + .expect("tamper digest"); + assert!( + store + .heartbeat(&claim.lease, "worker", DEFAULT_LEASE_DURATION, false) + .await + .is_err(), + "a mismatched digest must not renew a lease: {sql}" + ); + assert!( + store + .verify_execution_token(&claim.lease, DeletionStage::Approved) + .await + .is_err(), + "a mismatched digest must not keep a lease valid: {sql}" + ); + let after = store.get(request.id).await.expect("lease after rejection"); + assert_eq!( + (after.stage, after.lease_generation, after.lease_until), + (held.stage, held.lease_generation, held.lease_until), + "{sql}" + ); + set_digest(sql, digest.clone()) + .await + .expect("restore digest"); + store + .verify_execution_token(&claim.lease, DeletionStage::Approved) + .await + .expect("restored digest keeps the lease valid"); + store + .heartbeat(&claim.lease, "worker", DEFAULT_LEASE_DURATION, false) + .await + .expect("restored digest renews the lease"); + } } #[tokio::test] @@ -8947,7 +8969,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[ignore = "requires Postgres"] async fn manifest_key_chunks_bind_freeze_execution_and_cleanup() { let (db, store) = store().await; - crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; let (request, inventory) = inventoried_request(&db, &store).await; store .approve(request.id, "approver", None) @@ -9080,7 +9101,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); #[ignore = "requires Postgres"] async fn purge_removes_fk_children_explicitly_without_fk_actions() { let (db, store) = store().await; - crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; let (request, inventory) = inventoried_request(&db, &store).await; let community = request.community_id; let owner = vec![7_u8; 32]; diff --git a/crates/buzz-db/src/store/product_feedback.rs b/crates/buzz-db/src/store/product_feedback.rs index 715660ad8ac..78209579281 100644 --- a/crates/buzz-db/src/store/product_feedback.rs +++ b/crates/buzz-db/src/store/product_feedback.rs @@ -59,9 +59,8 @@ pub struct ProductFeedbackRecord { /// changing its source community; callers intentionally receive the same /// successful acknowledgment in both cases. /// -/// The community must exist, and nothing is written when it does not: while -/// the foreign key to `communities` exists it rejects the insert first, and -/// once the key is dropped this returns [`DbError::NotFound`]. Any lifecycle +/// The community must exist, and nothing is written when it does not: this +/// returns [`DbError::NotFound`]. Any lifecycle /// state qualifies: the table is provenance-only /// and unfenced (`docs/database.md`), so feedback stays writable while its /// community is being deleted, and the purge clears its provenance. @@ -94,7 +93,7 @@ pub async fn insert( .fetch_one(&mut *tx) .await?; let id = row.try_get("id")?; - // Check after the write, as the foreign key did: the purge locks feedback + // Check after the write: the purge locks feedback // rows before the community, so taking the community first would deadlock // with a replay that overlaps it. crate::store::reference_check::require_community(&mut tx, community).await?; @@ -232,11 +231,6 @@ mod postgres_tests { let pool = PgPool::connect(&crate::test_support::database_url()) .await .expect("connect test database"); - crate::test_support::drop_foreign_keys_between( - &pool, - &[("product_feedback", "communities")], - ) - .await; pool } @@ -342,8 +336,8 @@ mod postgres_tests { /// The check holds `FOR KEY SHARE` on the community row, so a concurrent /// delete of that row (which locks it `FOR UPDATE` first) and the insert - /// are ordered. With the foreign key dropped, only the explicit lock can - /// block the insert behind a community held `FOR UPDATE`. + /// are ordered. No foreign key exists, so only the explicit lock can block + /// the insert behind a community held `FOR UPDATE`. #[tokio::test] #[ignore = "requires Postgres"] async fn insert_key_share_locks_community_without_foreign_key() { diff --git a/crates/buzz-db/src/store/reference_check.rs b/crates/buzz-db/src/store/reference_check.rs index 4019c996584..7ebc7ca2d4e 100644 --- a/crates/buzz-db/src/store/reference_check.rs +++ b/crates/buzz-db/src/store/reference_check.rs @@ -4,8 +4,8 @@ //! Each helper locks the parent row `FOR KEY SHARE`: the lock a foreign key's //! check takes, so a concurrent delete of the parent (which locks it //! `FOR UPDATE` first) either waits for the writing transaction or runs first -//! and makes the check fail. While the foreign keys still exist the two checks -//! are idempotent; once they are dropped these checks are the only guard. +//! and makes the check fail. The foreign keys are dropped (migrations +//! 0102-0104), so these checks are the only guard. //! //! A missing parent is `DbError::NotFound`, never a silent success. Every //! lookup below the community is scoped by `community_id`, so a parent that diff --git a/crates/buzz-db/src/store/reference_check_postgres_tests.rs b/crates/buzz-db/src/store/reference_check_postgres_tests.rs index 4aad4068209..923cd356e14 100644 --- a/crates/buzz-db/src/store/reference_check_postgres_tests.rs +++ b/crates/buzz-db/src/store/reference_check_postgres_tests.rs @@ -1,7 +1,6 @@ //! Writers that name a channel or a user reject a missing parent in -//! application code. Each test drops the foreign keys it covers from the -//! per-test database first, so a pass proves the in-transaction check rather -//! than the constraint. +//! application code. The schema has no foreign keys, so a pass proves the +//! in-transaction check. //! //! The relay-member references (join-policy acceptances) are covered next to //! the removal path they race, in `relay_members.rs`. @@ -82,8 +81,6 @@ fn assert_not_found(result: Result, what: &str) { #[ignore = "requires Postgres"] async fn insert_auto_membership_rejects_missing_channel_without_foreign_key() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("channel_members", "channels")]) - .await; let member = [0x41; 32]; let creator = [0x42; 32]; let other = new_community(&db).await; @@ -191,7 +188,7 @@ async fn lock_channel_archived_at_distinguishes_missing_from_not_archived() { #[tokio::test] #[ignore = "requires Postgres"] -async fn set_agent_owner_rejects_missing_owner_with_and_without_foreign_key() { +async fn set_agent_owner_rejects_missing_owner_without_foreign_key() { let (db, community) = setup().await; let agent = [0x51; 32]; let owner = [0x52; 32]; @@ -209,22 +206,11 @@ async fn set_agent_owner_rejects_missing_owner_with_and_without_foreign_key() { .expect("read owner") }; - // With the owner foreign key intact the contract is the same: the check - // runs before the UPDATE, so a missing owner is `NotFound` rather than a - // foreign key violation, and the agent keeps no owner. - assert_not_found( - set_agent_owner(&db.pool, community, &agent, &owner).await, - "owner", - ); - assert_eq!(stored_owner(db.pool.clone(), agent).await, None); assert_not_found( set_agent_owner(&db.pool, community, &[0x53; 32], &owner).await, "agent pubkey", ); - // Now the foreign key is gone and the application check stands alone. - crate::test_support::drop_foreign_keys_between(&db.pool, &[("users", "users")]).await; - // Unknown owner: refused, and the agent keeps no owner. assert_not_found( set_agent_owner(&db.pool, community, &agent, &owner).await, @@ -299,8 +285,6 @@ fn thread_meta(event: &nostr::Event, channel: Uuid) -> crate::event::ThreadMetad #[ignore = "requires Postgres"] async fn thread_metadata_writers_reject_missing_channel_without_foreign_key() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("thread_metadata", "channels")]) - .await; let keys = nostr::Keys::generate(); let other = new_community(&db).await; let elsewhere = new_channel(&db, other).await; @@ -429,8 +413,6 @@ fn new_action(channel_id: Option) -> crate::moderation::NewAction<'static> #[ignore = "requires Postgres"] async fn moderation_report_rejects_missing_channel_without_foreign_key() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("moderation_reports", "channels")]) - .await; let other = new_community(&db).await; let elsewhere = new_channel(&db, other).await; @@ -492,8 +474,6 @@ async fn moderation_report_rejects_missing_channel_without_foreign_key() { #[ignore = "requires Postgres"] async fn moderation_action_rejects_missing_channel_without_foreign_key() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("moderation_actions", "channels")]) - .await; let other = new_community(&db).await; let elsewhere = new_channel(&db, other).await; @@ -541,8 +521,6 @@ async fn report_state(db: &Db, community: CommunityId, id: Uuid) -> (String, Opt #[ignore = "requires Postgres"] async fn report_resolution_writers_reject_missing_channel_without_foreign_key() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("moderation_actions", "channels")]) - .await; let actor = [0x71; 32]; let target = [0x72; 32]; let missing = Uuid::new_v4(); @@ -650,8 +628,6 @@ async fn report_resolution_writers_reject_missing_channel_without_foreign_key() #[ignore = "requires Postgres"] async fn direct_action_claim_rejects_missing_channel_without_foreign_key() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("moderation_actions", "channels")]) - .await; let actor = [0x81; 32]; let author = [0x82; 32]; let event_id = [0x83; 32]; @@ -697,18 +673,13 @@ async fn direct_action_claim_rejects_missing_channel_without_foreign_key() { // -- Lock tests --------------------------------------------------------------- /// The channel and owner checks hold `FOR KEY SHARE` on the parent rows, so a -/// concurrent delete or key update of a parent waits for the writer. The -/// foreign keys are dropped, so only the explicit lock can block the writer -/// behind a parent held `FOR UPDATE`. +/// concurrent delete or key update of a parent waits for the writer. No foreign +/// key exists, so only the explicit lock can block the writer behind a parent +/// held `FOR UPDATE`. #[tokio::test] #[ignore = "requires Postgres"] async fn reference_checks_key_share_lock_parents_without_foreign_keys() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[("moderation_actions", "channels"), ("users", "users")], - ) - .await; let channel = new_channel(&db, community).await; let agent = [0x91; 32]; let owner = [0x92; 32]; diff --git a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs index a85ddc48f8b..ae33ae0ab2d 100644 --- a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs +++ b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs @@ -646,6 +646,13 @@ async fn migration_schema_desired_pgschema_reconcile_matches_populated_upgrade() // Existing partitioned tables require the operator prebuild before pgschema, // which otherwise tries unsupported CREATE INDEX CONCURRENTLY on the parent. crate::test_support::prebuild_media_edit_index(&pool).await; + // pgschema cannot drop the partitioned tables' foreign keys itself. + sqlx::raw_sql(include_str!( + "../../../../../scripts/drop-partitioned-foreign-keys.sql" + )) + .execute(&pool) + .await + .unwrap(); apply_pgschema_to_existing_database(&pool).await; assert_admission_column(&pool).await; assert_join_role_preserved(&pool, cases[0].community).await; diff --git a/crates/buzz-db/src/store/relay_members.rs b/crates/buzz-db/src/store/relay_members.rs index 7a7ea60e806..87f1be59a1b 100644 --- a/crates/buzz-db/src/store/relay_members.rs +++ b/crates/buzz-db/src/store/relay_members.rs @@ -508,7 +508,7 @@ async fn lock_owner_mutation_admission( crate::deletion::lock_community_deletion_shared(tx, community).await?; // `FOR NO KEY UPDATE` still serializes with archive (`FOR NO KEY UPDATE`), // unarchive and deletion admission (`FOR UPDATE`), but not with the - // `FOR KEY SHARE` that every foreign-key child insert takes. A membership + // `FOR KEY SHARE` that reference checks take. A membership // writer holding a member row or the list lock inserts its kind:13534 // list into `events` last, so `FOR UPDATE` here would deadlock with it. let target = sqlx::query( @@ -1075,10 +1075,7 @@ impl MembershipWrite { /// changes `relay_members`, so the list commits or rolls back with the change. /// The per-community list lock is the last explicit lock: every other lock a /// membership transaction takes comes first, so the final writer reads every -/// committed change. While `events.community_id`'s foreign key exists, the -/// list insert also takes `FOR KEY SHARE` on the community row; owner -/// mutations lock that row `FOR NO KEY UPDATE`, which doesn't conflict, so no -/// lock cycle forms. `created_at` is at least one second +/// committed change. `created_at` is at least one second /// past every earlier list's, so the id is new and a client replacing by /// timestamp never keeps an older list from the same second. A burst of /// changes runs the timestamp ahead of the clock by up to one second per @@ -1813,14 +1810,12 @@ mod postgres_tests { .expect("count acceptances") } - /// Both removal paths delete acceptance evidence themselves: with every - /// foreign-key delete action retired, nothing cascades. Owners and a role - /// mismatch keep theirs. + /// Both removal paths delete acceptance evidence themselves: no foreign + /// key cascades. Owners and a role mismatch keep theirs. #[tokio::test] #[ignore = "requires Postgres"] async fn member_removal_deletes_acceptances_without_cascades() { let pool = setup_pool().await; - crate::test_support::retire_foreign_key_delete_actions(&pool).await; let (community, owner) = owned_community(&pool).await; let version = "a".repeat(64); sqlx::query( @@ -1899,20 +1894,13 @@ mod postgres_tests { /// An acceptance inserted concurrently with the removal holds the member /// row's key-share lock (taken by the acceptance writer's own member - /// check; the acceptance foreign key is dropped here, so the lock is not - /// the constraint's). Removal must wait for it at its row lock and then + /// check; no foreign key takes it). Removal must wait for it at its row lock and then /// delete it; a removal that took its child snapshot first would leave the /// acceptance behind with no member. #[tokio::test] #[ignore = "requires Postgres"] async fn member_removal_waits_for_and_removes_concurrent_acceptance() { let pool = setup_pool().await; - crate::test_support::retire_foreign_key_delete_actions(&pool).await; - crate::test_support::drop_foreign_keys_between( - &pool, - &[("join_policy_acceptances", "relay_members")], - ) - .await; let (community, _owner) = owned_community(&pool).await; let member = test_pubkey(); claim_relay_membership( @@ -2145,12 +2133,6 @@ mod postgres_tests { #[ignore = "requires Postgres"] async fn cascade_waits_for_and_removes_owned_agent_concurrent_acceptance() { let pool = setup_pool().await; - crate::test_support::retire_foreign_key_delete_actions(&pool).await; - crate::test_support::drop_foreign_keys_between( - &pool, - &[("join_policy_acceptances", "relay_members")], - ) - .await; let (community, _owner) = owned_community(&pool).await; let (human, agent) = (test_pubkey(), test_pubkey()); add_with_acceptance(&pool, community, &human, "member").await; @@ -3062,7 +3044,7 @@ mod postgres_tests { /// A list repair that holds the list lock while a transfer waits on it /// still inserts its list: the transfer's community row lock doesn't - /// block the insert's foreign-key `FOR KEY SHARE`, so both commit. + /// block the insert, so both commit. #[tokio::test] #[ignore = "requires Postgres"] async fn owner_transfer_and_list_repair_both_commit() { @@ -3203,7 +3185,7 @@ mod postgres_tests { /// A membership claim whose insert hit a conflict (the member already /// exists) locks nothing on its own. It must lock the member row before it - /// writes the acceptance: with the acceptance foreign key dropped, a + /// writes the acceptance: with no foreign key, a /// removal that locked the member `FOR UPDATE`, deleted its acceptances and /// then the member would otherwise commit before the claim's acceptance /// lands, leaving an acceptance with no member. The claim refuses instead. @@ -3211,11 +3193,6 @@ mod postgres_tests { #[ignore = "requires Postgres"] async fn membership_claim_racing_member_removal_leaves_no_orphan_acceptance() { let pool = setup_pool().await; - crate::test_support::drop_foreign_keys_between( - &pool, - &[("join_policy_acceptances", "relay_members")], - ) - .await; let (community, _owner) = owned_community(&pool).await; let member = test_pubkey(); let keys = nostr::Keys::generate(); @@ -3282,11 +3259,6 @@ mod postgres_tests { #[ignore = "requires Postgres"] async fn invite_claim_racing_member_removal_rejoins_without_orphan_acceptance() { let pool = setup_pool().await; - crate::test_support::drop_foreign_keys_between( - &pool, - &[("join_policy_acceptances", "relay_members")], - ) - .await; let (community, owner) = owned_community(&pool).await; let member = test_pubkey(); let keys = nostr::Keys::generate(); @@ -3356,18 +3328,13 @@ mod postgres_tests { /// then hits `ON CONFLICT DO NOTHING`, which locks nothing, so the claim /// must lock the member row before it writes the acceptance. The claim is /// paused before the INSERT while the member is added and a removal - /// takes the member `FOR UPDATE`; with the acceptance foreign key dropped - /// the claim then waits on that lock, and once the removal commits it + /// takes the member `FOR UPDATE`; with no foreign key, the claim then + /// waits on that lock, and once the removal commits it /// refuses with no acceptance, no orphan and no invite use consumed. #[tokio::test] #[ignore = "requires Postgres"] async fn invite_claim_conflicting_with_a_member_added_mid_claim_waits_for_removal() { let pool = setup_pool().await; - crate::test_support::drop_foreign_keys_between( - &pool, - &[("join_policy_acceptances", "relay_members")], - ) - .await; let (community, owner) = owned_community(&pool).await; let member = test_pubkey(); let keys = nostr::Keys::generate(); diff --git a/crates/buzz-db/src/store/user.rs b/crates/buzz-db/src/store/user.rs index 1b7b5cf2000..8f1acd59ef1 100644 --- a/crates/buzz-db/src/store/user.rs +++ b/crates/buzz-db/src/store/user.rs @@ -382,9 +382,8 @@ async fn set_agent_owner_with_operation( // Lock order: admission, then the agent row, then the owner row. The agent // row is read `FOR NO KEY UPDATE` (the lock the UPDATE below takes), so the // outcomes below are decided on a row nothing else can change, and the - // owner is checked before the UPDATE: with the owner foreign key still - // installed the UPDATE itself would fail on a missing owner with a foreign - // key error instead of the `NotFound` this function promises. + // owner is checked before the UPDATE, so a missing owner is the `NotFound` + // this function promises. let locked: Option>> = sqlx::query_scalar( "SELECT agent_owner_pubkey FROM users \ WHERE community_id = $1 AND pubkey = $2 FOR NO KEY UPDATE", diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships.rs b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships.rs index 5f9fdf28e20..b90a9210b3f 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships.rs @@ -64,6 +64,16 @@ impl UserDeletionStore { .ok_or_else(|| invalid("missing relay signing key"))?; check_signer(tx.conn(), community, signer).await?; batch(writer, options, op, &keys, summary)?; + // The member row is locked, so no new acceptance can be recorded + // (`record_join_policy_acceptance` locks it `FOR KEY SHARE`). Delete + // the ones recorded after the acceptance batch ran, in the same + // transaction as the member, as `delete_member_with_acceptances` does. + // A rollback below keeps them with the member. + sqlx::query("DELETE FROM join_policy_acceptances WHERE community_id=$1 AND pubkey=$2") + .bind(community) + .bind(&options.pubkey) + .execute(tx.conn()) + .await?; // The selected row is locked: a concurrent ownership grant cannot turn // this target into an owner between this predicate and the delete. let removed = sqlx::query( diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships_postgres_tests.rs index 29f4d6e200d..e49aebba105 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships_postgres_tests.rs @@ -125,3 +125,90 @@ async fn community_only_membership_refresh_is_atomic_and_preserves_other_communi ); assert_eq!(rosters(&f.pool).await, after); } + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn membership_delete_removes_acceptance_recorded_after_acceptance_batch() { + let f = Fixture::new().await; + let community = f.options.community; + // No foreign key cascades, so only the membership transaction can remove + // an acceptance that commits after the acceptance batch ran. + + // An acceptance write in flight: the member row is key-share locked and + // the acceptance is not yet visible to the acceptance batch. + let mut holder = f.pool.begin().await.unwrap(); + let holder_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *holder) + .await + .unwrap(); + crate::store::reference_check::require_relay_member( + &mut holder, + CommunityId::from_uuid(community), + TARGET, + ) + .await + .unwrap(); + sqlx::query( + "INSERT INTO join_policy_acceptances (community_id, pubkey, policy_version) \ + VALUES ($1, $2, $3)", + ) + .bind(community) + .bind(TARGET) + .bind("f".repeat(64)) + .execute(&mut *holder) + .await + .unwrap(); + + let store = f.store(); + let options = AccountBatchOptions { + community, + pubkey: TARGET.to_owned(), + batch_size: f.options.batch_size, + max_items: f.options.max_items, + }; + let run = tokio::spawn(async move { + store + .run_account_batches(&options, ExecutionMode::Delete, &mut Vec::new(), None) + .await + }); + // The membership delete waits on the member row lock. + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let blocked: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_stat_activity \ + WHERE $1 = ANY(pg_blocking_pids(pid)))", + ) + .bind(holder_pid) + .fetch_one(&f.pool) + .await + .unwrap(); + if blocked { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("membership delete waits on the acceptance writer"); + holder.commit().await.unwrap(); + run.await.unwrap().unwrap(); + + let left: i64 = sqlx::query_scalar( + "SELECT count(*) FROM join_policy_acceptances WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community) + .bind(TARGET) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!(left, 0, "acceptance left without its member"); + let member: i64 = sqlx::query_scalar( + "SELECT count(*) FROM relay_members WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community) + .bind(TARGET) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!(member, 0); +} diff --git a/crates/buzz-db/src/store/workflow.rs b/crates/buzz-db/src/store/workflow.rs index ded7d5b6286..d9c8f1aadc3 100644 --- a/crates/buzz-db/src/store/workflow.rs +++ b/crates/buzz-db/src/store/workflow.rs @@ -677,8 +677,7 @@ pub async fn latest_scheduled_workflow_fire( /// Returns `false` when no unlinked claim matches, or the run is missing or /// belongs to another workflow. A link stays inside one workflow, so workflow /// delete, which removes that workflow's fires and runs together, never leaves -/// a fire naming a deleted run (and, while the fire→run foreign key exists, -/// never trips it). +/// a fire naming a deleted run. pub async fn attach_scheduled_workflow_run( pool: &PgPool, community_id: CommunityId, diff --git a/crates/buzz-db/src/store/workflow/deletion_tests.rs b/crates/buzz-db/src/store/workflow/deletion_tests.rs index 481538918f9..d12ca0ecca1 100644 --- a/crates/buzz-db/src/store/workflow/deletion_tests.rs +++ b/crates/buzz-db/src/store/workflow/deletion_tests.rs @@ -122,8 +122,8 @@ async fn workflow_deletion_removes_both_projections_and_is_scoped_and_retryable( ) .await .expect("run"); - // A fired schedule links both the workflow and a cascading run. Deletion - // must also remove the claim despite its NO ACTION run foreign key. + // A fired schedule links both the workflow and a run. Deletion must also + // remove the claim. sqlx::query( "INSERT INTO scheduled_workflow_fires \ (community_id, workflow_id, scheduled_for, workflow_run_id) VALUES ($1, $2, NOW(), $3)", @@ -382,14 +382,12 @@ async fn count_where(db: &Db, table: &str, column: &str, community: CommunityId, .expect("count children") } -/// With every foreign-key delete action retired, the coordinate delete must -/// remove approvals (of the workflow or of its runs), fires and runs itself, -/// in an order the remaining constraints accept. +/// No foreign key cascades, so the coordinate delete must remove approvals (of +/// the workflow or of its runs), fires and runs itself. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_deletion_removes_children_without_cascades() { let (db, community) = setup().await; - crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; let keys = Keys::generate(); let owner = keys.public_key().to_bytes(); let id = Uuid::new_v4(); @@ -462,16 +460,12 @@ async fn workflow_deletion_removes_children_without_cascades() { /// A run inserted concurrently with the delete holds the workflow's key-share /// lock, taken by the run writer's reference check. The delete must wait for it /// at its row lock and then remove the run; if it took its child snapshot -/// first, the run would commit after the child delete and dangle. The -/// run-to-workflow foreign key is dropped, so only the explicit lock can make -/// the delete wait. +/// first, the run would commit after the child delete and dangle. No foreign +/// key exists, so only the explicit lock can make the delete wait. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_deletion_waits_for_and_removes_concurrent_run() { let (db, community) = setup().await; - crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("workflow_runs", "workflows")]) - .await; let keys = Keys::generate(); let owner = keys.public_key().to_bytes(); let id = Uuid::new_v4(); @@ -519,21 +513,12 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_run() { /// key-share locks that run (in its reference check), so the workflow lock does /// not exclude it. The delete must lock the runs, wait for the insert, and then /// remove it; if the approval committed between the approval and run deletes it -/// would dangle. The approval foreign keys are dropped, so only the explicit -/// locks can make the delete wait. +/// would dangle. No foreign key exists, so only the explicit locks can make +/// the delete wait. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_approval() { let (db, community) = setup().await; - crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[ - ("workflow_approvals", "workflows"), - ("workflow_approvals", "workflow_runs"), - ], - ) - .await; let keys = Keys::generate(); let owner = keys.public_key().to_bytes(); let id = Uuid::new_v4(); @@ -601,16 +586,14 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_appro assert!(get_workflow(&db.pool, community, other).await.is_ok()); } -/// Attaching a run to a scheduled fire locks the fire row, then, while the -/// fire's run foreign key exists (this test keeps it), key-share locks the -/// run. The delete must take those two in the same -/// order (fire before run), so an attach in flight when the delete starts -/// completes and is then removed, rather than deadlocking with it. +/// Attaching a run to a scheduled fire locks the fire row before the run. The +/// delete must take those two in the same order (fire before run), so an +/// attach in flight when the delete starts completes and is then removed, +/// rather than deadlocking with it. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock() { let (db, community) = setup().await; - crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; let keys = Keys::generate(); let owner = keys.public_key().to_bytes(); let id = Uuid::new_v4(); @@ -637,7 +620,7 @@ async fn workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock() { .await .expect("unlinked scheduled claim"); - // Hold the fire row as an attach does before its foreign-key check runs. + // Hold the fire row as an attach does before it touches the run. let mut attacher = db.pool.begin().await.expect("begin fire attach"); sqlx::query( "SELECT 1 FROM scheduled_workflow_fires \ @@ -735,7 +718,7 @@ async fn write_while_delete_holds_locks( write.await.expect("join writer") } -/// With the fire-to-workflow foreign key dropped, a fire claim racing a +/// With no fire-to-workflow foreign key, a fire claim racing a /// workflow delete must wait on the workflow row (its `FOR KEY SHARE`) and then /// find no workflow. Without that lock the claim reads its snapshot while the /// delete is uncommitted, inserts after the delete removed the fires, and leaves @@ -744,11 +727,6 @@ async fn write_while_delete_holds_locks( #[ignore = "requires Postgres"] async fn fire_claim_waits_for_workflow_delete_and_leaves_no_orphan_fire() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[("scheduled_workflow_fires", "workflows")], - ) - .await; let keys = Keys::generate(); let id = Uuid::new_v4(); seed( @@ -795,8 +773,6 @@ async fn fire_claim_waits_for_workflow_delete_and_leaves_no_orphan_fire() { #[ignore = "requires Postgres"] async fn run_create_waits_for_workflow_delete_and_leaves_no_orphan_run() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("workflow_runs", "workflows")]) - .await; let keys = Keys::generate(); let id = Uuid::new_v4(); seed( @@ -840,15 +816,6 @@ async fn run_create_waits_for_workflow_delete_and_leaves_no_orphan_run() { /// names under another workflow, waits on that parent's lock and then fails. async fn approval_waits_for_delete_and_leaves_no_orphan_approval(names_deleted_workflow: bool) { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[ - ("workflow_runs", "workflows"), - ("workflow_approvals", "workflows"), - ("workflow_approvals", "workflow_runs"), - ], - ) - .await; let keys = Keys::generate(); let now = Timestamp::now().as_secs(); let id = Uuid::new_v4(); diff --git a/crates/buzz-db/src/store/workflow/reference_tests.rs b/crates/buzz-db/src/store/workflow/reference_tests.rs index b5b1477adf2..9a7b005a635 100644 --- a/crates/buzz-db/src/store/workflow/reference_tests.rs +++ b/crates/buzz-db/src/store/workflow/reference_tests.rs @@ -1,6 +1,6 @@ //! A writer into a workflow table rejects a missing parent in application -//! code. Each test drops the foreign keys it covers from the per-test database -//! first, so a pass proves the in-transaction check rather than the constraint. +//! code. The schema has no foreign keys, so a pass proves the in-transaction +//! check. use super::*; use crate::user::ensure_user; @@ -79,11 +79,6 @@ const DEFINITION: &str = r#"{"trigger":{"on":"manual"},"steps":[]}"#; #[ignore = "requires Postgres"] async fn create_workflow_rejects_missing_owner_or_channel_without_foreign_keys() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[("workflows", "users"), ("workflows", "channels")], - ) - .await; let owner = [0x11; 32]; let create = |channel: Option, owner: [u8; 32]| { let pool = db.pool.clone(); @@ -124,11 +119,6 @@ async fn create_workflow_rejects_missing_owner_or_channel_without_foreign_keys() #[ignore = "requires Postgres"] async fn upsert_workflow_rejects_missing_owner_or_channel_without_foreign_keys() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[("workflows", "users"), ("workflows", "channels")], - ) - .await; let owner = [0x12; 32]; let upsert = |channel: Option, owner: [u8; 32]| { let pool = db.pool.clone(); @@ -231,8 +221,6 @@ async fn upsert_workflow_rejects_missing_owner_or_channel_without_foreign_keys() #[ignore = "requires Postgres"] async fn create_workflow_run_rejects_missing_workflow_without_foreign_key() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between(&db.pool, &[("workflow_runs", "workflows")]) - .await; let owner = [0x13; 32]; assert_not_found( @@ -283,14 +271,6 @@ async fn create_workflow_run_rejects_missing_workflow_without_foreign_key() { #[ignore = "requires Postgres"] async fn create_approval_rejects_missing_workflow_or_run_without_foreign_keys() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[ - ("workflow_approvals", "workflows"), - ("workflow_approvals", "workflow_runs"), - ], - ) - .await; let owner = [0x14; 32]; let workflow = new_workflow(&db, community, &owner).await; let run = create_workflow_run( @@ -363,18 +343,13 @@ async fn create_approval_rejects_missing_workflow_or_run_without_foreign_keys() } /// The owner and channel checks hold `FOR KEY SHARE` on the parent rows, so a -/// concurrent delete or key update of a parent waits for the writer. The -/// foreign keys are dropped, so only the explicit lock can block the writer -/// behind a parent held `FOR UPDATE`. +/// concurrent delete or key update of a parent waits for the writer. No foreign +/// key exists, so only the explicit lock can block the writer behind a parent +/// held `FOR UPDATE`. #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_writers_key_share_lock_owner_and_channel_without_foreign_keys() { let (db, community) = setup().await; - crate::test_support::drop_foreign_keys_between( - &db.pool, - &[("workflows", "users"), ("workflows", "channels")], - ) - .await; let owner = [0x15; 32]; ensure_user(&db.pool, community, &owner) .await diff --git a/crates/buzz-db/src/test_support.rs b/crates/buzz-db/src/test_support.rs index f089297578b..7df0e26d5f3 100644 --- a/crates/buzz-db/src/test_support.rs +++ b/crates/buzz-db/src/test_support.rs @@ -475,113 +475,6 @@ pub(crate) fn desired_state_schema_dir() -> std::path::PathBuf { std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schema") } -/// Rewrite every `ON DELETE CASCADE`, `SET NULL` and `SET DEFAULT` foreign key -/// in this test's database as `NO ACTION`: the schema the cascade retirement -/// targets. Every trigger stays live, including the foreign-key checks and the -/// community fence, so a delete path exercised afterwards must remove its -/// children itself, in an order the remaining constraints accept. -/// -/// Each PostgreSQL test process owns its database (`crates/buzz-db/TESTING.md`), -/// so the rewrite does not reach other tests. It refuses any database whose -/// name does not match the per-test wrapper's (`buzz_nt_` plus 24 hex digits), -/// which excludes the run's `_desired` template. The name is the only check: -/// a manually created database with that shape would pass. -pub(crate) async fn retire_foreign_key_delete_actions(pool: &sqlx::PgPool) { - assert_per_test_database(pool).await; - sqlx::raw_sql( - r#"DO $$ - DECLARE c record; - BEGIN - FOR c IN SELECT conrelid::regclass AS tbl, conname, pg_get_constraintdef(oid) AS def - FROM pg_constraint - WHERE contype = 'f' AND confdeltype IN ('c', 'n', 'd') AND conparentid = 0 - LOOP - EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I, ADD CONSTRAINT %I %s', - c.tbl, c.conname, c.conname, - regexp_replace(c.def, ' ON DELETE (CASCADE|SET NULL|SET DEFAULT)( \([^)]*\))?', '')); - END LOOP; - END $$"#, - ) - .execute(pool) - .await - .expect("retire foreign-key delete actions"); - let remaining: i64 = sqlx::query_scalar( - "SELECT count(*) FROM pg_constraint WHERE contype = 'f' AND confdeltype IN ('c', 'n', 'd')", - ) - .fetch_one(pool) - .await - .expect("count foreign-key delete actions"); - assert_eq!(remaining, 0, "every foreign-key delete action is retired"); -} - -/// Refuse to continue unless `pool` is this test process's own database (named -/// `buzz_nt_` plus 24 hex digits by the per-test wrapper), so a schema rewrite -/// cannot reach a shared database or the run's `_desired` template. -async fn assert_per_test_database(pool: &sqlx::PgPool) { - let database: String = sqlx::query_scalar("SELECT current_database()") - .fetch_one(pool) - .await - .expect("read current database"); - assert!( - database - .strip_prefix("buzz_nt_") - .is_some_and(|hash| hash.len() == 24 - && hash - .bytes() - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))), - "refusing to rewrite foreign keys in shared database {database}; \ - run this test through scripts/postgres-test-run.sh" - ); -} - -/// Drop every foreign key from `child` to `parent` in this test's database, for -/// each `(child, parent)` pair: the schema a foreign-key retirement targets. -/// A test that then expects the writer to reject a missing parent proves the -/// application check, because the constraint can no longer do the work. -/// -/// Refuses databases that are not the per-test wrapper's, like -/// [`retire_foreign_key_delete_actions`]. Panics if a pair has no foreign key, -/// so a renamed table cannot turn the test into a silent no-op. -pub(crate) async fn drop_foreign_keys_between(pool: &sqlx::PgPool, pairs: &[(&str, &str)]) { - assert_per_test_database(pool).await; - for (child, parent) in pairs { - let constraints: Vec = sqlx::query_scalar( - "SELECT conname FROM pg_constraint \ - WHERE contype = 'f' AND conrelid = $1::text::regclass AND confrelid = $2::text::regclass", - ) - .bind(child) - .bind(parent) - .fetch_all(pool) - .await - .expect("list foreign keys"); - assert!( - !constraints.is_empty(), - "no foreign key from {child} to {parent} to drop" - ); - for name in constraints { - sqlx::query(sqlx::AssertSqlSafe(format!( - "ALTER TABLE {child} DROP CONSTRAINT \"{name}\"" - ))) - .execute(pool) - .await - .expect("drop foreign key"); - } - let remaining: i64 = sqlx::query_scalar( - "SELECT count(*) FROM pg_constraint \ - WHERE contype = 'f' AND conrelid = $1::text::regclass AND confrelid = $2::text::regclass", - ) - .bind(child) - .bind(parent) - .fetch_one(pool) - .await - .expect("recount foreign keys"); - assert_eq!( - remaining, 0, - "foreign keys from {child} to {parent} dropped" - ); - } -} - /// A single-connection pool whose session carries `application_name`, so /// [`wait_for_lock_wait`] can tell when its statement is blocked. pub(crate) async fn named_pool(application_name: &str) -> sqlx::PgPool { diff --git a/docs/database.md b/docs/database.md index 43d62cdf232..53faaea8fa1 100644 --- a/docs/database.md +++ b/docs/database.md @@ -17,7 +17,7 @@ PostgreSQL stores data. The application owns behavior. |---|---|---| | Schema source of truth | Two parallel sources: ordered sqlx migrations in `migrations/` and the desired-state manifest in `schema/` | The declarative desired state in `schema/tables/public/` is the source of truth. Deployments that apply schema out of band plan each change from it, with the tool of their choice. `migrations/` stays, because auto-migration stays supported (next row). Each app owns its own migrations and declarative schema: the relay's copies of the push gateway's tables are debt to remove (Rule 4). | | Who applies DDL | Startup migrations when `BUZZ_AUTO_MIGRATE` is on (binary default off, Helm chart default on), `buzz-admin migrate`, the push gateway's pre-upgrade Helm Job, and partition creation at relay startup and on a schedule | Both modes stay supported. Deployments at scale, including Block's hosted deployment, apply schema changes out of band through a reviewed workflow before deploying, and their serving relay runs no DDL. Smaller and self-hosted deployments MAY keep auto-migration on. Still open: how the two modes share one schema source, how auto-migration orders a release whose expand, backfill, and contract steps arrive in one upgrade, and how an operator recovers after a contract migration fails at boot (Rule 5). Monthly partition creation is planned to move out of the relay. Changes to partitioned tables (`events`, `delivery_log`) are outside the out-of-band envelope (Rule 6): attaching a partition to a live parent and building an index on a partitioned parent need their own reviewed procedure. | -| Integrity between tables | Some foreign keys, including `ON DELETE CASCADE` and `ON DELETE SET NULL` | None in the database. The owning application transaction checks references and performs deletes explicitly. | +| Integrity between tables | None in the database (migrations `0102`-`0104` dropped the last foreign keys) | None in the database. The owning application transaction checks references and performs deletes explicitly. | | Guards and follow-up writes | Triggers and PL/pgSQL functions (`schema/functions/`, `schema/triggers/`) | None in the database. Guards run in the owning writer's transaction; follow-up work is recorded in the same transaction and processed as durable, retryable application work. | | Data repair | Some historical repair embedded in migrations | Backfill definitions in application code, run by the durable framework in [data-backfills.md](data-backfills.md). | | Rollout | Effectively schema and code together | Expand, then deploy, then backfill, then contract. Each step is applied and verified on its own. | @@ -48,10 +48,9 @@ adds to them moves away from the target. or recovery. The backfill framework exists to provide those properties. The move to declarative, out-of-band schema changes is in progress. Until it -finishes, existing triggers, functions, and foreign keys stay in place as -backstops. They are removed one at a time, after their application replacement -has shipped and been verified. They are not removed early, and new ones are not -added. +finishes, any remaining trigger or function stays in place as a backstop. Each +is removed on its own, after its application replacement has shipped and been +verified. None is removed early, and no new one is added. ## Rules for changes now @@ -414,6 +413,14 @@ parity assertion on the table for that window. 3. Removing a guard requires a falsifiable test showing that the application path enforces what the guard enforced. +pgschema cannot drop a trigger or foreign key from a partitioned table: it +plans a drop for each partition's copy, which PostgreSQL refuses (`2BP01`) or +which the parent's drop already removed (`42704`). A deployment that applies +`schema/` with pgschema applies the dropping migration first, under that +migration's lock budgets, then runs pgschema. For the trigger drops see +[trigger-retirement-deployment.md](trigger-retirement-deployment.md); for the +foreign keys on `events` and `delivery_log`, apply `0104`. + ### 6. Bound every lock and statement - Every migration MUST start with `SET LOCAL lock_timeout`, and SHOULD set diff --git a/migrations/0102_drop_tenant_reference_fks.sql b/migrations/0102_drop_tenant_reference_fks.sql new file mode 100644 index 00000000000..5534f65c97c --- /dev/null +++ b/migrations/0102_drop_tenant_reference_fks.sql @@ -0,0 +1,69 @@ +-- Contract step (docs/database.md Rule 2 and "Retiring a trigger, function, +-- or foreign key"): drop the 25 foreign keys between tenant tables. The +-- owning application transactions check each reference and delete or detach +-- dependent rows themselves. +-- +-- Required stop: run a relay build with the application reference checks and +-- explicit child deletes (#9608 or later) on every pod and job first. Do not +-- roll back below it. +-- +-- Dropping a foreign key takes ACCESS EXCLUSIVE on the child and on the +-- referenced table. Take every lock in one statement, children before +-- parents. The budgets end the attempt well before the 1s deadlock_timeout, +-- so this transaction fails instead of a relay query. Retry on failure. +SET LOCAL lock_timeout = '300ms'; +SET LOCAL statement_timeout = '800ms'; + +LOCK TABLE + join_policy_acceptances, + personal_read_frontiers, + push_wake_outbox, + relay_admin_outbox, + relay_admin_actions, + moderation_reports, + moderation_actions, + thread_metadata, + channel_members, + scheduled_workflow_fires, + workflow_approvals, + workflow_runs, + workflows, + api_tokens, + subscriptions, + community_deletion_approvals, + community_deletion_checkpoints, + community_deletion_executor_heartbeats, + community_deletion_manifest_keys, + relay_members, + personal_read_accounts, + push_leases, + channels, + users, + community_deletion_requests + IN ACCESS EXCLUSIVE MODE; + +ALTER TABLE join_policy_acceptances DROP CONSTRAINT join_policy_acceptances_community_id_pubkey_fkey; +ALTER TABLE personal_read_frontiers DROP CONSTRAINT personal_read_frontiers_community_id_actor_fkey; +ALTER TABLE personal_read_frontiers DROP CONSTRAINT personal_read_frontiers_community_id_channel_id_fkey; +ALTER TABLE push_wake_outbox DROP CONSTRAINT push_wake_outbox_community_id_author_installation_id_fkey; +ALTER TABLE relay_admin_outbox DROP CONSTRAINT relay_admin_outbox_action_id_fkey; +ALTER TABLE relay_admin_actions DROP CONSTRAINT relay_admin_actions_report_community_id_report_id_fkey; +ALTER TABLE moderation_reports DROP CONSTRAINT moderation_reports_community_id_action_id_fkey; +ALTER TABLE moderation_reports DROP CONSTRAINT moderation_reports_community_id_channel_id_fkey; +ALTER TABLE moderation_actions DROP CONSTRAINT moderation_actions_community_id_channel_id_fkey; +ALTER TABLE thread_metadata DROP CONSTRAINT thread_metadata_community_id_channel_id_fkey; +ALTER TABLE channel_members DROP CONSTRAINT channel_members_community_id_channel_id_fkey; +ALTER TABLE scheduled_workflow_fires DROP CONSTRAINT scheduled_workflow_fires_community_id_workflow_id_fkey; +ALTER TABLE scheduled_workflow_fires DROP CONSTRAINT scheduled_workflow_fires_community_id_workflow_run_id_fkey; +ALTER TABLE workflow_approvals DROP CONSTRAINT workflow_approvals_community_id_workflow_id_fkey; +ALTER TABLE workflow_approvals DROP CONSTRAINT workflow_approvals_community_id_run_id_fkey; +ALTER TABLE workflow_runs DROP CONSTRAINT workflow_runs_community_id_workflow_id_fkey; +ALTER TABLE workflows DROP CONSTRAINT workflows_community_id_owner_pubkey_fkey; +ALTER TABLE workflows DROP CONSTRAINT workflows_community_id_channel_id_fkey; +ALTER TABLE api_tokens DROP CONSTRAINT api_tokens_community_id_owner_pubkey_fkey; +ALTER TABLE subscriptions DROP CONSTRAINT subscriptions_community_id_owner_pubkey_fkey; +ALTER TABLE users DROP CONSTRAINT users_community_id_agent_owner_pubkey_fkey; +ALTER TABLE community_deletion_approvals DROP CONSTRAINT community_deletion_approvals_request_id_community_id_inven_fkey; +ALTER TABLE community_deletion_checkpoints DROP CONSTRAINT community_deletion_checkpoints_request_id_fkey; +ALTER TABLE community_deletion_executor_heartbeats DROP CONSTRAINT community_deletion_executor_heartbeats_request_id_fkey; +ALTER TABLE community_deletion_manifest_keys DROP CONSTRAINT community_deletion_manifest_keys_request_id_fkey; diff --git a/migrations/0103_drop_community_fks.sql b/migrations/0103_drop_community_fks.sql new file mode 100644 index 00000000000..11e47205f6b --- /dev/null +++ b/migrations/0103_drop_community_fks.sql @@ -0,0 +1,83 @@ +-- Contract step (docs/database.md Rule 2): drop the community_id foreign keys +-- on the 32 unpartitioned tenant tables. Writers prove the community inside +-- their own transaction (AdmittedTx, or an INSERT ... SELECT from an active +-- community), and community deletion purges children explicitly before it +-- tombstones the community row. Production code never deletes a community. +-- +-- Required stop: as for 0102. +-- +-- Each drop takes ACCESS EXCLUSIVE on the child and on communities. Take +-- every lock in one statement, communities last. The budgets end the attempt +-- well before the 1s deadlock_timeout, so this transaction fails instead of a +-- relay query. Retry on failure. +SET LOCAL lock_timeout = '300ms'; +SET LOCAL statement_timeout = '800ms'; + +LOCK TABLE + api_tokens, + archived_identities, + artifact_heads, + artifact_revisions, + audit_log, + channel_members, + channels, + community_bans, + community_deletion_requests, + community_nip_fi_issuers, + community_serving_write_leases, + event_mentions, + git_repo_names, + moderation_actions, + moderation_reports, + parameterized_event_watermarks, + personal_read_accounts, + product_feedback, + pubkey_allowlist, + push_leases, + push_match_queue, + push_wake_outbox, + reactions, + relay_invites, + relay_members, + scheduled_workflow_fires, + subscriptions, + thread_metadata, + users, + workflow_approvals, + workflow_runs, + workflows, + communities + IN ACCESS EXCLUSIVE MODE; + +ALTER TABLE api_tokens DROP CONSTRAINT api_tokens_community_id_fkey; +ALTER TABLE archived_identities DROP CONSTRAINT archived_identities_community_id_fkey; +ALTER TABLE artifact_heads DROP CONSTRAINT artifact_heads_community_id_fkey; +ALTER TABLE artifact_revisions DROP CONSTRAINT artifact_revisions_community_id_fkey; +ALTER TABLE audit_log DROP CONSTRAINT audit_log_community_id_fkey; +ALTER TABLE channel_members DROP CONSTRAINT channel_members_community_id_fkey; +ALTER TABLE channels DROP CONSTRAINT channels_community_id_fkey; +ALTER TABLE community_bans DROP CONSTRAINT community_bans_community_id_fkey; +ALTER TABLE community_deletion_requests DROP CONSTRAINT community_deletion_requests_community_id_fkey; +ALTER TABLE community_nip_fi_issuers DROP CONSTRAINT community_nip_fi_issuers_community_id_fkey; +ALTER TABLE community_serving_write_leases DROP CONSTRAINT community_serving_write_leases_community_id_fkey; +ALTER TABLE event_mentions DROP CONSTRAINT event_mentions_community_id_fkey; +ALTER TABLE git_repo_names DROP CONSTRAINT git_repo_names_community_id_fkey; +ALTER TABLE moderation_actions DROP CONSTRAINT moderation_actions_community_id_fkey; +ALTER TABLE moderation_reports DROP CONSTRAINT moderation_reports_community_id_fkey; +ALTER TABLE parameterized_event_watermarks DROP CONSTRAINT parameterized_event_watermarks_community_id_fkey; +ALTER TABLE personal_read_accounts DROP CONSTRAINT personal_read_accounts_community_id_fkey; +ALTER TABLE product_feedback DROP CONSTRAINT product_feedback_community_id_fkey; +ALTER TABLE pubkey_allowlist DROP CONSTRAINT pubkey_allowlist_community_id_fkey; +ALTER TABLE push_leases DROP CONSTRAINT push_leases_community_id_fkey; +ALTER TABLE push_match_queue DROP CONSTRAINT push_match_queue_community_id_fkey; +ALTER TABLE push_wake_outbox DROP CONSTRAINT push_wake_outbox_community_id_fkey; +ALTER TABLE reactions DROP CONSTRAINT reactions_community_id_fkey; +ALTER TABLE relay_invites DROP CONSTRAINT relay_invites_community_id_fkey; +ALTER TABLE relay_members DROP CONSTRAINT relay_members_community_id_fkey; +ALTER TABLE scheduled_workflow_fires DROP CONSTRAINT scheduled_workflow_fires_community_id_fkey; +ALTER TABLE subscriptions DROP CONSTRAINT subscriptions_community_id_fkey; +ALTER TABLE thread_metadata DROP CONSTRAINT thread_metadata_community_id_fkey; +ALTER TABLE users DROP CONSTRAINT users_community_id_fkey; +ALTER TABLE workflow_approvals DROP CONSTRAINT workflow_approvals_community_id_fkey; +ALTER TABLE workflow_runs DROP CONSTRAINT workflow_runs_community_id_fkey; +ALTER TABLE workflows DROP CONSTRAINT workflows_community_id_fkey; diff --git a/migrations/0104_drop_event_table_community_fks.sql b/migrations/0104_drop_event_table_community_fks.sql new file mode 100644 index 00000000000..252ec98f3cd --- /dev/null +++ b/migrations/0104_drop_event_table_community_fks.sql @@ -0,0 +1,20 @@ +-- Contract step (docs/database.md Rule 2): drop the community_id foreign keys +-- on the partitioned events and delivery_log tables, and with them the clone +-- on every partition. Event writers prove the community in AdmittedTx; +-- delivery_log has no production writer, and community deletion purges both. +-- +-- Required stop: as for 0102. +-- +-- Each drop takes ACCESS EXCLUSIVE on the parent, on every partition and on +-- communities. LOCK TABLE without ONLY takes the partitions too, in one +-- statement, with communities last. The budgets end the attempt well before +-- the 1s deadlock_timeout, so this transaction fails instead of a relay query. +-- Retry on failure. Deployments that apply schema out of band apply this file +-- in its own transaction, apart from 0102 and 0103. +SET LOCAL lock_timeout = '300ms'; +SET LOCAL statement_timeout = '800ms'; + +LOCK TABLE events, delivery_log, communities IN ACCESS EXCLUSIVE MODE; + +ALTER TABLE events DROP CONSTRAINT events_community_id_fkey; +ALTER TABLE delivery_log DROP CONSTRAINT delivery_log_community_id_fkey; diff --git a/schema/tables/public/api_tokens.sql b/schema/tables/public/api_tokens.sql index 35666c52cbe..c7cde4c01f6 100644 --- a/schema/tables/public/api_tokens.sql +++ b/schema/tables/public/api_tokens.sql @@ -3,7 +3,7 @@ -- (community_id, token_hash); channel claims reference channels in same community. CREATE TABLE api_tokens ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id UUID NOT NULL DEFAULT gen_random_uuid(), token_hash BYTEA NOT NULL, owner_pubkey BYTEA NOT NULL, @@ -17,7 +17,6 @@ CREATE TABLE api_tokens ( revoked_by BYTEA, created_by_self_mint BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (community_id, id), - FOREIGN KEY (community_id, owner_pubkey) REFERENCES users (community_id, pubkey), CONSTRAINT chk_api_tokens_hash_len CHECK (LENGTH(token_hash) = 32) ); diff --git a/schema/tables/public/archived_identities.sql b/schema/tables/public/archived_identities.sql index d8475df0452..e268bf3a254 100644 --- a/schema/tables/public/archived_identities.sql +++ b/schema/tables/public/archived_identities.sql @@ -2,7 +2,7 @@ -- Conformance: archive cannot hide a key in another community. PK scoped. CREATE TABLE archived_identities ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, pubkey TEXT NOT NULL, consent_path TEXT NOT NULL CHECK (consent_path IN ('self', 'owner', 'admin')), actor TEXT NOT NULL, diff --git a/schema/tables/public/artifact_heads.sql b/schema/tables/public/artifact_heads.sql index 7e73557b9b6..b3f34209e31 100644 --- a/schema/tables/public/artifact_heads.sql +++ b/schema/tables/public/artifact_heads.sql @@ -1,6 +1,6 @@ -- NIP-AR current heads and acceptance ledger are independent of event retention. CREATE TABLE artifact_heads ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, artifact_id UUID NOT NULL, event_id BYTEA NOT NULL CHECK (length(event_id) = 32), channel_id UUID NOT NULL, diff --git a/schema/tables/public/artifact_revisions.sql b/schema/tables/public/artifact_revisions.sql index d3320c0bfff..6120eccf5d3 100644 --- a/schema/tables/public/artifact_revisions.sql +++ b/schema/tables/public/artifact_revisions.sql @@ -1,7 +1,7 @@ -- Every accepted revision ID, so replays stay idempotent after redaction or -- retention. CREATE TABLE artifact_revisions ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, event_id BYTEA NOT NULL CHECK (length(event_id) = 32), artifact_id UUID NOT NULL, source_channel_id UUID, diff --git a/schema/tables/public/audit_log.sql b/schema/tables/public/audit_log.sql index 6038505f0df..90983b50880 100644 --- a/schema/tables/public/audit_log.sql +++ b/schema/tables/public/audit_log.sql @@ -4,7 +4,7 @@ -- (Lane Audit/Dawn builds the chain logic; Lane 0 fixes the scoped schema.) CREATE TABLE audit_log ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, seq BIGINT NOT NULL, hash_version SMALLINT NOT NULL DEFAULT 1 CHECK (hash_version IN (1, 2)), hash BYTEA NOT NULL, diff --git a/schema/tables/public/channel_members.sql b/schema/tables/public/channel_members.sql index b0cd4e67926..826d6278646 100644 --- a/schema/tables/public/channel_members.sql +++ b/schema/tables/public/channel_members.sql @@ -2,7 +2,7 @@ -- Conformance: "Channels and channel membership". PK leads with community_id. CREATE TABLE channel_members ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, channel_id UUID NOT NULL, pubkey BYTEA NOT NULL, role member_role NOT NULL DEFAULT 'member', @@ -12,9 +12,7 @@ CREATE TABLE channel_members ( removed_by BYTEA, hidden_at TIMESTAMPTZ, sync_modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - PRIMARY KEY (community_id, channel_id, pubkey), - FOREIGN KEY (community_id, channel_id) - REFERENCES channels (community_id, id) ON DELETE CASCADE + PRIMARY KEY (community_id, channel_id, pubkey) ); CREATE INDEX idx_channel_members_pubkey ON channel_members (community_id, pubkey) diff --git a/schema/tables/public/channels.sql b/schema/tables/public/channels.sql index 9162b502a64..c3347114fe7 100644 --- a/schema/tables/public/channels.sql +++ b/schema/tables/public/channels.sql @@ -9,7 +9,7 @@ CREATE TABLE channels ( id UUID NOT NULL DEFAULT gen_random_uuid(), - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, name VARCHAR(255) NOT NULL, channel_type channel_type NOT NULL DEFAULT 'stream', visibility channel_visibility NOT NULL DEFAULT 'open', diff --git a/schema/tables/public/community_bans.sql b/schema/tables/public/community_bans.sql index b6dadb2d298..9efcf476ebc 100644 --- a/schema/tables/public/community_bans.sql +++ b/schema/tables/public/community_bans.sql @@ -5,7 +5,7 @@ -- A row may be ban-only, timeout-only, or both over its lifetime. CREATE TABLE community_bans ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, pubkey BYTEA NOT NULL CHECK (length(pubkey) = 32), banned BOOLEAN NOT NULL DEFAULT false, -- NULL + banned=true ⇒ permanent. diff --git a/schema/tables/public/community_deletion_approvals.sql b/schema/tables/public/community_deletion_approvals.sql index 633f1f79bac..5c031120b45 100644 --- a/schema/tables/public/community_deletion_approvals.sql +++ b/schema/tables/public/community_deletion_approvals.sql @@ -6,8 +6,5 @@ CREATE TABLE community_deletion_approvals ( approval_origin TEXT NOT NULL DEFAULT 'operator' CHECK (approval_origin IN ('operator', 'owner_automatic')), note TEXT, - approved_at TIMESTAMPTZ NOT NULL DEFAULT now(), - FOREIGN KEY (request_id, community_id, inventory_digest) - REFERENCES community_deletion_requests(id, community_id, inventory_digest) - ON DELETE RESTRICT + approved_at TIMESTAMPTZ NOT NULL DEFAULT now() ); diff --git a/schema/tables/public/community_deletion_checkpoints.sql b/schema/tables/public/community_deletion_checkpoints.sql index b2d8e172138..cd74a2c64fa 100644 --- a/schema/tables/public/community_deletion_checkpoints.sql +++ b/schema/tables/public/community_deletion_checkpoints.sql @@ -1,5 +1,5 @@ CREATE TABLE community_deletion_checkpoints ( - request_id UUID NOT NULL REFERENCES community_deletion_requests(id) ON DELETE RESTRICT, + request_id UUID NOT NULL, sequence BIGINT GENERATED ALWAYS AS IDENTITY, stage TEXT NOT NULL, unit_key TEXT NOT NULL, diff --git a/schema/tables/public/community_deletion_executor_heartbeats.sql b/schema/tables/public/community_deletion_executor_heartbeats.sql index 1d7a90f2c35..491afde1efd 100644 --- a/schema/tables/public/community_deletion_executor_heartbeats.sql +++ b/schema/tables/public/community_deletion_executor_heartbeats.sql @@ -1,7 +1,7 @@ CREATE TABLE community_deletion_executor_heartbeats ( executor_id TEXT PRIMARY KEY, mode TEXT NOT NULL CHECK (mode IN ('run', 'drain', 'worker')), - request_id UUID REFERENCES community_deletion_requests(id) ON DELETE SET NULL, + request_id UUID, started_at TIMESTAMPTZ NOT NULL DEFAULT now(), heartbeat_at TIMESTAMPTZ NOT NULL DEFAULT now(), draining BOOLEAN NOT NULL DEFAULT false, diff --git a/schema/tables/public/community_deletion_manifest_keys.sql b/schema/tables/public/community_deletion_manifest_keys.sql index 49bd90bb3c8..15a39c64825 100644 --- a/schema/tables/public/community_deletion_manifest_keys.sql +++ b/schema/tables/public/community_deletion_manifest_keys.sql @@ -5,7 +5,7 @@ -- verification. The request row keeps only per-prefix count/bytes/digest -- summaries; the chunk stream must hash to those frozen digests. CREATE TABLE community_deletion_manifest_keys ( - request_id UUID NOT NULL REFERENCES community_deletion_requests(id) ON DELETE CASCADE, + request_id UUID NOT NULL, chunk_no BIGINT NOT NULL CHECK (chunk_no >= 0), prefix TEXT NOT NULL, keys JSONB NOT NULL, diff --git a/schema/tables/public/community_deletion_requests.sql b/schema/tables/public/community_deletion_requests.sql index 80f4b3cba5a..2e537e2b02a 100644 --- a/schema/tables/public/community_deletion_requests.sql +++ b/schema/tables/public/community_deletion_requests.sql @@ -1,7 +1,7 @@ -- ── Whole-community deletion control plane (migration 0029) ───────────────── CREATE TABLE community_deletion_requests ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, community_host TEXT NOT NULL, stage TEXT NOT NULL DEFAULT 'submitted' CHECK (stage IN ( 'submitted', 'inventoried', 'approved', 'fenced', 'drained', diff --git a/schema/tables/public/community_nip_fi_issuers.sql b/schema/tables/public/community_nip_fi_issuers.sql index d44482a18e8..993f143524b 100644 --- a/schema/tables/public/community_nip_fi_issuers.sql +++ b/schema/tables/public/community_nip_fi_issuers.sql @@ -5,7 +5,7 @@ -- for it fails closed. CREATE TABLE community_nip_fi_issuers ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, issuer TEXT NOT NULL CHECK (length(issuer) BETWEEN 1 AND 2048), created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (community_id, issuer) diff --git a/schema/tables/public/community_serving_write_leases.sql b/schema/tables/public/community_serving_write_leases.sql index 6a905fe6b47..45fcf28c470 100644 --- a/schema/tables/public/community_serving_write_leases.sql +++ b/schema/tables/public/community_serving_write_leases.sql @@ -1,6 +1,6 @@ CREATE TABLE community_serving_write_leases ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, operation TEXT NOT NULL, owner TEXT NOT NULL, generation BIGINT NOT NULL DEFAULT 1 CHECK (generation > 0), diff --git a/schema/tables/public/delivery_log.sql b/schema/tables/public/delivery_log.sql index 51e42c41db1..b3afa31e03f 100644 --- a/schema/tables/public/delivery_log.sql +++ b/schema/tables/public/delivery_log.sql @@ -3,7 +3,7 @@ -- attribution; child of subscriptions. CREATE TABLE delivery_log ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id BIGINT GENERATED ALWAYS AS IDENTITY, subscription_id VARCHAR(255), event_id BYTEA, diff --git a/schema/tables/public/event_mentions.sql b/schema/tables/public/event_mentions.sql index b0eb9dcb4a7..befa2ba9e56 100644 --- a/schema/tables/public/event_mentions.sql +++ b/schema/tables/public/event_mentions.sql @@ -5,7 +5,7 @@ -- mentions (Max, verified at event.rs:222). CREATE TABLE event_mentions ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, pubkey_hex VARCHAR(64) NOT NULL, event_id BYTEA NOT NULL, event_created_at TIMESTAMPTZ NOT NULL, diff --git a/schema/tables/public/events.sql b/schema/tables/public/events.sql index 6056fc556bd..771d2c26648 100644 --- a/schema/tables/public/events.sql +++ b/schema/tables/public/events.sql @@ -6,7 +6,7 @@ -- (community_id, created_at, id) dedupes within one, allows across. CREATE TABLE events ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id BYTEA NOT NULL, pubkey BYTEA NOT NULL, created_at TIMESTAMPTZ NOT NULL, diff --git a/schema/tables/public/git_repo_names.sql b/schema/tables/public/git_repo_names.sql index e366d92fccb..037a16f5bfb 100644 --- a/schema/tables/public/git_repo_names.sql +++ b/schema/tables/public/git_repo_names.sql @@ -1,7 +1,7 @@ -- ── Additive tenant tables represented in migrations 0002/0007/0017 ────────── -- Keep desired-state schema parity with the embedded SQLx migration path. CREATE TABLE git_repo_names ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, repo_id TEXT NOT NULL, owner_pubkey TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), diff --git a/schema/tables/public/join_policy_acceptances.sql b/schema/tables/public/join_policy_acceptances.sql index 95db631584c..b89b9671b4b 100644 --- a/schema/tables/public/join_policy_acceptances.sql +++ b/schema/tables/public/join_policy_acceptances.sql @@ -1,14 +1,13 @@ -- ── Join policy acceptances ────────────────────────────────────────────────── -- Durable evidence of the policy version accepted when an invite claim grants --- relay membership. The composite foreign key keeps evidence bound to a live --- member in the same community and removes it with that membership. +-- relay membership. The writer binds each acceptance to a live member in the +-- same community, and removing the member removes its acceptances in the same +-- transaction. CREATE TABLE join_policy_acceptances ( community_id UUID NOT NULL, pubkey TEXT NOT NULL, policy_version TEXT NOT NULL CHECK (length(policy_version) = 64), accepted_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY (community_id, pubkey, policy_version), - FOREIGN KEY (community_id, pubkey) - REFERENCES relay_members (community_id, pubkey) ON DELETE CASCADE + PRIMARY KEY (community_id, pubkey, policy_version) ); diff --git a/schema/tables/public/moderation_actions.sql b/schema/tables/public/moderation_actions.sql index 309c5a54d1f..7968185b939 100644 --- a/schema/tables/public/moderation_actions.sql +++ b/schema/tables/public/moderation_actions.sql @@ -4,7 +4,7 @@ -- tombstone carries only action_id + reason_code + sanitized public_reason. CREATE TABLE moderation_actions ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id UUID NOT NULL DEFAULT gen_random_uuid(), actor_pubkey BYTEA NOT NULL CHECK (length(actor_pubkey) = 32), action TEXT NOT NULL CHECK (action IN ( @@ -28,8 +28,7 @@ CREATE TABLE moderation_actions ( actor_authority TEXT NOT NULL DEFAULT 'community' CHECK (actor_authority IN ('community', 'relay_operator', 'relay_moderator')), created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY (community_id, id), - FOREIGN KEY (community_id, channel_id) REFERENCES channels (community_id, id) + PRIMARY KEY (community_id, id) ); CREATE INDEX idx_moderation_actions_created diff --git a/schema/tables/public/moderation_reports.sql b/schema/tables/public/moderation_reports.sql index 13243e365f3..16784e25345 100644 --- a/schema/tables/public/moderation_reports.sql +++ b/schema/tables/public/moderation_reports.sql @@ -4,7 +4,7 @@ -- moderators in the queue but never revealed to the reported author. CREATE TABLE moderation_reports ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id UUID NOT NULL DEFAULT gen_random_uuid(), -- The signed kind:1984 event id (stored for audit/idempotency). report_event_id BYTEA NOT NULL CHECK (length(report_event_id) = 32), @@ -36,13 +36,7 @@ CREATE TABLE moderation_reports ( (target_kind = 'event' AND target_event_id IS NOT NULL AND target_pubkey IS NULL AND target_blob_sha256 IS NULL) OR (target_kind = 'pubkey' AND target_event_id IS NULL AND target_pubkey IS NOT NULL AND target_blob_sha256 IS NULL) OR (target_kind = 'blob' AND target_event_id IS NULL AND target_pubkey IS NULL AND target_blob_sha256 IS NOT NULL) - ), - -- Same-community channel provenance (channels are soft-deleted, never - -- hard-deleted, so this FK cannot dangle). - FOREIGN KEY (community_id, channel_id) REFERENCES channels (community_id, id), - -- Same-community resolution provenance: a report can only be resolved by an - -- action row in its own community. - FOREIGN KEY (community_id, action_id) REFERENCES moderation_actions (community_id, id) + ) ); -- Queue reads: open reports, newest first, per community. diff --git a/schema/tables/public/parameterized_event_watermarks.sql b/schema/tables/public/parameterized_event_watermarks.sql index 107d9823999..2d80c577209 100644 --- a/schema/tables/public/parameterized_event_watermarks.sql +++ b/schema/tables/public/parameterized_event_watermarks.sql @@ -1,5 +1,5 @@ CREATE TABLE parameterized_event_watermarks ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, kind INT NOT NULL, pubkey BYTEA NOT NULL, d_tag TEXT NOT NULL, diff --git a/schema/tables/public/personal_read_accounts.sql b/schema/tables/public/personal_read_accounts.sql index 0573c458072..90b1fbdade7 100644 --- a/schema/tables/public/personal_read_accounts.sql +++ b/schema/tables/public/personal_read_accounts.sql @@ -5,7 +5,7 @@ -- started_at is the actor's first read intent. NULL until then: an account -- can exist before its actor has started. CREATE TABLE personal_read_accounts ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, actor BYTEA NOT NULL CHECK (octet_length(actor) = 32), started_at TIMESTAMPTZ, PRIMARY KEY (community_id, actor) diff --git a/schema/tables/public/personal_read_frontiers.sql b/schema/tables/public/personal_read_frontiers.sql index e62eb9c8b94..abc8106a193 100644 --- a/schema/tables/public/personal_read_frontiers.sql +++ b/schema/tables/public/personal_read_frontiers.sql @@ -6,9 +6,5 @@ CREATE TABLE personal_read_frontiers ( through_timestamp TIMESTAMPTZ NOT NULL, -- The message whose arrival is through_timestamp; NULL before 0058. through_message_id BYTEA CHECK (octet_length(through_message_id) = 32), - PRIMARY KEY (community_id, actor, channel_id, root_id), - FOREIGN KEY (community_id, actor) - REFERENCES personal_read_accounts (community_id, actor) ON DELETE CASCADE, - FOREIGN KEY (community_id, channel_id) - REFERENCES channels (community_id, id) ON DELETE CASCADE + PRIMARY KEY (community_id, actor, channel_id, root_id) ); diff --git a/schema/tables/public/product_feedback.sql b/schema/tables/public/product_feedback.sql index fdbfc79dab1..a51db47a50f 100644 --- a/schema/tables/public/product_feedback.sql +++ b/schema/tables/public/product_feedback.sql @@ -1,6 +1,6 @@ CREATE TABLE product_feedback ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - community_id UUID REFERENCES communities(id) ON DELETE SET NULL, + community_id UUID, event_id BYTEA NOT NULL CHECK (length(event_id) = 32), submitter_pubkey BYTEA NOT NULL CHECK (length(submitter_pubkey) = 32), category TEXT CHECK (category IN ('bug', 'praise', 'needs-work')), diff --git a/schema/tables/public/pubkey_allowlist.sql b/schema/tables/public/pubkey_allowlist.sql index af623765f9e..b305e4be453 100644 --- a/schema/tables/public/pubkey_allowlist.sql +++ b/schema/tables/public/pubkey_allowlist.sql @@ -3,7 +3,7 @@ -- PK becomes (community_id, pubkey). CREATE TABLE pubkey_allowlist ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, pubkey BYTEA NOT NULL, added_by BYTEA, added_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), diff --git a/schema/tables/public/push_leases.sql b/schema/tables/public/push_leases.sql index 13abbac47c1..43aa1b0dd2b 100644 --- a/schema/tables/public/push_leases.sql +++ b/schema/tables/public/push_leases.sql @@ -1,7 +1,7 @@ -- NIP-PL effective lease state and durable wake outbox. Every key is led by -- community_id: client-provided origin is confirmation only, never routing. CREATE TABLE push_leases ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, author BYTEA NOT NULL CHECK (length(author) = 32), installation_id TEXT NOT NULL CHECK (octet_length(installation_id) BETWEEN 1 AND 64), source_event_id BYTEA NOT NULL CHECK (length(source_event_id) = 32), diff --git a/schema/tables/public/push_match_queue.sql b/schema/tables/public/push_match_queue.sql index 423c69b4bf3..fd267eec179 100644 --- a/schema/tables/public/push_match_queue.sql +++ b/schema/tables/public/push_match_queue.sql @@ -3,7 +3,7 @@ -- authoritative. Legacy writers may still enqueue in their event transaction. -- Processing is idempotent through the outbox endpoint/event unique key. CREATE TABLE push_match_queue ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, event_id BYTEA NOT NULL CHECK (length(event_id) = 32), state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending','matching')), attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), diff --git a/schema/tables/public/push_wake_outbox.sql b/schema/tables/public/push_wake_outbox.sql index cee9366339d..720b13011c5 100644 --- a/schema/tables/public/push_wake_outbox.sql +++ b/schema/tables/public/push_wake_outbox.sql @@ -1,5 +1,5 @@ CREATE TABLE push_wake_outbox ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id UUID NOT NULL DEFAULT gen_random_uuid(), author BYTEA NOT NULL CHECK (length(author) = 32), installation_id TEXT NOT NULL, @@ -15,8 +15,6 @@ CREATE TABLE push_wake_outbox ( claim_id UUID, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (community_id, id), - FOREIGN KEY (community_id, author, installation_id) - REFERENCES push_leases (community_id, author, installation_id), UNIQUE (community_id, endpoint_hash, event_id) ); CREATE INDEX push_wake_outbox_due diff --git a/schema/tables/public/reactions.sql b/schema/tables/public/reactions.sql index b9ed4488b65..085da0e665f 100644 --- a/schema/tables/public/reactions.sql +++ b/schema/tables/public/reactions.sql @@ -2,7 +2,7 @@ -- Conformance: reactions filter by community before event/pubkey matching. CREATE TABLE reactions ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, event_created_at TIMESTAMPTZ NOT NULL, event_id BYTEA NOT NULL, pubkey BYTEA NOT NULL, diff --git a/schema/tables/public/relay_admin_actions.sql b/schema/tables/public/relay_admin_actions.sql index 0643e29325e..9efd0d427e2 100644 --- a/schema/tables/public/relay_admin_actions.sql +++ b/schema/tables/public/relay_admin_actions.sql @@ -59,9 +59,7 @@ CREATE TABLE relay_admin_actions ( OR (action = 'delete' AND enforcement_target_event_id IS NOT NULL AND enforcement_target_pubkey IS NOT NULL AND timeout_secs IS NULL AND timeout_until IS NULL) - ), - FOREIGN KEY (report_community_id, report_id) - REFERENCES moderation_reports (community_id, id) + ) ); CREATE INDEX idx_relay_admin_actions_report diff --git a/schema/tables/public/relay_admin_outbox.sql b/schema/tables/public/relay_admin_outbox.sql index f81de55ca00..4a5f6ef0780 100644 --- a/schema/tables/public/relay_admin_outbox.sql +++ b/schema/tables/public/relay_admin_outbox.sql @@ -3,7 +3,7 @@ CREATE TABLE relay_admin_outbox ( id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(), - action_id UUID NOT NULL REFERENCES relay_admin_actions(id), + action_id UUID NOT NULL, -- Delivery task type: 'tombstone' | 'system_message' | 'reporter_notice'. task_type TEXT NOT NULL, -- Task payload (JSON). diff --git a/schema/tables/public/relay_invites.sql b/schema/tables/public/relay_invites.sql index d2352f4f419..5a7f2c19527 100644 --- a/schema/tables/public/relay_invites.sql +++ b/schema/tables/public/relay_invites.sql @@ -4,7 +4,7 @@ -- PK and UNIQUE both lead with community_id. max_uses NULL = unlimited. CREATE TABLE relay_invites ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id UUID NOT NULL DEFAULT gen_random_uuid(), token_hash BYTEA NOT NULL CHECK (length(token_hash) = 32), role TEXT NOT NULL DEFAULT 'member' CHECK (role = 'member'), diff --git a/schema/tables/public/relay_members.sql b/schema/tables/public/relay_members.sql index b739e0aa294..0f3b0487d46 100644 --- a/schema/tables/public/relay_members.sql +++ b/schema/tables/public/relay_members.sql @@ -3,7 +3,7 @@ -- (unchanged wire form). PK (community_id, pubkey). CREATE TABLE relay_members ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, pubkey TEXT NOT NULL, role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'member')), added_by TEXT, diff --git a/schema/tables/public/scheduled_workflow_fires.sql b/schema/tables/public/scheduled_workflow_fires.sql index 73be34a6993..2d0329c9c01 100644 --- a/schema/tables/public/scheduled_workflow_fires.sql +++ b/schema/tables/public/scheduled_workflow_fires.sql @@ -7,24 +7,16 @@ -- the claim binds both community and id explicitly rather than resolving from id. -- workflow_run_id links the won claim to the run it created (audit; NULL until the -- post-insert attach, and stays NULL if run creation failed after a won claim). --- The FK to workflow_runs uses NO ACTION (not SET NULL): community_id is shared --- with the claim PK and is NOT NULL, so SET NULL is unimplementable here; a future --- delete of a still-linked run is blocked rather than orphaning the at-most-once --- claim row. Workflow delete removes the workflow's own fires before its runs, so --- attach_scheduled_workflow_run only links a run of the same workflow; a --- cross-workflow link would otherwise block that delete. +-- Workflow delete removes the workflow's own fires before its runs, and +-- attach_scheduled_workflow_run links only an existing run of the same workflow. CREATE TABLE scheduled_workflow_fires ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, workflow_id UUID NOT NULL, scheduled_for TIMESTAMPTZ NOT NULL, claimed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), workflow_run_id UUID, - PRIMARY KEY (community_id, workflow_id, scheduled_for), - FOREIGN KEY (community_id, workflow_id) - REFERENCES workflows (community_id, id) ON DELETE CASCADE, - FOREIGN KEY (community_id, workflow_run_id) - REFERENCES workflow_runs (community_id, id) ON DELETE NO ACTION + PRIMARY KEY (community_id, workflow_id, scheduled_for) ); -- The interval anchor reads MAX(scheduled_for) per workflow; the janitor prunes diff --git a/schema/tables/public/subscriptions.sql b/schema/tables/public/subscriptions.sql index 0e74dfdde53..b57a2b0a507 100644 --- a/schema/tables/public/subscriptions.sql +++ b/schema/tables/public/subscriptions.sql @@ -2,7 +2,7 @@ -- Conformance: "Mesh, agents, ACP/MCP, and CLI" (persisted subscriptions). CREATE TABLE subscriptions ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id VARCHAR(255) NOT NULL, owner_pubkey BYTEA NOT NULL, filter_kinds JSONB, @@ -18,6 +18,5 @@ CREATE TABLE subscriptions ( error_count BIGINT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (community_id, id), - FOREIGN KEY (community_id, owner_pubkey) REFERENCES users (community_id, pubkey) + PRIMARY KEY (community_id, id) ); diff --git a/schema/tables/public/thread_metadata.sql b/schema/tables/public/thread_metadata.sql index 2c9ed9800ac..c7dc8b7dd63 100644 --- a/schema/tables/public/thread_metadata.sql +++ b/schema/tables/public/thread_metadata.sql @@ -2,7 +2,7 @@ -- Conformance: thread lookups filter by community before event matching. CREATE TABLE thread_metadata ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, event_created_at TIMESTAMPTZ NOT NULL, event_id BYTEA NOT NULL, channel_id UUID NOT NULL, @@ -15,8 +15,7 @@ CREATE TABLE thread_metadata ( descendant_count INT NOT NULL DEFAULT 0, last_reply_at TIMESTAMPTZ, broadcast BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (community_id, event_created_at, event_id), - FOREIGN KEY (community_id, channel_id) REFERENCES channels (community_id, id) + PRIMARY KEY (community_id, event_created_at, event_id) ); CREATE INDEX idx_thread_metadata_parent ON thread_metadata (community_id, parent_event_id); diff --git a/schema/tables/public/users.sql b/schema/tables/public/users.sql index 9fb16885886..816ff1a4a51 100644 --- a/schema/tables/public/users.sql +++ b/schema/tables/public/users.sql @@ -3,7 +3,7 @@ -- (community, pubkey): the same key reposts kind:0 in each community it joins. CREATE TABLE users ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, pubkey BYTEA NOT NULL, nip05_handle VARCHAR(255), display_name VARCHAR(255), @@ -19,10 +19,7 @@ CREATE TABLE users ( agent_owner_pubkey BYTEA, channel_add_policy channel_add_policy NOT NULL DEFAULT 'anyone', PRIMARY KEY (community_id, pubkey), - CONSTRAINT chk_users_pubkey_len CHECK (LENGTH(pubkey) = 32), - -- agent owner is a user in the SAME community. - FOREIGN KEY (community_id, agent_owner_pubkey) - REFERENCES users (community_id, pubkey) ON DELETE SET NULL + CONSTRAINT chk_users_pubkey_len CHECK (LENGTH(pubkey) = 32) ); -- NIP-05 handle and Okta id unique within a community, not globally. diff --git a/schema/tables/public/workflow_approvals.sql b/schema/tables/public/workflow_approvals.sql index 6f91297345b..c954614d343 100644 --- a/schema/tables/public/workflow_approvals.sql +++ b/schema/tables/public/workflow_approvals.sql @@ -3,7 +3,7 @@ -- community's same hash (conformance). CREATE TABLE workflow_approvals ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, token BYTEA NOT NULL, workflow_id UUID NOT NULL, run_id UUID NOT NULL, @@ -17,11 +17,7 @@ CREATE TABLE workflow_approvals ( denied_at TIMESTAMPTZ, expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (community_id, token), - FOREIGN KEY (community_id, workflow_id) - REFERENCES workflows (community_id, id) ON DELETE CASCADE, - FOREIGN KEY (community_id, run_id) - REFERENCES workflow_runs (community_id, id) ON DELETE CASCADE + PRIMARY KEY (community_id, token) ); CREATE INDEX idx_workflow_approvals_workflow ON workflow_approvals (community_id, workflow_id); diff --git a/schema/tables/public/workflow_runs.sql b/schema/tables/public/workflow_runs.sql index 61d48b0f9e1..7ee95dd16e0 100644 --- a/schema/tables/public/workflow_runs.sql +++ b/schema/tables/public/workflow_runs.sql @@ -1,7 +1,7 @@ -- ── Workflow runs ───────────────────────────────────────────────────────────── CREATE TABLE workflow_runs ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id UUID NOT NULL DEFAULT gen_random_uuid(), workflow_id UUID NOT NULL, status run_status NOT NULL DEFAULT 'pending', @@ -20,9 +20,7 @@ CREATE TABLE workflow_runs ( CONSTRAINT workflow_runs_cause_source_check CHECK (cause_source IN ('event', 'schedule', 'webhook', 'manual')), CONSTRAINT workflow_runs_cause_pubkey_check - CHECK (length(cause_pubkey) = 32), - FOREIGN KEY (community_id, workflow_id) - REFERENCES workflows (community_id, id) ON DELETE CASCADE + CHECK (length(cause_pubkey) = 32) ); CREATE INDEX idx_workflow_runs_workflow ON workflow_runs (community_id, workflow_id); diff --git a/schema/tables/public/workflows.sql b/schema/tables/public/workflows.sql index dba16b42e5d..a850e9918b2 100644 --- a/schema/tables/public/workflows.sql +++ b/schema/tables/public/workflows.sql @@ -3,7 +3,7 @@ -- community fixed at create from req.community; runs/approvals inherit it. CREATE TABLE workflows ( - community_id UUID NOT NULL REFERENCES communities(id), + community_id UUID NOT NULL, id UUID NOT NULL DEFAULT gen_random_uuid(), name VARCHAR(255) NOT NULL, owner_pubkey BYTEA NOT NULL, @@ -14,9 +14,7 @@ CREATE TABLE workflows ( enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (community_id, id), - FOREIGN KEY (community_id, owner_pubkey) REFERENCES users (community_id, pubkey), - FOREIGN KEY (community_id, channel_id) REFERENCES channels (community_id, id) + PRIMARY KEY (community_id, id) ); CREATE INDEX idx_workflows_channel_active ON workflows (community_id, channel_id, status, enabled); diff --git a/scripts/drop-partitioned-foreign-keys.sql b/scripts/drop-partitioned-foreign-keys.sql new file mode 100644 index 00000000000..677850a4b97 --- /dev/null +++ b/scripts/drop-partitioned-foreign-keys.sql @@ -0,0 +1,30 @@ +-- Drop the foreign keys on the partitioned tables before pgschema apply. +-- +-- pgschema cannot drop a foreign key from a partitioned table. Its plan drops +-- the parent's constraint, then the copy on each partition, which the first +-- drop already removed (SQLSTATE 42704). This file runs migration 0104's drop +-- for a database that pgschema brings up to date instead. +-- +-- For the test launchers only: scripts/start-relay-for-tests.sh, which reuses +-- its database, and the populated-upgrade test run it before apply. +-- Deployments apply migration 0104 instead (docs/database.md, "Retiring a +-- trigger, function, or foreign key"). It does nothing on an empty database or +-- one without the keys. +-- +-- As in 0104: each drop locks the table, every partition and communities, so +-- take every lock in one statement, communities last, with budgets that end +-- the attempt before the 1s deadlock_timeout. On failure nothing changes; +-- retry. +BEGIN; +SET LOCAL lock_timeout = '300ms'; +SET LOCAL statement_timeout = '800ms'; +DO $$ +BEGIN + IF to_regclass('events') IS NULL THEN + RETURN; + END IF; + LOCK TABLE events, delivery_log, communities IN ACCESS EXCLUSIVE MODE; + ALTER TABLE events DROP CONSTRAINT IF EXISTS events_community_id_fkey; + ALTER TABLE delivery_log DROP CONSTRAINT IF EXISTS delivery_log_community_id_fkey; +END $$; +COMMIT; diff --git a/scripts/start-relay-for-tests.sh b/scripts/start-relay-for-tests.sh index 36973ed0aab..ee3f0bbd6b4 100755 --- a/scripts/start-relay-for-tests.sh +++ b/scripts/start-relay-for-tests.sh @@ -107,6 +107,9 @@ export PGSCHEMA_PLAN_PASSWORD=buzz_dev # repair existed would fail apply, so repair it first (see the script). docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 < scripts/repair-events-pkey.sql +# pgschema cannot drop the partitioned tables' foreign keys (see the script). +docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ + psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 < scripts/drop-partitioned-foreign-keys.sql ./bin/pgschema apply --file schema/schema.sql --auto-approve docker exec -i -e PGPASSWORD="${PGPASSWORD}" buzz-postgres \ psql -U "${PGUSER}" -d "${PGDATABASE}" -v ON_ERROR_STOP=1 < scripts/reconcile-schema-after-pgschema.sql