Skip to content

Commit 729cb10

Browse files
buzz-db: drop the remaining relay foreign keys (#9740)
1 parent 9bcb3e4 commit 729cb10

65 files changed

Lines changed: 610 additions & 462 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 106 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -879,7 +879,19 @@ mod postgres_tests {
879879
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
880880
migrations.sort_by_key(|migration| migration.version);
881881

882-
assert_eq!(migrations.len(), 101);
882+
assert_eq!(migrations.len(), 104);
883+
assert_eq!(migrations[103].version, 104);
884+
let event_table_drops = strip_sql_comments(migrations[103].sql.as_str());
885+
assert!(event_table_drops
886+
.contains("LOCK TABLE events, delivery_log, communities IN ACCESS EXCLUSIVE MODE;"));
887+
assert!(event_table_drops.contains("DROP CONSTRAINT events_community_id_fkey;"));
888+
assert_eq!(migrations[102].version, 103);
889+
assert!(strip_sql_comments(migrations[102].sql.as_str())
890+
.contains("ALTER TABLE users DROP CONSTRAINT users_community_id_fkey;"));
891+
assert_eq!(migrations[101].version, 102);
892+
assert!(strip_sql_comments(migrations[101].sql.as_str()).contains(
893+
"ALTER TABLE join_policy_acceptances DROP CONSTRAINT join_policy_acceptances_community_id_pubkey_fkey;"
894+
));
883895
assert_eq!(migrations[100].version, 101);
884896
assert!(strip_sql_comments(migrations[100].sql.as_str())
885897
.contains("DROP CONSTRAINT IF EXISTS push_gateway_delegations_installation_id_fkey"));
@@ -1843,6 +1855,23 @@ mod postgres_tests {
18431855
);
18441856
}
18451857

1858+
/// pgschema cannot drop a foreign key from a partitioned table, so the
1859+
/// launcher that reuses its database drops those keys before apply.
1860+
#[test]
1861+
fn partitioned_foreign_key_drop_runs_before_reused_apply() {
1862+
let launcher = include_str!("../../../../scripts/start-relay-for-tests.sh");
1863+
let drop_at = launcher
1864+
.find("scripts/drop-partitioned-foreign-keys.sql")
1865+
.expect("start-relay-for-tests.sh runs scripts/drop-partitioned-foreign-keys.sql");
1866+
let apply_at = launcher
1867+
.find("./bin/pgschema apply")
1868+
.expect("start-relay-for-tests.sh runs pgschema apply");
1869+
assert!(
1870+
drop_at < apply_at,
1871+
"start-relay-for-tests.sh must drop the partitioned foreign keys before pgschema apply"
1872+
);
1873+
}
1874+
18461875
/// The reconcile script repairs `events_pkey` after every apply, and
18471876
/// `start-relay-for-tests.sh` runs the same repair before apply so a reused
18481877
/// database reconciled before the repair existed can still be applied.
@@ -2440,6 +2469,41 @@ mod postgres_tests {
24402469
strings
24412470
}
24422471

2472+
/// Drop foreign-key elements and inline `REFERENCES` clauses from a
2473+
/// normalized `CREATE TABLE`.
2474+
fn without_foreign_keys(table: &str) -> String {
2475+
let open = table.find('(').expect("table body");
2476+
let close = find_matching_paren(table, open).expect("table body end");
2477+
let elements: Vec<String> = split_top_level_csv(&table[open + 1..close])
2478+
.into_iter()
2479+
.filter(|element| !element.starts_with("foreign key"))
2480+
.map(|element| {
2481+
let Some(start) = element.find(" references ") else {
2482+
return element;
2483+
};
2484+
let paren = start + element[start..].find('(').expect("referenced columns");
2485+
let mut end = find_matching_paren(&element, paren).expect("columns end") + 1;
2486+
for action in [
2487+
" on delete cascade",
2488+
" on delete set null",
2489+
" on delete restrict",
2490+
" on delete no action",
2491+
] {
2492+
if element[end..].starts_with(action) {
2493+
end += action.len();
2494+
}
2495+
}
2496+
format!("{}{}", &element[..start], &element[end..])
2497+
})
2498+
.collect();
2499+
format!(
2500+
"{}({}){}",
2501+
&table[..open],
2502+
elements.join(", "),
2503+
&table[close + 1..]
2504+
)
2505+
}
2506+
24432507
fn surface(sql: &str) -> DeletionSurface {
24442508
let mut surface = DeletionSurface::default();
24452509
for statement in split_sql_statements(sql) {
@@ -2511,9 +2575,11 @@ mod postgres_tests {
25112575
.tables
25122576
.get(table)
25132577
.unwrap_or_else(|| panic!("schema.sql is missing deletion table {table}"));
2578+
// 0102-0104 dropped every foreign key; the rest must not drift.
25142579
if table != "community_deletion_requests" && table != "community_deletion_approvals" {
25152580
assert_eq!(
2516-
in_schema, definition,
2581+
without_foreign_keys(in_schema),
2582+
without_foreign_keys(definition),
25172583
"schema.sql definition of {table} drifted from migration 0029"
25182584
);
25192585
}
@@ -2526,19 +2592,15 @@ mod postgres_tests {
25262592
.tables
25272593
.get("community_deletion_approvals")
25282594
.expect("schema.sql approval table");
2529-
for invariant in [
2530-
"inventory_digest bytea not null check (length(inventory_digest) = 32)",
2531-
"foreign key (request_id, community_id, inventory_digest) references community_deletion_requests(id, community_id, inventory_digest) on delete restrict",
2532-
] {
2533-
assert!(
2534-
migration_approval_table.contains(invariant),
2535-
"0029 deletion approvals are missing {invariant}"
2536-
);
2537-
assert!(
2538-
schema_approval_table.contains(invariant),
2539-
"schema.sql deletion approvals are missing {invariant}"
2540-
);
2541-
}
2595+
let invariant = "inventory_digest bytea not null check (length(inventory_digest) = 32)";
2596+
assert!(
2597+
migration_approval_table.contains(invariant),
2598+
"0029 deletion approvals are missing {invariant}"
2599+
);
2600+
assert!(
2601+
schema_approval_table.contains(invariant),
2602+
"schema.sql deletion approvals are missing {invariant}"
2603+
);
25422604
let migration_request_table = migration
25432605
.tables
25442606
.get("community_deletion_requests")
@@ -2668,13 +2730,17 @@ mod postgres_tests {
26682730
.as_str();
26692731
assert!(through_message.contains("DROP COLUMN threads_through_timestamp"));
26702732
for (table, definition) in personal.tables {
2733+
// `without_foreign_keys` also normalizes spacing, so apply it to both.
26712734
let in_schema = schema.tables.get(&table).map(|schema_definition| {
2735+
let schema_definition = without_foreign_keys(schema_definition);
26722736
if table == "personal_read_accounts" {
26732737
schema_definition.replacen(started_at_column, "", 1)
26742738
} else {
2675-
schema_definition.clone()
2739+
schema_definition
26762740
}
26772741
});
2742+
// 0102 dropped the foreign keys that 0056 created.
2743+
let definition = without_foreign_keys(&definition);
26782744
let definition = if table == "personal_read_frontiers" {
26792745
definition.replacen(threads_through_column, through_message_column, 1)
26802746
} else {
@@ -3152,6 +3218,30 @@ mod postgres_tests {
31523218
migration and schema.sql must both use a representable shape."
31533219
);
31543220
}
3221+
// docs/database.md Rule 2: 0102-0104 dropped every foreign key, and
3222+
// schema/ declares none, so neither bootstrap path has one.
3223+
async fn foreign_keys(pool: &PgPool) -> Vec<(String, String)> {
3224+
sqlx::query_as(
3225+
"SELECT con.conrelid::regclass::text, con.conname::text \
3226+
FROM pg_constraint con \
3227+
JOIN pg_namespace n ON n.oid = con.connamespace \
3228+
WHERE n.nspname = 'public' AND con.contype = 'f' \
3229+
ORDER BY 1, 2",
3230+
)
3231+
.fetch_all(pool)
3232+
.await
3233+
.expect("read foreign keys")
3234+
}
3235+
assert_eq!(
3236+
foreign_keys(&desired).await,
3237+
Vec::new(),
3238+
"desired state has a foreign key"
3239+
);
3240+
assert_eq!(
3241+
foreign_keys(&migrated).await,
3242+
Vec::new(),
3243+
"migrations leave a foreign key"
3244+
);
31553245
async fn media_edit_index(pool: &PgPool) -> (String, String, String) {
31563246
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")
31573247
.fetch_one(pool).await.expect("valid media edit index")

‎crates/buzz-db/src/store/channel.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1375,8 +1375,8 @@ async fn lock_channel_row(
13751375
lock_channel_ttl(tx, channel_id, ttl).await?;
13761376
// `FOR NO KEY UPDATE`, like a huddle join: it orders this write against
13771377
// every other settings write and a huddle join, but not against a
1378-
// `KEY SHARE` lock on the channel (a membership INSERT's foreign key while
1379-
// it exists, `insert_auto_membership`'s channel check).
1378+
// `KEY SHARE` lock on the channel (`insert_auto_membership`'s channel
1379+
// check).
13801380
let (previous_visibility, archived, listed): (String, bool, bool) =
13811381
sqlx::query_as(sqlx::AssertSqlSafe(format!(
13821382
"SELECT visibility::text, archived_at IS NOT NULL, {LISTED_CHANNEL_SQL} FROM channels \

‎crates/buzz-db/src/store/channel_members.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -307,8 +307,8 @@ pub async fn lock_channel_memberships_in_transaction<'tx>(
307307
/// rolls back, so a join cannot commit into a channel archived concurrently.
308308
/// `FOR UPDATE` would invert the lock order against a membership writer that
309309
/// key-share locks `channels` after taking the advisory membership lock
310-
/// ([`ChannelMembershipLocks::insert_auto_membership`]'s channel check, and a
311-
/// membership INSERT's foreign key while it exists); `FOR NO KEY UPDATE` still
310+
/// ([`ChannelMembershipLocks::insert_auto_membership`]'s channel check);
311+
/// `FOR NO KEY UPDATE` still
312312
/// blocks archive (a non-key update) and a delete, but is compatible with
313313
/// `KEY SHARE`. Re-reading under the lock is safe: the caller already holds it.
314314
pub async fn lock_channel_archived_at_in_transaction(

‎crates/buzz-db/src/store/community.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ impl Db {
823823
/// Locks the community row before reading ownership so a concurrent owner
824824
/// transfer, whose `FOR NO KEY UPDATE` conflicts with this one, has one
825825
/// serial order with the archive. The weaker lock lets the archive
826-
/// proceed past foreign-key child inserts' `FOR KEY SHARE`. A single
826+
/// proceed past reference checks' `FOR KEY SHARE`. A single
827827
/// `UPDATE ... FROM relay_members` would keep its pre-lock ownership
828828
/// snapshot after waiting and could archive the new owner's community on
829829
/// the old owner's assertion.
@@ -1601,8 +1601,8 @@ mod postgres_tests {
16011601
.expect("restored community state"));
16021602
}
16031603

1604-
/// Foreign-key child inserts hold `FOR KEY SHARE` on the community row for
1605-
/// their whole transaction. Archive and the lifecycle fences must not queue
1604+
/// Reference checks hold `FOR KEY SHARE` on the community row for their
1605+
/// whole transaction. Archive and the lifecycle fences must not queue
16061606
/// behind them, or a busy community stalls the operator archive and
16071607
/// revalidation and conn-control on every pod. `FOR UPDATE` would block
16081608
/// here; `FOR NO KEY UPDATE` must not.

0 commit comments

Comments
 (0)