Files
buzz/crates/buzz-db/src/test_support.rs
Luke Tornquist 52d13efc08 fix(buzz-db): delete workflow and membership children explicitly (#8212)
## What

Workflow deletion and relay-member removal relied on `ON DELETE CASCADE`
to remove child rows. Both paths now delete their own children inside
the same transaction, so a later migration can drop those foreign-key
actions without changing behavior.

**Workflow deletion** (`store/workflow/deletion.rs`, the coordinate path
used by NIP-09 deletes of workflow definitions):
- Locks the target workflow row with `SELECT … FOR UPDATE`, under the
same owner and coordinate predicate as before. A concurrent run or fire
insert has to lock that row for its foreign key, so the child deletes
see every committed child.
- Deletes scheduled fires first. A new fire has to lock the workflow
row, and a cron attach locks the fire before the run, so deleting fires
before the run lock keeps the lock order consistent and avoids a
deadlock.
- Then locks the workflow's runs `FOR UPDATE` in `id` order. An approval
that names another workflow but references one of these runs key-share
locks only the run, so the workflow lock alone doesn't exclude it.
- `delete_workflow_with_children` then deletes approvals (for the
workflow or any of its runs), then runs, then the workflow, and returns
its `channel_id`.

**Relay-member removal** (`store/relay_members.rs`):
`remove_relay_member` and `remove_relay_member_if_role` share a new
`delete_member_with_acceptances` helper. It locks the member row under
the existing predicate (any non-owner, or an exact role), deletes
`join_policy_acceptances`, then deletes the member, in one transaction.
The `RemoveResult` outcomes are unchanged.

**Removed:** `delete_workflow` (no callers) and
`delete_workflow_for_owner` (test-only), plus their `Db` wrappers. The
community-confinement test now drives the production coordinate
deletion.

## Tests

- `test_support::retire_foreign_key_delete_actions` rewrites every
`CASCADE`, `SET NULL` and `SET DEFAULT` foreign key in the test's own
per-test database as `NO ACTION`, which is the target schema of the
follow-up migration. It asserts that none remain. All triggers stay
live, including foreign-key checks and the community write fence. It
refuses to run unless `current_database()` has the per-test wrapper's
exact shape (`buzz_nt_` plus 24 hex digits), which excludes the run's
`_desired` template. It checks the name only.
- `workflow_deletion_removes_children_without_cascades` and
`member_removal_deletes_acceptances_without_cascades` run the production
paths on that schema and require every child row to be gone. One
approval references another workflow but this workflow's run, which pins
the `run_id` branch. The owner, role-mismatch and not-found outcomes
still hold.
- `workflow_deletion_waits_for_and_removes_concurrent_run` and
`member_removal_waits_for_and_removes_concurrent_acceptance` hold a
child insert open in a second transaction, wait until the removal is
blocked on a lock, and then commit. The removal must succeed with no
children left.
- `workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock`
holds a fire row the way the cron attach does, then attaches a run to it
while the deletion waits. Both must succeed.
-
`workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_approval`
does the same with an approval for another workflow that references this
workflow's run.
- The bridge test schema now includes `join_policy_acceptances`.

## What got simpler

Two delete paths no longer depend on implicit constraint actions, and
two unused workflow-delete functions are gone. This is the first step of
retiring the `CASCADE` and `SET NULL` foreign keys.

**Identified debt (later PRs):** `channel_members` and
`personal_read_frontiers` (no hard-delete path found yet for their
parents), the deletion `manifest_keys` cascade, the `SET NULL` actions
on `executor_heartbeats` and `product_feedback`, and the `users`
self-reference. That last one is a composite `(community_id,
agent_owner_pubkey)` `ON DELETE SET NULL` that would try to null the
`NOT NULL` `community_id`. Also, a scheduled fire for workflow B can
link to a run of A (that FK is already `NO ACTION`), which would block
A's run delete; the scheduler always attaches a run to its own
workflow's fire, so this needs same-workflow enforcement in the cascade
work.

## Verification

Head `081be4c0d`, tree `ab649487`, on a Linux cloud workstation: fmt,
buzz-db and workspace clippy, source policy and buzz-db lib pass; the
six new tests pass; buzz-db PostgreSQL passes 490/490 and buzz-relay
PostgreSQL 378/378. A sixth mutation, moving the fire delete back after
the run lock, makes
`workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock`
fail with `40P01` (deadlock detected).

Previous head:

Head `787c7c42d`, tree `6b9cf5d5`, on a Linux cloud workstation: fmt,
buzz-db and workspace clippy, source policy and buzz-db lib pass; the
new tests pass 5/5; buzz-relay PostgreSQL passes 378/378; buzz-db
PostgreSQL passes 488/489, the one failure being
`parent_contention_times_out_without_blocking_the_other_table` in
`store/partition/`, which this PR doesn't touch and which passes on its
own at the same tree. A fifth mutation, removing the run lock, makes the
new cross-workflow approval test fail with the reviewer's exact 23503 on
`workflow_approvals_community_id_run_id_fkey`.

Previous head `00cba2f4a`, tree `2f89fed4`, base `e9269cbdf`. Results
from a Linux cloud workstation:
- fmt, buzz-db and workspace clippy, the source policy and buzz-db lib
all pass.
- The buzz-db PostgreSQL suite passes 488/488.
- The buzz-relay PostgreSQL suite passes 378/378.

Each of four mutations makes exactly one of the new tests fail with the
foreign-key violation you'd expect (23503):
- swapping the fires and runs deletes
- deleting approvals by `workflow_id` only
- removing the workflow row lock
- removing the member row lock

GitHub CI is green at this head.






buzz-review-completed

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
2026-10-14 08:27:26 -04:00

175 lines
7.1 KiB
Rust

const DEFAULT_DATABASE_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials
/// Resolve the database URL shared by PostgreSQL-backed unit tests.
pub(crate) fn database_url() -> String {
std::env::var("BUZZ_TEST_DATABASE_URL")
.or_else(|_| std::env::var("TEST_DATABASE_URL"))
.or_else(|_| std::env::var("DATABASE_URL"))
.unwrap_or_else(|_| DEFAULT_DATABASE_URL.to_owned())
}
/// Move a community fixture into a deletion lifecycle state the way the
/// executor does: the tombstone trigger only accepts lifecycle changes from a
/// transaction carrying the executor GUCs for that community, including its
/// current fence generation.
pub(crate) async fn set_deletion_state(pool: &sqlx::PgPool, id: uuid::Uuid, state: &str) {
let mut tx = pool.begin().await.expect("begin lifecycle fixture");
sqlx::query(
"SELECT set_config('buzz.deletion_executor_community', $1, true), \
set_config('buzz.deletion_fence_generation', \
(SELECT deletion_fence_generation::text FROM communities WHERE id = $2), true)",
)
.bind(id.to_string())
.bind(id)
.execute(&mut *tx)
.await
.expect("authorize lifecycle fixture");
sqlx::query(
"UPDATE communities SET deletion_state = $2, \
deleted_at = CASE WHEN $2 = 'tombstone' THEN now() END \
WHERE id = $1",
)
.bind(id)
.bind(state)
.execute(&mut *tx)
.await
.expect("set lifecycle state");
tx.commit().await.expect("commit lifecycle fixture");
}
/// Move a disposable test community into `quiescing`, the state in which
/// admission must reject new serving writes.
pub(crate) async fn quiesce_community_for_tests(
pool: &sqlx::PgPool,
community: buzz_core::CommunityId,
) {
set_deletion_state(pool, *community.as_uuid(), "quiescing").await;
}
/// Whether `error` is the community-admission rejection taken at transaction
/// entry, as opposed to a later commit-time trigger rejection.
pub(crate) fn is_admission_rejection(error: &crate::DbError) -> bool {
matches!(error, crate::DbError::AccessDenied(message) if message.contains("write-fenced (quiescing)"))
}
/// The desired-state schema as one SQL script.
///
/// `schema/schema.sql` is a manifest of `\i` includes resolved relative to the
/// including file (as `pgschema` does). This expands every include in place,
/// so text assertions and `sqlx::raw_sql` bootstraps see the same statements,
/// in the same order, that `pgschema apply` loads.
pub(crate) fn desired_state_schema_sql() -> String {
fn expand(path: &std::path::Path, out: &mut String) {
let text = std::fs::read_to_string(path)
.unwrap_or_else(|error| panic!("read {}: {error}", path.display()));
let dir = path.parent().expect("schema file has a parent directory");
for line in text.split_inclusive('\n') {
match line.trim_end().strip_prefix("\\i ") {
Some(include) => expand(&dir.join(include.trim()), out),
None => out.push_str(line),
}
}
if !out.ends_with('\n') {
out.push('\n');
}
}
let mut out = String::new();
expand(&desired_state_schema_dir().join("schema.sql"), &mut out);
out
}
/// `schema/` at the workspace root.
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) {
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"
);
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");
}
/// 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 {
use std::str::FromStr as _;
let options = sqlx::postgres::PgConnectOptions::from_str(&database_url())
.expect("parse test database URL")
.application_name(application_name);
sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.expect("connect named test pool")
}
/// Wait until the session named `application_name` in this test's database is
/// blocked on a lock.
pub(crate) async fn wait_for_lock_wait(pool: &sqlx::PgPool, application_name: &str) {
tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
let waiting: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pg_stat_activity \
WHERE datname = current_database() AND application_name = $1 \
AND wait_event_type = 'Lock')",
)
.bind(application_name)
.fetch_one(pool)
.await
.expect("inspect lock wait");
if waiting {
break;
}
tokio::task::yield_now().await;
}
})
.await
.expect("session reached a lock wait");
}