From 598fcae0cdad02dd10674a9ca6421761db6b4e91 Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Mon, 16 Nov 2026 11:49:29 -0500 Subject: [PATCH] buzz-db: drop the created_at floor, community write-fence and migration-only NIP-RS triggers (contract) (#8326) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > **Combined contract PR.** This PR now carries all three trigger drops that were stacked as #8326 → #8323 → #8211. Each drop's prerequisite app change has already shipped to production, and none of them depends on another, so they ship as one release with one migration per drop: > - `0089`: `events_created_at_floor` (this PR's original scope, BUZZ-316; phase 1 #8325 is on prod) > - `0090`: the universal community write-fence triggers and functions (from #8323, BUZZ-315; app admission #8219/#8318/#8322) > - `0091`: the migration-only NIP-RS, mention-live and mesh-purge triggers (from #8211, BUZZ-312; prerequisite #8128) > > #8323 and #8211 keep their full write-ups. The commits are cherry-picked unchanged except for the renumbering commit at the tip. #8211's post-rollout cleanup SQL still runs after this deploys. ## Summary Phase 2 of BUZZ-316. This is a destructive contract change. Phase 1, #8325 (merged), added the insert-time application floor check. After phase 1, the app check at every channel-bearing `INSERT INTO events` is the only `created_at` floor guard. This PR removes the database backstop and everything that existed only to verify it: - **Migration 0089** drops the deferred constraint trigger `events_created_at_floor` on `events`. That also removes its partition clones. It then loops over `pg_partition_tree('events')` to drop any child copy that was attached separately, and drops the `events_created_at_floor_guard()` function. Every drop uses `IF EXISTS` and none uses `CASCADE`. The migration sets `lock_timeout` to 5s. Migration 0021 stays byte-for-byte unchanged. - **Desired state:** removes the function file, its `schema.sql` include, the trigger in `schema/triggers/events.sql`, and the eight child-copy drops in `scripts/reconcile-schema-after-pgschema.sql`. Both boot paths stay catalog-equivalent, and `admin_schema_parity_between_desired_state_and_migrations` passes. - **Runtime:** deletes `verify_floor_guard_catalog`, `verify_floor_guard_behavior`, and the boot wrapper that gated the probe on them. Also deletes the writer-pool `buzz.created_at_floor` GUC arming and its `CreatedAtFloor` connection-setup metric step. The setup-series ceiling drops from 71 to 54. `spawn_fence_probe` becomes synchronous and returns `bool`, so the relay's startup error branch goes away. `CREATED_AT_FLOOR_SECS` (960s) stays because the app check and the fence wall both use it. - **Kept:** every other fail-closed probe check. That covers writer-pool isolation and timeouts, partition topology, the activity scan, the heartbeat/epoch checks, and closing on probe error. No other trigger, function, FK, or tenant fence is touched. ## Deploy gate (required) **Required stop:** the new `docs/trigger-retirement-deployment.md` names it (docs/database.md Rule 5). Relay deployments track images built from `main` and no release is being cut, so a docs follow-up rewords it as any relay build at or after `68785206` (#8325's merge). `relay-v0.3.0` has the 0090/0091 prerequisites but not #8325, so a deployment on it must move to such a build first. The doc also covers the auto-migration-off order, the pgschema parent-trigger note, the #8211 cleanup, and rollback. 1. Phase 1 must be running on **every** writer pod and job, with no rollback expected. Pods that are already running never recheck the guard, so a rolling deploy on its own is not enough. 2. Stop out-of-band writers: direct SQL, COPY, restores, seed scripts, and anything that prepares transactions. 3. Hold the replica breaker closed from before the drop until replay catches up and the new scheme is verified. 4. Run the migration off-peak. `DROP TRIGGER` takes `ACCESS EXCLUSIVE` on `events` and every partition, so expect `events` reads and writes to stall for up to the 5s `lock_timeout`. A lock timeout aborts the migration transaction and is safe to retry. Under auto-migrate, the pod fails boot, restarts, and retries. Mixed-version behavior: - **A phase-1 pod that restarts after the drop, default config (`migrate.autoMigrate: true` in the chart):** sqlx finds applied migration 89 missing from its embedded set and returns `VersionMissing(89)`. Boot is fatal and the pod **crash-loops**. A binary rollback is therefore unsafe once 0089 has run. - **The same pod with auto-migrate off:** `verify_floor_guard_catalog` fails, the fence starts closed, and the relay degrades the `ReplicaFenceProbe` startup step. It keeps serving, with cursor reads on the writer. - **This binary against a database that still has the trigger:** boots and runs. It neither requires nor arms the guard. ## Tests `crates/buzz-db/src/runtime/tests/floor_retirement.rs` adds four PostgreSQL tests. CI's nextest filter picks them up through `postgres_tests::`: - the migration drops the parent trigger, its partition clones, and the function, and leaves every other trigger and FK unchanged; - the migration removes a separately attached child copy and can safely run twice; - the desired-state catalog has no floor objects; - the production writer pool no longer arms the GUC, and the probe runs against the retired schema. All four fail when the change is reverted (0/4 pass) and pass with it (4/4). Four tests that only exercised the trigger or the probes are deleted. The outbox durable-failure regression is kept: it now injects an isolated `BEFORE INSERT` failure instead of arming the floor. The phase-1 floor fixture no longer disables a trigger that no longer exists. It still asserts that no enabled floor trigger can mask the app check. With the trigger gone, the floor source policy (`every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it`) is the only guard against a writer that skips the app check or rewrites `created_at`/`channel_id` on an existing row. Phase 1 already makes it scan every crate's `src`. This PR closes two matcher gaps the trigger used to cover: - `UPDATE events SET(created_at, …)` written with no space before the parenthesis; - `INSERT INTO events … ON CONFLICT … DO UPDATE SET channel_id = …`, which names no table but can re-home an existing row below the floor. Each `DO UPDATE` is bound to the INSERT it belongs to, so a watermark upsert that sets `created_at` next to a guarded events insert (the replaceable-event writer's shape) is not flagged. Both gaps have negative fixtures, plus controls for a non-floor-column upsert, `DO NOTHING`, and the watermark shape. The policy also now fails closed on SQL the per-function literal scan could not attribute to a writer (`event_floor_policy_fails_closed_on_sql_it_cannot_attribute`): - `include_str!` is expanded from the file it loads, and `concat!` becomes one literal, with an `{opaque}` placeholder for each non-literal argument. Every delimiter (`()`, `[]`, `{}`) and path prefix (`::core::concat!`) is recognized. - Every SQL literal is checked on its own as well as per function. Anything the policy cannot attribute is a violation: a write target or `SET` column that is a placeholder (`concat!` or `format!`); a `SET` list of floor columns whose `UPDATE` is in another literal; an `UPDATE events` or `DO UPDATE` whose `SET` list continues in another literal or argument (empty, or an item with no `=`, as in `format!("UPDATE events SET {}", …)` or `QueryBuilder::new("UPDATE events SET ").push(…)`); an `INSERT INTO` with no table after it in the literal, or an events INSERT with a placeholder tail; `events` written by `MERGE INTO`/`COPY`; and event-write SQL in a `const`, `static`, or macro body outside any function. A placeholder in a `WHERE` or a value is allowed, so the retention deletes (`concat!` around a predicate macro) and the tenant-severing `UPDATE {table} SET community_id = NULL` pass. - An `include_str!` whose path is not one readable literal and any sqlx `query_file*!` macro are violations. Nothing uses `query_file`. - `PREPARE TRANSACTION` in any production literal, including a dangling `PREPARE`, is a violation (see below). - Function slices are cut to their own item, so a trailing `const` is judged at item level instead of being credited to the function before it. **Prepared transactions.** The fence used to bound a prepared (2PC) transaction by `pg_prepared_xacts.prepared`. That only held because the deferred trigger checked its rows at `PREPARE`; the insert-time check runs earlier, at a time `pg_prepared_xacts` does not expose. So the probe no longer folds `prepared` into the wall: any prepared transaction fails the sample closed (`ProbeError::PreparedTransactions`). No supported writer prepares transactions (now source-policy enforced) and `max_prepared_transactions` defaults to 0, so in supported deployments this never fires. `cluster_global_sample_writer_fails_closed_on_prepared_transaction` asserts 2PC is unavailable at the default setting, and asserts the fail-closed error when the server allows it. CI runs only the default branch; the 2PC-enabled branch and a check-removed falsification run are pinned from the Blox gate. The prepared count is cluster-wide, like the activity scan. ## Verification Head `6ef31ef113` (before the fold). On Blox, fmt, clippy and buzz-db unit pass, and the full buzz-db PostgreSQL lane passes except `media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`, which fails only on the Blox host (it passes in CI). The two `floor_retirement` tests were fixed after that run, so they were rerun on their own and pass at this head. ## What got simpler The change is net −600 lines. Gone are one function, one parent constraint trigger plus its partition clones, two startup probes and their scratch helper, one boot wrapper, the per-connection GUC setup, one metric step, and an async startup branch that could no longer be reached. ## Notes - Migration number: `0089`, the first free number after main's `0088` (workflow run cause). The fence drop (`0090`) and NIP-RS drop (`0091`) follow it in this PR. - Restack: `floor_retirement.rs` now snapshots at `0088` and compares after `0089` alone, then runs the later migrations. The held-writer media prebuild test in `migration.rs` now stops at `0088` while the writer is held, then rolls the writer back before applying the rest. Otherwise a later `DROP TRIGGER` migration in the stack waits on that writer's lock (`55P03`). The floor policy's `SET` list ends at a top-level `WHERE` or `RETURNING` (a subquery's `WHERE` no longer hides later assignments). An `UPDATE` `SET` list that runs to the end of its literal fails closed, and an open events upsert list is read on through later literals (`QueryBuilder` pushes). `events_p*` partitions count as `events` in every check. `replacement_scope!` now leaves `WHERE` to its callers so the policy can see the supersede `UPDATE`'s list end; the SQL is unchanged. - Pre-existing, unrelated to this change: three `buzz-relay` `group_state_postgres_tests` hit `PoolTimedOut` on a clean base too. --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Luke Tornquist Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 --- ARCHITECTURE.md | 52 +- crates/buzz-db/src/lib.rs | 6 +- crates/buzz-db/src/runtime/admitted_tx.rs | 8 +- .../src/runtime/connection_observability.rs | 39 +- crates/buzz-db/src/runtime/migration.rs | 388 ++++---- crates/buzz-db/src/runtime/mod.rs | 86 +- crates/buzz-db/src/runtime/observability.rs | 14 +- crates/buzz-db/src/runtime/replica_fence.rs | 333 ++----- crates/buzz-db/src/runtime/tests.rs | 687 +------------ .../src/runtime/tests/floor_retirement.rs | 145 +++ .../schema_fence_bootstrap_postgres_tests.rs | 39 - .../tests/thread_window_postgres_tests.rs | 9 +- crates/buzz-db/src/store/deletion.rs | 232 ++--- crates/buzz-db/src/store/event.rs | 7 +- crates/buzz-db/src/store/event_deletion.rs | 201 +++- .../src/store/event_floor_postgres_tests.rs | 13 +- crates/buzz-db/src/store/push.rs | 8 - crates/buzz-db/src/store/relay_invite.rs | 6 +- .../relay_invite/upgrade_postgres_tests.rs | 13 +- crates/buzz-db/src/store/replaceable.rs | 622 ++++-------- crates/buzz-db/src/test_support.rs | 14 +- crates/buzz-db/tests/observability_source.rs | 937 +++++++++++++++--- crates/buzz-relay/src/api/admin/mod.rs | 71 +- .../bridge/thread_window/postgres_tests.rs | 2 +- crates/buzz-relay/src/api/git/transport.rs | 4 +- crates/buzz-relay/src/main.rs | 25 +- crates/buzz-relay/src/startup_steps.rs | 2 +- deploy/charts/buzz/README.md | 6 +- docs/buzz-v1-read-state.md | 5 +- docs/database.md | 63 +- docs/trigger-retirement-deployment.md | 71 ++ migrations/0089_retire_created_at_floor.sql | 30 + .../0090_retire_community_write_fence.sql | 44 + ...91_drop_nip_rs_mesh_migration_triggers.sql | 31 + .../assert_community_write_allowed.sql | 78 -- .../attach_community_write_fence.sql | 45 - schema/functions/community_write_allowed.sql | 24 - .../community_write_fence_excluded_table.sql | 12 - .../enforce_community_write_fence.sql | 24 - .../events_created_at_floor_guard.sql | 29 - schema/schema.sql | 42 +- schema/triggers/api_tokens.sql | 1 - schema/triggers/archived_identities.sql | 1 - schema/triggers/artifact_heads.sql | 1 - schema/triggers/artifact_revisions.sql | 1 - schema/triggers/audit_log.sql | 1 - schema/triggers/channel_members.sql | 1 - schema/triggers/channels.sql | 1 - schema/triggers/community_bans.sql | 1 - schema/triggers/community_nip_fi_issuers.sql | 1 - schema/triggers/delivery_log.sql | 1 - schema/triggers/event_mentions.sql | 1 - schema/triggers/events.sql | 13 - schema/triggers/git_repo_names.sql | 1 - schema/triggers/join_policy_acceptances.sql | 1 - schema/triggers/moderation_actions.sql | 1 - schema/triggers/moderation_reports.sql | 1 - .../parameterized_event_watermarks.sql | 1 - schema/triggers/personal_read_accounts.sql | 1 - schema/triggers/personal_read_frontiers.sql | 1 - schema/triggers/pubkey_allowlist.sql | 1 - schema/triggers/push_leases.sql | 1 - schema/triggers/push_match_queue.sql | 1 - schema/triggers/push_wake_outbox.sql | 1 - schema/triggers/reactions.sql | 1 - schema/triggers/relay_invites.sql | 1 - schema/triggers/relay_members.sql | 1 - schema/triggers/scheduled_workflow_fires.sql | 1 - schema/triggers/subscriptions.sql | 1 - schema/triggers/thread_metadata.sql | 1 - schema/triggers/users.sql | 1 - schema/triggers/workflow_approvals.sql | 1 - schema/triggers/workflow_runs.sql | 1 - schema/triggers/workflows.sql | 1 - scripts/backfill-d-tag.sql | 17 - scripts/cutover/README.md | 6 +- scripts/reconcile-schema-after-pgschema.sql | 22 - 77 files changed, 2055 insertions(+), 2502 deletions(-) create mode 100644 crates/buzz-db/src/runtime/tests/floor_retirement.rs delete mode 100644 crates/buzz-db/src/runtime/tests/schema_fence_bootstrap_postgres_tests.rs create mode 100644 docs/trigger-retirement-deployment.md create mode 100644 migrations/0089_retire_created_at_floor.sql create mode 100644 migrations/0090_retire_community_write_fence.sql create mode 100644 migrations/0091_drop_nip_rs_mesh_migration_triggers.sql delete mode 100644 schema/functions/assert_community_write_allowed.sql delete mode 100644 schema/functions/attach_community_write_fence.sql delete mode 100644 schema/functions/community_write_allowed.sql delete mode 100644 schema/functions/community_write_fence_excluded_table.sql delete mode 100644 schema/functions/enforce_community_write_fence.sql delete mode 100644 schema/functions/events_created_at_floor_guard.sql delete mode 100644 schema/triggers/api_tokens.sql delete mode 100644 schema/triggers/archived_identities.sql delete mode 100644 schema/triggers/artifact_heads.sql delete mode 100644 schema/triggers/artifact_revisions.sql delete mode 100644 schema/triggers/audit_log.sql delete mode 100644 schema/triggers/channel_members.sql delete mode 100644 schema/triggers/community_bans.sql delete mode 100644 schema/triggers/community_nip_fi_issuers.sql delete mode 100644 schema/triggers/delivery_log.sql delete mode 100644 schema/triggers/event_mentions.sql delete mode 100644 schema/triggers/git_repo_names.sql delete mode 100644 schema/triggers/join_policy_acceptances.sql delete mode 100644 schema/triggers/moderation_actions.sql delete mode 100644 schema/triggers/moderation_reports.sql delete mode 100644 schema/triggers/parameterized_event_watermarks.sql delete mode 100644 schema/triggers/personal_read_accounts.sql delete mode 100644 schema/triggers/personal_read_frontiers.sql delete mode 100644 schema/triggers/pubkey_allowlist.sql delete mode 100644 schema/triggers/push_leases.sql delete mode 100644 schema/triggers/push_match_queue.sql delete mode 100644 schema/triggers/push_wake_outbox.sql delete mode 100644 schema/triggers/reactions.sql delete mode 100644 schema/triggers/relay_invites.sql delete mode 100644 schema/triggers/relay_members.sql delete mode 100644 schema/triggers/scheduled_workflow_fires.sql delete mode 100644 schema/triggers/subscriptions.sql delete mode 100644 schema/triggers/thread_metadata.sql delete mode 100644 schema/triggers/users.sql delete mode 100644 schema/triggers/workflow_approvals.sql delete mode 100644 schema/triggers/workflow_runs.sql delete mode 100644 schema/triggers/workflows.sql delete mode 100644 scripts/backfill-d-tag.sql diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a4b90dec11..6000fd606f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -489,42 +489,36 @@ All database access. Uses `sqlx::query()` (runtime, not compile-time macros) — - Approval tokens: `create_approval` receives the raw token and hashes it internally with SHA-256. - DDL injection protection in partition manager: allowlist of table names + strict suffix/date validators. -### Supported Writer Contract (transition state) +### Supported Writer Contract -The repository is moving toward a **supported-writer contract** where relay-owned -write APIs provide the only supported mutation path for tenant data. The current -shape is an explicit transition, not a flag day: +Relay-owned write APIs provide the supported mutation path for tenant data: -- **Trajectory:** converge from trigger/function/FK-enforced fencing toward - application-owned transaction protocols, while keeping existing DB backstops - in place until coverage and fleet gates are proven. -- **Community fence (transition foundation):** runtime admission APIs now offer - one shared community deletion lock per transaction, while deletion lifecycle - transitions take the matching exclusive lock. A supported serving transaction - never spans communities. Serving leases use the same application admission. - Startup and deletion catalog validation tolerate the universal fence objects - being absent; inventories still record live fences for older executors. - Desired-state bootstraps install only explicitly declared legacy fences. - New tenant-owned tables rely on application admission, without a fence trigger. -- **Replica floor (transition foundation):** runtime now provides a shared - replica-floor lock helper for compliant channel-event writers, and the writer - probe handshake takes the exclusive counterpart before sampling `S`, scanning - activity, and committing the heartbeat token last. `probe_once` remains the - sole token/fence-wall publication path; there is no separately persisted active - floor cutoff. Commit-time trigger+GUC enforcement remains authoritative for all - paths. -- **Dual enforcement (current):** application-owned lock+precheck paths run in - front of the existing trigger/function enforcement; commit-time trigger checks - remain authoritative during this phase. Removing those backstops is a separate - gated migration, after every pod tolerates their absence and no rollback below - that version is expected. +- **Community fence:** supported serving writers admit each tenant transaction + through the runtime API, which takes one shared community deletion lock and + checks active, undeleted state. Deletion lifecycle transitions take the + matching exclusive lock. A serving transaction never spans communities. + The universal per-table write-fence triggers and their functions have been + retired after writer coverage and fleet gates; the community tombstone guard + remains. New tenant-owned tables rely on this admission alone. +- **Replica floor:** supported channel-event insertions check `created_at` + against `clock_timestamp()` on their admitted transaction using the shared + 960-second floor. The ordered heartbeat handshake and activity scan retain + the same fence-wall calculation. Migration 0089 retires only the deferred + floor trigger/function; writer connections no longer arm its GUC and probe + startup no longer requires those objects. +- **Floor retirement deploy gate:** phase 1 must be deployed to every writer + pod/job, with no rollback expected, before applying the destructive contract. + Drain old connections/in-flight transactions, stop out-of-band writers, and + hold the replica breaker closed through the drop until replay catches up. + Already-running old pods do not reverify the trigger on each heartbeat. - **Role separation:** relay/runtime code owns admission and lock protocols; operator maintenance/backfill workflows must either use those protocols or run under explicit reviewed procedures that keep routing fences closed. - **Unsupported shape:** direct owner SQL that bypasses supported transaction and lock protocols is not a supported write path. -- **Fleet gates and reconciliation:** startup/fence probes verify guard catalog + - behavior, pgschema bootstraps run reconciliation, and lock/pool metrics remain +- **Fleet gates and reconciliation:** retained guards keep their catalog and + behavior checks; heartbeat/epoch and activity checks still fail closed. + pgschema bootstraps run reconciliation, and lock/pool metrics remain the operational evidence path for rollout safety. The database end state (a declarative schema source, applied out of band at diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 49809b98ae..f52ad2a4a4 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -70,15 +70,15 @@ pub const DB_POOL_ACQUIRE_RAW_SERIES_PER_POD: usize = runtime::observability::POOL_ACQUIRE_RAW_SERIES_PER_POD; /// Valid database connection role/step pairs with a start counter. -pub const DB_CONNECTION_STARTED_STEPS: [(DbPoolRole, DbConnectionStep); 4] = +pub const DB_CONNECTION_STARTED_STEPS: [(DbPoolRole, DbConnectionStep); 3] = runtime::CONNECTION_STARTED_STEPS; /// Valid database connection role/step pairs with a duration histogram. -pub const DB_CONNECTION_DURATION_STEPS: [(DbPoolRole, DbConnectionStep); 4] = +pub const DB_CONNECTION_DURATION_STEPS: [(DbPoolRole, DbConnectionStep); 3] = runtime::CONNECTION_DURATION_STEPS; /// Valid database connection role/step/outcome terminal combinations. -pub const DB_CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutcome); 15] = +pub const DB_CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutcome); 12] = runtime::CONNECTION_TERMINALS; /// Raw Prometheus series ceiling per pod for connection-step telemetry. diff --git a/crates/buzz-db/src/runtime/admitted_tx.rs b/crates/buzz-db/src/runtime/admitted_tx.rs index d70512c233..c6d7f7bdaa 100644 --- a/crates/buzz-db/src/runtime/admitted_tx.rs +++ b/crates/buzz-db/src/runtime/admitted_tx.rs @@ -24,10 +24,10 @@ use crate::Result; /// statements on it, and [`AdmittedTx::commit`] and [`AdmittedTx::rollback`] /// are the only ways it can end the transaction. Inside the crate, the /// `conn()` accessor hands statements the connection; the type can't stop -/// crate code from issuing a raw `COMMIT` through it, so the database -/// community write fences remain the backstop while deployed. Internal writers -/// must preserve this boundary and use `commit()` for staged follow-up work. -/// Dropping the value without committing rolls back, as with [`sqlx::Transaction`]. +/// crate code from issuing a raw `COMMIT` through it. Internal writers must +/// preserve this transaction boundary and use `commit()` for staged follow-up +/// work. Dropping the value without committing rolls back, as with +/// [`sqlx::Transaction`]. /// /// These are live regressions for the guarantee. Event-write helpers accept an /// admitted transaction: diff --git a/crates/buzz-db/src/runtime/connection_observability.rs b/crates/buzz-db/src/runtime/connection_observability.rs index a1ab04022f..710d3e04a5 100644 --- a/crates/buzz-db/src/runtime/connection_observability.rs +++ b/crates/buzz-db/src/runtime/connection_observability.rs @@ -17,8 +17,6 @@ pub enum DbConnectionStep { WriterPool, /// A physical connection has completed DNS/network/TLS/authentication. PhysicalConnect, - /// Install the created-at replica-fence floor. - CreatedAtFloor, /// Install lock, idle-transaction, and statement timeouts. SessionTimeouts, /// Verify READ COMMITTED transaction isolation. @@ -29,10 +27,9 @@ pub enum DbConnectionStep { impl DbConnectionStep { /// Complete metric-label vocabulary. - pub const ALL: [Self; 6] = [ + pub const ALL: [Self; 5] = [ Self::WriterPool, Self::PhysicalConnect, - Self::CreatedAtFloor, Self::SessionTimeouts, Self::Isolation, Self::Ready, @@ -43,7 +40,6 @@ impl DbConnectionStep { match self { Self::WriterPool => "writer_pool", Self::PhysicalConnect => "physical_connect", - Self::CreatedAtFloor => "created_at_floor", Self::SessionTimeouts => "session_timeouts", Self::Isolation => "isolation", Self::Ready => "ready", @@ -77,18 +73,17 @@ impl DbConnectionOutcome { } /// Valid role/step pairs with an explicit start counter. -pub const CONNECTION_STARTED_STEPS: [(DbPoolRole, DbConnectionStep); 4] = [ +pub const CONNECTION_STARTED_STEPS: [(DbPoolRole, DbConnectionStep); 3] = [ (DbPoolRole::Writer, DbConnectionStep::WriterPool), - (DbPoolRole::Writer, DbConnectionStep::CreatedAtFloor), (DbPoolRole::Writer, DbConnectionStep::SessionTimeouts), (DbPoolRole::Writer, DbConnectionStep::Isolation), ]; /// Valid role/step pairs with a duration histogram. -pub const CONNECTION_DURATION_STEPS: [(DbPoolRole, DbConnectionStep); 4] = CONNECTION_STARTED_STEPS; +pub const CONNECTION_DURATION_STEPS: [(DbPoolRole, DbConnectionStep); 3] = CONNECTION_STARTED_STEPS; /// Valid role/step/outcome terminal combinations. -pub const CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutcome); 15] = [ +pub const CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutcome); 12] = [ ( DbPoolRole::Writer, DbConnectionStep::WriterPool, @@ -114,21 +109,6 @@ pub const CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutc DbConnectionStep::PhysicalConnect, DbConnectionOutcome::Succeeded, ), - ( - DbPoolRole::Writer, - DbConnectionStep::CreatedAtFloor, - DbConnectionOutcome::Succeeded, - ), - ( - DbPoolRole::Writer, - DbConnectionStep::CreatedAtFloor, - DbConnectionOutcome::Failed, - ), - ( - DbPoolRole::Writer, - DbConnectionStep::CreatedAtFloor, - DbConnectionOutcome::Cancelled, - ), ( DbPoolRole::Writer, DbConnectionStep::SessionTimeouts, @@ -166,8 +146,8 @@ pub const CONNECTION_TERMINALS: [(DbPoolRole, DbConnectionStep, DbConnectionOutc ), ]; -/// Four start counters + four 13-series histograms + fifteen terminal counters. -pub const CONNECTION_RAW_SERIES_PER_POD: usize = 4 + (4 * 13) + 15; +/// Three start counters + three 13-series histograms + twelve terminal counters. +pub const CONNECTION_RAW_SERIES_PER_POD: usize = 3 + (3 * 13) + 12; pub(crate) struct DbConnectionStepAttempt { pool_role: DbPoolRole, @@ -282,13 +262,12 @@ mod tests { [ "writer_pool", "physical_connect", - "created_at_floor", "session_timeouts", "isolation", "ready", ] ); - assert_eq!(CONNECTION_RAW_SERIES_PER_POD, 71); + assert_eq!(CONNECTION_RAW_SERIES_PER_POD, 54); } #[test] @@ -297,7 +276,7 @@ mod tests { let snapshotter = recorder.snapshotter(); let _guard = metrics::set_default_local_recorder(&recorder); let attempt = - DbConnectionStepAttempt::start(DbPoolRole::Writer, DbConnectionStep::CreatedAtFloor); + DbConnectionStepAttempt::start(DbPoolRole::Writer, DbConnectionStep::SessionTimeouts); drop(attempt); let metrics = snapshotter.snapshot().into_vec(); @@ -309,7 +288,7 @@ mod tests { .map(|label| (label.key(), label.value())) .collect::>(); assert_eq!(labels.get("pool_role"), Some(&"writer")); - assert_eq!(labels.get("step"), Some(&"created_at_floor")); + assert_eq!(labels.get("step"), Some(&"session_timeouts")); assert!(!labels.contains_key("reason")); assert!(!labels.contains_key("connection_ordinal")); match value { diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 7a9a2b7bf8..735e92e1fc 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -14,10 +14,6 @@ use crate::Result; static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("../../migrations"); -#[cfg(test)] -#[path = "tests/schema_fence_bootstrap_postgres_tests.rs"] -mod schema_fence_bootstrap_postgres_tests; - /// Run all pending Buzz database migrations. /// /// The entire run holds the exclusive [`SCHEMA_DESTRUCTION_LOCK_KEY`] session @@ -58,14 +54,6 @@ async fn run_migrations_locked(conn: &mut PgConnection) -> Result<()> { build_indexes_before_migration(conn, *version, doc, indexes).await?; } MIGRATOR.run(&mut *conn).await?; - // The replica-fence proof (see `replica_fence`) requires the commit-time - // `created_at` floor trigger from migration 0021 — correctly shaped — on - // the `events` parent and every partition. `CREATE TABLE .. PARTITION OF` - // clones parent triggers, but a partition attached with `ATTACH - // PARTITION` or created by an older code path would silently escape the - // guard, so migration fails closed if any is missing. (The fence probe - // re-runs this same check at startup on non-migrating relays.) - crate::replica_fence::verify_floor_guard_catalog(&mut *conn).await?; Ok(()) } @@ -902,7 +890,12 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 88); + assert_eq!(migrations.len(), 91); + assert_eq!(migrations[89].version, 90); + assert!(migrations[89] + .sql + .as_str() + .contains("DROP FUNCTION enforce_community_write_fence();")); assert!(migrations[83] .sql .as_str() @@ -923,6 +916,11 @@ mod postgres_tests { .sql .as_str() .contains("VALIDATE CONSTRAINT workflow_runs_cause_pubkey_check")); + // 0089 retires the deferred created_at floor trigger and its function. + assert_eq!(migrations[88].version, 89); + let retire_floor = strip_sql_comments(migrations[88].sql.as_str()); + assert!(retire_floor.contains("DROP TRIGGER IF EXISTS events_created_at_floor ON events;")); + assert!(retire_floor.contains("DROP FUNCTION IF EXISTS events_created_at_floor_guard();")); for (index, migration) in migrations.iter().enumerate() { assert_eq!(migration.version, (index + 1) as i64); } @@ -1002,6 +1000,34 @@ mod postgres_tests { .sql .as_str() .contains("CREATE FUNCTION profile_name_fields")); + // The app owns the NIP-RS watermark, retention-free purge and + // mention liveness, so 0091 drops the migration-only triggers that + // 0009, 0010, 0011 and 0019 installed. Those files stay frozen. + assert_eq!(migrations[90].version, 91); + let retire_nip_rs = strip_sql_comments(migrations[90].sql.as_str()); + for statement in [ + "SET LOCAL lock_timeout = '5s';", + "DROP TRIGGER trg_events_nip_rs_watermark ON events;", + "DROP TRIGGER trg_events_guard_nip_rs_hard_delete ON events;", + "DROP TRIGGER trg_events_purge_soft_deleted_nip_rs ON events;", + "DROP TRIGGER trg_events_purge_soft_deleted_buzz_mesh_status ON events;", + "DROP TRIGGER trg_event_mentions_require_live_event ON event_mentions;", + "DROP FUNCTION guard_nip_rs_watermark();", + "DROP FUNCTION guard_nip_rs_hard_delete();", + "DROP FUNCTION purge_soft_deleted_nip_rs();", + "DROP FUNCTION purge_soft_deleted_buzz_mesh_status();", + "DROP FUNCTION guard_event_mention_live();", + ] { + assert!( + retire_nip_rs.contains(statement), + "0091 must run {statement}" + ); + } + assert!( + retire_nip_rs.find("SET LOCAL lock_timeout").unwrap() + < retire_nip_rs.find("DROP TRIGGER").unwrap(), + "0091 must bound its ACCESS EXCLUSIVE lock on events before the first DROP" + ); assert_eq!(migrations[55].version, 56); assert!(migrations[55] .sql @@ -1338,12 +1364,6 @@ mod postgres_tests { .as_str() .contains("CREATE TABLE join_policy_acceptances")); - // Replica-fence commit-time floor guard on channel-bearing events. - assert_eq!(migrations[20].version, 21); - assert!(migrations[20] - .sql - .as_str() - .contains("events_created_at_floor_guard")); assert!(!migrations[0] .sql .as_str() @@ -1459,6 +1479,41 @@ mod postgres_tests { assert!(deletion.contains("CREATE FUNCTION attach_community_write_fence")); assert!(deletion.contains("community_write_fence_excluded_table")); assert!(deletion.contains("CREATE FUNCTION enforce_community_tombstone")); + let retirement = migrations + .iter() + .find(|migration| migration.version == 90) + .expect("retirement migration 0090") + .sql + .as_str(); + assert!(retirement.starts_with("SET LOCAL lock_timeout = '5s';")); + // Tables added after docs/database.md Rule 1 never had a fence. + let never_fenced = [ + "nip_fi_profile_heads", + "media_uploaders", + "media_publications", + ]; + for table in crate::deletion::EXPECTED_SCOPED_TABLES + .iter() + .filter(|table| !never_fenced.contains(table)) + { + assert!( + retirement.contains(&format!( + "DROP TRIGGER IF EXISTS community_write_fence_{table} ON {table};" + )), + "0090 must retire the universal fence on {table}" + ); + } + for signature in [ + "attach_community_write_fence(REGCLASS)", + "enforce_community_write_fence()", + "assert_community_write_allowed(UUID)", + "community_write_allowed(UUID)", + "community_write_fence_excluded_table(NAME)", + ] { + assert!(retirement.contains(&format!("DROP FUNCTION {signature};"))); + } + assert!(!retirement.contains("DROP FUNCTION community_deletion_lock_key")); + assert!(!retirement.contains("DROP FUNCTION enforce_community_tombstone")); assert!(deletion.contains("community tombstones are permanent")); assert!(deletion.contains("SET LOCAL lock_timeout = '5s'")); assert!(deletion.contains("'active', 'quiescing', 'fenced', 'tombstone'")); @@ -1701,13 +1756,6 @@ mod postgres_tests { "schema.sql must declare {index_shape}" ); } - // schema.sql keeps the restored (pre-0041) deletion exclusions and also - // leaves the deployment-global listener outbox outside tenant fencing. - assert!( - desired_schema - .contains("'rate_limit_violations', 'operator_listener_outbox'\n ]::TEXT[])"), - "schema.sql must exclude the deployment-global listener outbox from tenant fencing" - ); assert_eq!(migrations[51].version, 52); assert!(migrations[51] .sql @@ -2330,8 +2378,7 @@ mod postgres_tests { /// Compares parsed statements, not substrings: every deletion control- /// plane table, function, trigger, and index 0028 creates must exist in /// schema.sql with an identical normalized definition; every operator- - /// global registry row 0028 inserts must be inserted by schema.sql; the - /// write-fence attachment target sets must be equal; and every column + /// global registry row 0028 inserts must be inserted by schema.sql; every column /// 0028 adds to `communities` must exist in the desired-state /// `communities` table. A desired-state bootstrap that passes this test /// cannot silently omit part of the deletion surface the way the @@ -2350,7 +2397,6 @@ mod postgres_tests { triggers: BTreeMap, indexes: BTreeSet, registry_rows: BTreeSet<(String, String)>, - fence_attachments: BTreeSet, communities_added_columns: BTreeSet, } @@ -2419,14 +2465,6 @@ mod postgres_tests { surface.communities_added_columns.insert(column); } } - if let Some(position) = normalized.find("attach_community_write_fence('") { - let target = normalized[position + "attach_community_write_fence('".len()..] - .split('\'') - .next() - .expect("fence attachment target") - .to_owned(); - surface.fence_attachments.insert(target); - } } surface } @@ -2455,7 +2493,6 @@ mod postgres_tests { "0029 deletion control plane must define exactly the known tables: {:?}", migration.tables.keys().collect::>() ); - assert!(!migration.fence_attachments.is_empty()); assert!(!migration.registry_rows.is_empty()); for (table, definition) in &migration.tables { @@ -2508,13 +2545,23 @@ mod postgres_tests { ); } for (function, definition) in &migration.functions { + if [ + "community_write_fence_excluded_table", + "community_write_allowed", + "assert_community_write_allowed", + "enforce_community_write_fence", + "attach_community_write_fence", + ] + .contains(&function.as_str()) + { + assert!(!schema.functions.contains_key(function)); + continue; + } let in_schema = schema .functions .get(function) .unwrap_or_else(|| panic!("schema.sql is missing deletion function {function}")); - if function != "community_write_fence_excluded_table" - && function != "prevent_community_deletion_request_retargeting" - { + if function != "prevent_community_deletion_request_retargeting" { assert_eq!( in_schema, definition, "schema.sql definition of {function}() drifted from migration 0029" @@ -2570,9 +2617,6 @@ mod postgres_tests { "schema.sql is missing operator-global registry row {row:?}" ); } - let mut expected_fences = migration.fence_attachments.clone(); - expected_fences.remove("product_feedback"); - expected_fences.remove("rate_limit_violations"); let personal = surface( MIGRATOR .iter() @@ -2626,21 +2670,6 @@ mod postgres_tests { "personal read table {table} differs" ); } - expected_fences.extend(personal.fence_attachments); - expected_fences.extend(["artifact_heads", "artifact_revisions"].map(str::to_owned)); - // 0066 fences the NIP-FI issuer bindings table. - assert!(MIGRATOR - .iter() - .find(|m| m.version == 66) - .expect("NIP-FI binding migration") - .sql - .as_str() - .contains("attach_community_write_fence('community_nip_fi_issuers')")); - expected_fences.insert("community_nip_fi_issuers".to_owned()); - assert_eq!( - expected_fences, schema.fence_attachments, - "write-fence attachment targets differ after recovery policy" - ); // 0029's ALTER TABLE additions are expressed inline by the // desired-state `communities` definition; require the columns to @@ -2935,6 +2964,10 @@ mod postgres_tests { /// drift this test guards against. `indoption` (not just `indexdef` text) is /// asserted so a resurrected `NULLS FIRST` in a migration that `pgschema` /// cannot represent is caught. + /// + /// It also asserts the fully migrated `events` and + /// `event_mentions` row triggers match `schema/` exactly, so no + /// migration-only trigger survives on the event write path. #[tokio::test] #[ignore = "requires Postgres"] async fn admin_schema_parity_between_desired_state_and_migrations() { @@ -3014,6 +3047,25 @@ mod postgres_tests { .expect("read events key definitions") } + // Row triggers on a parent table (partition clones follow the parent): + // name, function, enable mode and the tgtype bitmask. + async fn trigger_shapes(pool: &PgPool, table: &str) -> Vec<(String, String, String, i16)> { + sqlx::query_as( + "SELECT trigger.tgname::text, procedure.proname::text, \ + trigger.tgenabled::text, trigger.tgtype \ + FROM pg_trigger trigger \ + JOIN pg_class c ON c.oid = trigger.tgrelid \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + JOIN pg_proc procedure ON procedure.oid = trigger.tgfoid \ + WHERE n.nspname = 'public' AND c.relname = $1 AND NOT trigger.tgisinternal \ + ORDER BY trigger.tgname", + ) + .bind(table) + .fetch_all(pool) + .await + .expect("read trigger shapes") + } + let base_url = std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) .unwrap_or_else(|_| TEST_DB_URL.to_owned()); @@ -3137,6 +3189,17 @@ mod postgres_tests { "constraint parity mismatch for {table}" ); } + + // Every migration-only trigger on the event tables is retired, so a + // fully migrated database carries exactly the desired-state triggers. + for table in ["events", "event_mentions"] { + assert_eq!( + trigger_shapes(&desired, table).await, + trigger_shapes(&migrated, table).await, + "trigger parity mismatch for {table}: a migration installs a trigger that \ + schema/ does not declare (or the reverse)" + ); + } } /// Re-applying `schema/schema.sql` to a database bootstrapped the way every @@ -3844,164 +3907,70 @@ mod postgres_tests { search_expression.contains("ELSE NULL::tsvector"), "fresh installs must default non-allowlisted kinds to NULL: {search_expression}" ); + } - let active_a = uuid::Uuid::new_v4(); - let active_b = uuid::Uuid::new_v4(); - let to_fence = uuid::Uuid::new_v4(); - for (community, label) in [ - (active_a, "active-a"), - (active_b, "active-b"), - (to_fence, "to-fence"), - ] { - sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") - .bind(community) - .bind(format!("late-fence-{label}-{}.example", community.simple())) - .execute(&pool) - .await - .expect("insert late-table test community"); - } - sqlx::query( - "CREATE TABLE late_created_scoped (\ - community_id UUID NOT NULL, id BIGINT PRIMARY KEY, value TEXT NOT NULL\ - )", - ) - .execute(&pool) - .await - .expect("create late scoped table"); - sqlx::query("SELECT attach_community_write_fence('late_created_scoped'::regclass)") - .execute(&pool) + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migrated_catalog_retires_universal_fences_but_keeps_deletion_guards() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + let retirement = MIGRATOR + .iter() + .find(|m| m.description == "retire community write fence") + .expect("fence retirement migration is embedded") + .version; + MIGRATOR + .run_to(retirement - 1, &pool) .await - .expect("attach late create fence"); - sqlx::query("CREATE TABLE late_altered_scoped (id BIGINT PRIMARY KEY)") - .execute(&pool) + .expect("apply pre-retirement migrations"); + let store = crate::deletion::DeletionStore::new(pool.clone()); + store + .validate_serving_catalog() .await - .expect("create table before late alter"); - sqlx::query("ALTER TABLE late_altered_scoped ADD COLUMN community_id UUID NOT NULL") - .execute(&pool) + .expect("new runtime must accept pre-retirement catalog"); + store + .validate_catalog() .await - .expect("add late community id"); - sqlx::query("SELECT attach_community_write_fence('late_altered_scoped'::regclass)") - .execute(&pool) - .await - .expect("attach late alter fence"); - let attached: Vec = sqlx::query_scalar( - "SELECT c.relname FROM pg_trigger trigger \ - JOIN pg_class c ON c.oid = trigger.tgrelid \ - JOIN pg_proc procedure ON procedure.oid = trigger.tgfoid \ - WHERE c.relname IN ('late_created_scoped', 'late_altered_scoped') \ - AND procedure.proname = 'enforce_community_write_fence' \ - AND NOT trigger.tgisinternal ORDER BY c.relname", - ) - .fetch_all(&pool) - .await - .expect("read late trigger catalog"); - assert_eq!(attached, vec!["late_altered_scoped", "late_created_scoped"]); - let malformed_fence_triggers: i64 = sqlx::query_scalar( - "SELECT count(*)::BIGINT FROM pg_trigger trigger \ - JOIN pg_class c ON c.oid = trigger.tgrelid \ - JOIN pg_proc procedure ON procedure.oid = trigger.tgfoid \ - WHERE c.relname IN ('late_created_scoped', 'late_altered_scoped') \ - AND procedure.proname = 'enforce_community_write_fence' \ - AND NOT trigger.tgisinternal \ - AND (trigger.tgenabled <> 'O' OR (trigger.tgtype & 31) <> 31)", + .expect("deletion must accept pre-retirement catalog"); + run_migrations(&pool).await.expect("apply all migrations"); + let fence_triggers: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname LIKE 'community_write_fence_%'", ) .fetch_one(&pool) .await - .expect("validate late trigger mode and operations"); - assert_eq!(malformed_fence_triggers, 0); - - sqlx::query( - "INSERT INTO late_created_scoped (community_id, id, value) \ - VALUES ($1, 1, 'same'), ($2, 2, 'source-fenced'), \ - ($1, 3, 'destination-fenced'), ($1, 4, 'opposite-a'), \ - ($3, 5, 'opposite-b')", - ) - .bind(active_a) - .bind(to_fence) - .bind(active_b) - .execute(&pool) - .await - .expect("seed late table while communities active"); - sqlx::query("UPDATE late_created_scoped SET value = 'same-ok' WHERE id = 1") - .execute(&pool) - .await - .expect("same-tenant active update"); - sqlx::query("UPDATE late_created_scoped SET community_id = $1 WHERE id = 1") - .bind(active_b) - .execute(&pool) - .await - .expect("active-to-active update"); - - let mut fence_connection = pool.acquire().await.expect("fence connection"); - sqlx::query("BEGIN") - .execute(&mut *fence_connection) - .await - .expect("begin direct fence"); - sqlx::query( - "SELECT set_config('buzz.deletion_executor_community', $1, true), \ - set_config('buzz.deletion_fence_generation', '1', true)", - ) - .bind(to_fence.to_string()) - .execute(&mut *fence_connection) - .await - .expect("authorize direct fence"); - sqlx::query( - "UPDATE communities SET deletion_state = 'fenced', \ - deletion_fence_generation = 1, archived_at = now() WHERE id = $1", - ) - .bind(to_fence) - .execute(&mut *fence_connection) - .await - .expect("fence test destination"); - sqlx::query("COMMIT") - .execute(&mut *fence_connection) - .await - .expect("commit direct fence"); - - let active_to_fenced = - sqlx::query("UPDATE late_created_scoped SET community_id = $1 WHERE id = 3") - .bind(to_fence) - .execute(&pool) + .expect("count retired triggers"); + assert_eq!(fence_triggers, 0); + let fence_functions: i64 = + sqlx::query_scalar("SELECT count(*) FROM pg_proc WHERE proname = ANY($1)") + .bind( + &[ + "attach_community_write_fence", + "enforce_community_write_fence", + "assert_community_write_allowed", + "community_write_allowed", + "community_write_fence_excluded_table", + ][..], + ) + .fetch_one(&pool) .await - .expect_err("active to fenced destination must fail"); - assert!(active_to_fenced - .to_string() - .contains("community write fenced")); - let fenced_to_active = - sqlx::query("UPDATE late_created_scoped SET community_id = $1 WHERE id = 2") - .bind(active_a) - .execute(&pool) - .await - .expect_err("fenced source to active destination must fail"); - assert!(fenced_to_active - .to_string() - .contains("community write fenced")); - let row_locations: Vec<(i64, uuid::Uuid)> = sqlx::query_as( - "SELECT id, community_id FROM late_created_scoped WHERE id IN (2, 3) ORDER BY id", + .expect("count retired functions"); + assert_eq!(fence_functions, 0); + let retained: (bool, bool) = sqlx::query_as( + "SELECT to_regprocedure('community_deletion_lock_key(uuid)') IS NOT NULL, \ + EXISTS(SELECT 1 FROM pg_trigger WHERE tgname = 'communities_deletion_tombstone')", ) - .fetch_all(&pool) + .fetch_one(&pool) .await - .expect("failed moves preserve row location"); - assert_eq!(row_locations, vec![(2, to_fence), (3, active_a)]); - - let move_a = sqlx::query("UPDATE late_created_scoped SET community_id = $1 WHERE id = 4") - .bind(active_b) - .execute(&pool); - let move_b = sqlx::query("UPDATE late_created_scoped SET community_id = $1 WHERE id = 5") - .bind(active_a) - .execute(&pool); - tokio::time::timeout(std::time::Duration::from_secs(2), async { - let (a, b) = tokio::join!(move_a, move_b); - a.expect("opposite active move A"); - b.expect("opposite active move B"); - }) - .await - .expect("opposite cross-tenant updates must not deadlock"); - - sqlx::query("DROP TABLE late_created_scoped, late_altered_scoped") - .execute(&pool) + .expect("read retained guards"); + assert_eq!(retained, (true, true)); + store + .validate_serving_catalog() .await - .expect("drop late-table fixtures"); + .expect("new code must boot against migrated catalog"); + store + .validate_catalog() + .await + .expect("deletion catalog must accept post-retirement catalog"); } /// Verify migration 0044 applies cleanly against a DB that has rows in @@ -4224,10 +4193,15 @@ mod postgres_tests { .await .unwrap(); if prebuilt { - run_migrations(&pool) + // Stop at 0088: later trigger retirements take ACCESS + // EXCLUSIVE on events, which this held writer lock blocks. + run_migrations_through(&pool, 88) .await .expect("verified prebuild does not request an index-build lock"); writer.rollback().await.unwrap(); + run_migrations(&pool) + .await + .expect("later migrations apply once the writer is gone"); } else { let error = run_migrations(&pool).await.unwrap_err(); assert!( diff --git a/crates/buzz-db/src/runtime/mod.rs b/crates/buzz-db/src/runtime/mod.rs index 5158954db5..ebe7fb4a3f 100644 --- a/crates/buzz-db/src/runtime/mod.rs +++ b/crates/buzz-db/src/runtime/mod.rs @@ -423,8 +423,8 @@ pub(crate) mod route_proof { use uuid::Uuid; /// Proof that a query/page can only return rows with - /// `channel_id IS NOT NULL` — the domain of the commit-time floor guard - /// (migration 0021). `channel_ids` (retains channel-NULL rows) and + /// `channel_id IS NOT NULL` — the domain of the application floor check + /// (see [`replica_fence`]). `channel_ids` (retains channel-NULL rows) and /// `global_only = false` are explicitly NOT proofs. /// /// Each constructor keys off *how* its path proves channel-bearing-ness: @@ -482,18 +482,18 @@ pub(crate) enum RoutePredicate { /// read budget `B` (default off). Bounds TIME — the page misses at most /// the freshest `B` of writes. Sound for ANY query shape, including /// global (channel-NULL) rows: it relies only on heartbeat commit order, - /// not the floor guard. + /// not the floor check. Bounded, /// Completeness: the proved wall must cover the page's upper bound. /// Bounds CONTENT — every row at/below `upper` is present, meaningful /// even when the cursor is hours old, where `B`-freshness says nothing. - /// Sound ONLY on the floor guard's domain (channel-bearing rows), hence + /// Sound ONLY on the application floor's domain (channel-bearing rows), hence /// the proof token. `upper` is non-optional: the no-upper-bound /// post-verifying case is [`RoutePredicate::CoveredPostVerified`]. /// /// Bounds INSERT-completeness only — "no missing rows", not "no extra /// rows". Soft deletes are `UPDATE .. SET deleted_at` commits outside - /// the floor guard and never touch `created_at`, so a covered page can + /// the floor check and never touch `created_at`, so a covered page can /// briefly serve a row the writer already excludes; deletion visibility /// is bounded by replication lag under `FENCE_STALENESS` (30s), not by /// `upper` or `B`. Do not extend the covered arm to a surface that @@ -816,10 +816,6 @@ impl Db { /// When `config.read_database_url` is set, a second pool with the same /// sizing is connected to it for lag-tolerant reads (see [`Db::read`]). /// - /// The writer pool arms the commit-time `created_at` floor guard - /// (migration 0021) on every connection by setting the - /// `buzz.created_at_floor` GUC — this is what makes the replica fence - /// proof hold for every insert path that goes through this pool. pub async fn new(config: &DbConfig) -> Result { let pool = Self::connect_writer_pool(config).await?; let read_max_connections = config @@ -863,16 +859,15 @@ impl Db { /// Connect the writer pool with all session-level safety premises. /// - /// SQLx stores one `after_connect` hook, so the floor guard and transaction - /// isolation assertion must remain in this single closure. Registering a - /// second hook replaces the first and silently disarms the floor trigger. + /// SQLx stores one `after_connect` hook, so session timeouts and the + /// transaction isolation assertion must remain in this single closure. /// Additional writer pools, including the relay audit pool, must use this - /// constructor so they inherit the timeout, floor-guard, and isolation + /// constructor so they inherit the timeout and isolation /// policy installed by [`Db::new`]. /// /// Two single-connection side pools deliberately do not, so serving-pool /// saturation cannot delay their work. Neither inserts into `events`, so - /// neither needs the `buzz.created_at_floor` guard, and each installs + /// neither needs the app-side floor check, and each installs /// its own shorter timeouts so it fails fast instead of queueing: /// - [`replica_fence::connect_probe_pool`]: the fence probe takes the /// floor lock itself (exclusive) and writes only `replica_heartbeat`. @@ -913,22 +908,6 @@ impl Db { // point at which DNS/network/TLS/authentication succeeded. record_milestone(DbPoolRole::Writer, DbConnectionStep::PhysicalConnect); - // `SET` cannot take bind parameters; `set_config` can. - let floor = DbConnectionStepAttempt::start( - DbPoolRole::Writer, - DbConnectionStep::CreatedAtFloor, - ); - if let Err(error) = - sqlx::query("SELECT set_config('buzz.created_at_floor', $1, false)") - .bind(replica_fence::CREATED_AT_FLOOR_SECS.to_string()) - .execute(&mut *conn) - .await - { - floor.fail(); - return Err(error); - } - floor.succeed(); - // `lock_timeout` fails the waiting statement; it does not // cancel the holder. `idle_in_transaction_session_timeout` // reaps only holders idling inside an open transaction, @@ -1072,9 +1051,8 @@ impl Db { /// and every released connection still passes the bounded release check /// in [`Db::read_pool_options`]. /// - /// No floor guard or writer-isolation assertion: replica sessions are - /// read-only, so the commit-time trigger from migration 0021 never fires - /// here and the write fence that depends on READ COMMITTED is never reached. + /// No writer-isolation assertion: replica sessions are read-only, so the + /// write fence that depends on READ COMMITTED is never reached here. /// /// Every replica session's `statement_timeout` is lowered to the /// event-read deadline ([`crate::event::READ_STATEMENT_TIMEOUT`]) unless @@ -1462,27 +1440,14 @@ impl Db { &self.fence } - /// Verify the floor guard end-to-end, then spawn the background fence - /// probe. Returns `Ok(false)` when no replica is configured. - /// - /// Ordering matters (Perci, PR #2084 review): this must run **after** - /// the migration decision. On a relay with `BUZZ_AUTO_MIGRATE` off, the - /// writer pool arms the GUC regardless, but if migration 0021 has not - /// been applied there is no trigger enforcing it — and a heartbeat probe - /// would open the fence over an unenforced floor. So the probe is gated - /// on an unconditional two-part verification against the live schema: - /// catalog shape ([`replica_fence::verify_floor_guard_catalog`]) and - /// observed semantics through this exact pool - /// ([`replica_fence::verify_floor_guard_behavior`]). - /// - /// On any verification failure the probe is never spawned and the fence - /// stays closed: every cursor page routes to the writer. The relay keeps - /// serving — degraded capacity, never holes. - pub async fn spawn_fence_probe(&self) -> Result { + /// Spawn the background fence probe after the migration decision. + /// Returns `false` when no replica is configured. Probe failures keep + /// the fence closed and cursor reads on the writer. Application floor + /// coverage is enforced by the supported-writer contract and fleet gate. + pub fn spawn_fence_probe(&self) -> bool { if self.read_pool.is_none() { - return Ok(false); + return false; } - self.verify_replica_fence_at_boot().await?; // The probe gets its own connection so serving-pool saturation // cannot delay the beat (see `replica_fence::connect_probe_pool`). tokio::spawn(replica_fence::run_probe( @@ -1490,18 +1455,7 @@ impl Db { std::sync::Arc::clone(&self.fence), self.fence_probe_interval, )); - Ok(true) - } - - /// Verify replica-fence catalog shape and behavior through attributed - /// writer/bootstrap acquisitions without starting the recurring probe. - pub(crate) async fn verify_replica_fence_at_boot(&self) -> Result<()> { - let mut connection = - observability::acquire_writer(&self.pool, observability::WriterOperation::Bootstrap) - .await?; - replica_fence::verify_floor_guard_catalog(&mut *connection).await?; - drop(connection); - replica_fence::verify_floor_guard_behavior(&self.pool).await + true } /// The pool for lag-tolerant reads: the read replica when configured, @@ -2259,3 +2213,7 @@ fn media_authorization_slots(pool: &PgPool) -> std::sync::Arc( - executor: impl sqlx::PgExecutor<'e>, -) -> crate::Result<()> { - // tgtype bits: 1 = ROW, 2 = BEFORE, 4 = INSERT, 16 = UPDATE, 64 = INSTEAD. - // Required: ROW + INSERT + UPDATE set, BEFORE + INSTEAD clear. - let missing: Vec = sqlx::query_scalar( - r#" - SELECT c.relname::text - FROM ( - SELECT 'events'::regclass AS oid - UNION ALL - SELECT inhrelid FROM pg_inherits WHERE inhparent = 'events'::regclass - ) rels - JOIN pg_class c ON c.oid = rels.oid - WHERE NOT EXISTS ( - SELECT 1 FROM pg_trigger t - WHERE t.tgrelid = rels.oid - AND t.tgname = 'events_created_at_floor' - AND t.tgfoid = 'events_created_at_floor_guard'::regproc - AND t.tgdeferrable - AND t.tginitdeferred - AND t.tgtype & 1 = 1 -- row-level - AND t.tgtype & 2 = 0 -- AFTER, not BEFORE - AND t.tgtype & 64 = 0 -- not INSTEAD OF - AND t.tgtype & 4 = 4 -- fires on INSERT - AND t.tgtype & 16 = 16 -- fires on UPDATE - ) - "#, - ) - .fetch_all(executor) - .await?; - if !missing.is_empty() { - return Err(crate::error::DbError::InvalidData(format!( - "created_at floor guard trigger missing or mis-shaped on: {} \ - (replica fence must stay closed)", - missing.join(", ") - ))); - } - Ok(()) -} - -/// Behavioral verification of the floor guard, end-to-end through the armed -/// pool. A catalog check cannot detect a no-op function body or an unarmed -/// pool; this proves the semantics the fence proof cites, inside one -/// rolled-back transaction: -/// -/// 1. the pool's session GUC equals [`CREATED_AT_FLOOR_SECS`] (arming); -/// 2. an old channel-bearing INSERT raises `check_violation` (23514); -/// 3. a fresh channel-bearing INSERT commits; -/// 4. rewriting a fresh row's `created_at` below the floor raises; -/// 5. an old channel-NULL INSERT is exempt, but flipping its `channel_id` -/// on raises (the `UPDATE OF` arm). -/// -/// `SET CONSTRAINTS ALL IMMEDIATE` makes the deferred trigger fire per -/// statement so each adversary is observable under a savepoint; deferral to -/// COMMIT is separately pinned by the held-transaction fixture. -#[datastore_span(name = "replica_fence_verify_behavior", system = "postgresql")] -pub async fn verify_floor_guard_behavior(pool: &PgPool) -> crate::Result<()> { - use crate::error::DbError; - - let expect_violation = |res: Result, - what: &str| - -> crate::Result<()> { - match res { - Err(sqlx::Error::Database(e)) if e.code().as_deref() == Some("23514") => Ok(()), - Ok(_) => Err(DbError::InvalidData(format!( - "floor guard is inert: {what} was accepted (replica fence must stay closed)" - ))), - Err(e) => Err(DbError::InvalidData(format!( - "floor guard verification failed unexpectedly on {what}: {e}" - ))), - } - }; - - let connection = crate::observability::acquire_writer( - pool, - crate::observability::WriterOperation::Bootstrap, - ) - .await?; - let mut tx = sqlx::Transaction::begin(connection, None).await?; - - // 1. Pool arming (Perci: assert the effective value, not the intent). - let armed: String = sqlx::query_scalar("SHOW buzz.created_at_floor") - .fetch_one(&mut *tx) - .await - .map_err(|e| { - DbError::InvalidData(format!( - "buzz.created_at_floor GUC not set on this pool: {e}" - )) - })?; - if armed != CREATED_AT_FLOOR_SECS.to_string() { - return Err(DbError::InvalidData(format!( - "buzz.created_at_floor is '{armed}', expected '{CREATED_AT_FLOOR_SECS}': \ - pool is not armed" - ))); - } - - sqlx::query("SET CONSTRAINTS ALL IMMEDIATE") - .execute(&mut *tx) - .await?; - - // Scratch community satisfying the FK; the whole transaction rolls back. - let community = uuid::Uuid::new_v4(); - sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") - .bind(community) - .bind(format!("fence-verify-{}.invalid", community.simple())) - .execute(&mut *tx) - .await?; - let channel = uuid::Uuid::new_v4(); - - let insert = |tx_id: [u8; 32], age_secs: i64, ch: Option| { - sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, \ - content, sig, received_at, channel_id) \ - VALUES ($1, $2, $3, clock_timestamp() - make_interval(secs => $4::double precision), \ - 9, '[]', 'fence-verify', $5, NOW(), $6)", - ) - .bind(community) - .bind(tx_id.to_vec()) - .bind(vec![0u8; 32]) - .bind(age_secs as f64) - .bind(vec![0u8; 64]) - .bind(ch) - }; - let old_age = CREATED_AT_FLOOR_SECS + 60; - - // 2. Old channel-bearing insert must raise. - sqlx::query("SAVEPOINT floor_probe") - .execute(&mut *tx) - .await?; - let res = insert(rand_id(), old_age, Some(channel)) - .execute(&mut *tx) - .await; - expect_violation(res, "an old channel-bearing INSERT")?; - sqlx::query("ROLLBACK TO SAVEPOINT floor_probe") - .execute(&mut *tx) - .await?; - - // 3. Fresh channel-bearing insert must pass. - let fresh_id = rand_id(); - insert(fresh_id, 0, Some(channel)).execute(&mut *tx).await?; - - // 4. Rewriting created_at below the floor must raise (in- or - // cross-partition, either arm of the guard catches the NEW row). - sqlx::query("SAVEPOINT floor_probe") - .execute(&mut *tx) - .await?; - let res = sqlx::query( - "UPDATE events SET created_at = clock_timestamp() - make_interval(secs => $1::double precision) \ - WHERE community_id = $2 AND id = $3", - ) - .bind(old_age as f64) - .bind(community) - .bind(fresh_id.to_vec()) - .execute(&mut *tx) - .await; - expect_violation(res, "rewriting created_at below the floor")?; - sqlx::query("ROLLBACK TO SAVEPOINT floor_probe") - .execute(&mut *tx) - .await?; - - // 5. Old channel-NULL insert is exempt; flipping channel_id on must raise. - let null_id = rand_id(); - insert(null_id, old_age, None).execute(&mut *tx).await?; - sqlx::query("SAVEPOINT floor_probe") - .execute(&mut *tx) - .await?; - let res = sqlx::query("UPDATE events SET channel_id = $1 WHERE community_id = $2 AND id = $3") - .bind(channel) - .bind(community) - .bind(null_id.to_vec()) - .execute(&mut *tx) - .await; - expect_violation(res, "moving an old channel-NULL row into a channel")?; - sqlx::query("ROLLBACK TO SAVEPOINT floor_probe") - .execute(&mut *tx) - .await?; - - tx.rollback().await?; - Ok(()) -} - -fn rand_id() -> [u8; 32] { - let mut id = [0u8; 32]; - for chunk in id.chunks_mut(16) { - chunk.copy_from_slice(&uuid::Uuid::new_v4().into_bytes()[..chunk.len()]); - } - id -} - /// One writer-side sample of the ordered handshake. #[derive(Debug)] struct WriterSample { @@ -673,6 +471,17 @@ pub enum ProbeError { /// Number of other client backends with masked/unknown state. masked: i64, }, + /// A prepared (2PC) transaction exists. Its rows were floor-checked at + /// insert time, which `pg_prepared_xacts` cannot bound, and no supported + /// writer prepares transactions — treat it as out-of-band. + #[error( + "{prepared} prepared transaction(s) in pg_prepared_xacts — out-of-band writer; \ + replica floor cannot bound their rows" + )] + PreparedTransactions { + /// Number of prepared transactions in the cluster. + prepared: i64, + }, /// The single heartbeat row (migration 0026) is missing on the writer. #[error("replica_heartbeat row missing on the writer — migration 0026 not applied?")] HeartbeatRowMissing, @@ -698,6 +507,7 @@ impl ProbeError { Self::Writer(sqlx::Error::Io(_)) => "io", Self::Writer(_) => "writer", Self::MaskedActivity { .. } => "masked_activity", + Self::PreparedTransactions { .. } => "prepared_transactions", Self::HeartbeatRowMissing => "heartbeat_row_missing", Self::Deadline(_) => "deadline", } @@ -860,26 +670,27 @@ async fn sample_writer( // conservative direction (a long autovacuum merely holds the fence // back), and it keeps the classification simple. // Scope is every other backend regardless of role or application - // name: an admin psql transaction writes under the same trigger and - // must be representable in the oldest-xact term. + // name: every open transaction must be representable in the + // oldest-xact term. Out-of-band writes require a closed breaker. // // Prepared transactions (2PC) are a bucket of their own: while // prepared they have left `pg_stat_activity` but can still commit - // after the token. Their deferred floor guard already ran at PREPARE, - // so `pg_prepared_xacts.prepared` bounds their rows exactly like - // `xact_start`; fold it into the same minimum. Only the retained - // deferred trigger provides that PREPARE-time check: the insert-time - // app guard runs earlier, and no app writer issues PREPARE TRANSACTION. - // Dropping the trigger must keep this case covered. + // after the token. Only the retired deferred trigger checked their + // rows at PREPARE; the insert-time app guard runs earlier, at a clock + // `pg_prepared_xacts` does not expose, so `prepared` no longer bounds + // their rows. No supported writer issues PREPARE TRANSACTION (the + // source policy enforces it) and `max_prepared_transactions` defaults + // to 0, so any prepared transaction is out-of-band: fail closed. The + // count is cluster-wide, like the activity scan: a prepared + // transaction in any database on the writer is outside the supported + // deploy, so it closes the fence rather than being scoped away. let row = sqlx::query( r#" SELECT - least( - (SELECT min(xact_start) - FROM pg_stat_activity - WHERE pid <> pg_backend_pid()), - (SELECT min(prepared) FROM pg_prepared_xacts) - ) AS oldest_xact_start, + (SELECT min(xact_start) + FROM pg_stat_activity + WHERE pid <> pg_backend_pid()) AS oldest_xact_start, + (SELECT count(*) FROM pg_prepared_xacts) AS prepared, (SELECT count(*) FROM pg_stat_activity WHERE pid <> pg_backend_pid() @@ -896,6 +707,10 @@ async fn sample_writer( if masked > 0 { return Err(ProbeError::MaskedActivity { masked }); } + let prepared: i64 = row.get("prepared"); + if prepared > 0 { + return Err(ProbeError::PreparedTransactions { prepared }); + } let oldest_xact_start: Option> = row.get("oldest_xact_start"); Ok((sampled_at, oldest_xact_start)) }) @@ -1671,6 +1486,62 @@ mod postgres_tests { unpriv.close().await; } + /// With the floor trigger retired, nothing bounds a prepared (2PC) + /// transaction's rows by `pg_prepared_xacts.prepared`, so the sample must + /// fail closed while one exists. On a server with the default + /// `max_prepared_transactions = 0` (CI, compose, chart) the test instead + /// pins that 2PC is unavailable, which is the supported-writer exclusion. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn cluster_global_sample_writer_fails_closed_on_prepared_transaction() { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect"); + let max_prepared: String = sqlx::query_scalar("SHOW max_prepared_transactions") + .fetch_one(&pool) + .await + .expect("show max_prepared_transactions"); + + let gid = format!("fence_probe_{}", uuid::Uuid::new_v4().simple()); + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::query("BEGIN") + .execute(&mut *conn) + .await + .expect("begin"); + sqlx::query("SELECT 1") + .execute(&mut *conn) + .await + .expect("touch tx"); + let prepare = sqlx::query(sqlx::AssertSqlSafe(format!("PREPARE TRANSACTION '{gid}'"))) + .execute(&mut *conn) + .await; + + if max_prepared == "0" { + prepare.expect_err("PREPARE TRANSACTION must fail when 2PC is disabled"); + sqlx::query("ROLLBACK") + .execute(&mut *conn) + .await + .expect("rollback"); + return; + } + + prepare.expect("prepare transaction"); + drop(conn); + let result = sample_writer(&pool, &mut ProbeTimings::default()).await; + sqlx::query(sqlx::AssertSqlSafe(format!("ROLLBACK PREPARED '{gid}'"))) + .execute(&pool) + .await + .expect("rollback prepared"); + let err = result.expect_err("a prepared transaction must fail the sample closed"); + assert!( + matches!(err, ProbeError::PreparedTransactions { prepared } if prepared >= 1), + "expected PreparedTransactions, got {err:?}" + ); + sample_writer(&pool, &mut ProbeTimings::default()) + .await + .expect("sample succeeds once no transaction is prepared"); + } + /// The Aurora PostgreSQL identity function name is exact — the /// MySQL-family near-miss (`aurora_server_id`) would make the /// capability probe cache a permanent false on real Aurora and diff --git a/crates/buzz-db/src/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index f776346673..77c209eec3 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -430,316 +430,6 @@ async fn make_community(pool: &PgPool) -> Uuid { id } -#[tokio::test] -#[ignore = "requires Postgres"] -async fn migration_schema_database_guard_covers_legacy_writer_and_nip09_deletion() { - use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; - - let db = setup_db().await; - let community = CommunityId::from_uuid(make_community(&db.pool).await); - let keys = Keys::generate(); - let d_tag = format!("read-state:{}", "b".repeat(32)); - let tags = vec![ - Tag::parse(["d", d_tag.as_str()]).expect("d tag"), - Tag::parse(["t", "read-state"]).expect("t tag"), - ]; - let base = Timestamp::now().as_secs(); - let a = EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), "A") - .tags(tags.clone()) - .custom_created_at(Timestamp::from(base)) - .sign_with_keys(&keys) - .expect("sign A"); - let x = EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), "X") - .tags(tags.clone()) - .custom_created_at(Timestamp::from(base + 1)) - .sign_with_keys(&keys) - .expect("sign X"); - let b = EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), "B") - .tags(tags.clone()) - .custom_created_at(Timestamp::from(base + 2)) - .sign_with_keys(&keys) - .expect("sign B"); - let c = EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), "C") - .tags(tags) - .custom_created_at(Timestamp::from(base + 3)) - .sign_with_keys(&keys) - .expect("sign C"); - - async fn legacy_insert( - pool: &PgPool, - community: CommunityId, - event: &nostr::Event, - d_tag: &str, - ) -> std::result::Result { - sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, d_tag) \ - VALUES ($1, $2, $3, to_timestamp($4), $5, $6, $7, $8, NOW(), $9) ON CONFLICT DO NOTHING", - ) - .bind(community.as_uuid()) - .bind(event.id.as_bytes().as_slice()) - .bind(event.pubkey.to_bytes()) - .bind(event.created_at.as_secs() as f64) - .bind(buzz_core::kind::KIND_READ_STATE as i32) - .bind(serde_json::to_value(&event.tags).expect("serialize tags")) - .bind(&event.content) - .bind(event.sig.serialize().as_slice()) - .bind(d_tag) - .execute(pool) - .await - } - - legacy_insert(&db.pool, community, &a, &d_tag) - .await - .expect("legacy insert A"); - let duplicate = legacy_insert(&db.pool, community, &a, &d_tag) - .await - .expect("legacy duplicate A remains idempotent"); - assert_eq!(duplicate.rows_affected(), 0); - - sqlx::query( - "INSERT INTO event_mentions \ - (community_id, pubkey_hex, event_id, event_created_at, event_kind) \ - VALUES ($1, $2, $3, to_timestamp($4), 30078)", - ) - .bind(community.as_uuid()) - .bind("c".repeat(64)) - .bind(a.id.as_bytes().as_slice()) - .bind(a.created_at.as_secs() as f64) - .execute(&db.pool) - .await - .expect("insert live mention"); - - // Emulate the pre-PR replacement path after migration 0007: soft-delete - // the live row, then insert B without any application watermark write. - sqlx::query( - "UPDATE events SET deleted_at=NOW() \ - WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3 AND deleted_at IS NULL", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(&d_tag) - .execute(&db.pool) - .await - .expect("legacy soft-delete A"); - let mentions_after_delete: i64 = sqlx::query_scalar( - "SELECT count(*) FROM event_mentions WHERE community_id=$1 AND event_id=$2", - ) - .bind(community.as_uuid()) - .bind(a.id.as_bytes().as_slice()) - .fetch_one(&db.pool) - .await - .expect("count mentions after delete"); - assert_eq!(mentions_after_delete, 0); - - let stale_mention = sqlx::query( - "INSERT INTO event_mentions \ - (community_id, pubkey_hex, event_id, event_created_at, event_kind) \ - VALUES ($1, $2, $3, to_timestamp($4), 30078)", - ) - .bind(community.as_uuid()) - .bind("d".repeat(64)) - .bind(a.id.as_bytes().as_slice()) - .bind(a.created_at.as_secs() as f64) - .execute(&db.pool) - .await - .expect("stale post-commit mention is skipped"); - assert_eq!(stale_mention.rows_affected(), 0); - - legacy_insert(&db.pool, community, &b, &d_tag) - .await - .expect("legacy insert B"); - let duplicate_b = legacy_insert(&db.pool, community, &b, &d_tag) - .await - .expect("live duplicate B is skipped"); - assert_eq!(duplicate_b.rows_affected(), 0); - - sqlx::query( - "INSERT INTO event_mentions \ - (community_id, pubkey_hex, event_id, event_created_at, event_kind) \ - VALUES ($1, $2, $3, to_timestamp($4), 30078)", - ) - .bind(community.as_uuid()) - .bind("e".repeat(64)) - .bind(b.id.as_bytes().as_slice()) - .bind(b.created_at.as_secs() as f64) - .execute(&db.pool) - .await - .expect("insert B mention"); - - // Exercise the new Rust hard-delete path independently. An in-flight - // mention holds KEY SHARE on B, so replacement by C must block, then - // complete after the mention commits and remove both B and its mention. - let mut rust_mention_tx = db - .pool - .begin() - .await - .expect("begin Rust mention transaction"); - sqlx::query( - "INSERT INTO event_mentions \ - (community_id, pubkey_hex, event_id, event_created_at, event_kind) \ - VALUES ($1, $2, $3, to_timestamp($4), 30078) ON CONFLICT DO NOTHING", - ) - .bind(community.as_uuid()) - .bind("e".repeat(64)) - .bind(b.id.as_bytes().as_slice()) - .bind(b.created_at.as_secs() as f64) - .execute(&mut *rust_mention_tx) - .await - .expect("hold B live-event key-share lock"); - - let replace_db = db.clone(); - let replace_d_tag = d_tag.clone(); - let replace_c = c.clone(); - let replace_task = tokio::spawn(async move { - replace_db - .replace_parameterized_event(community, &replace_c, &replace_d_tag, None) - .await - }); - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - assert!( - !replace_task.is_finished(), - "Rust hard delete should wait for mention lock" - ); - rust_mention_tx - .commit() - .await - .expect("release Rust mention lock"); - let replaced = tokio::time::timeout(std::time::Duration::from_secs(2), replace_task) - .await - .expect("Rust hard delete deadlocked with mention insert") - .expect("replacement task panicked") - .expect("replace B with C"); - assert!(replaced.1, "C must replace B"); - let b_mentions: i64 = sqlx::query_scalar( - "SELECT count(*) FROM event_mentions WHERE community_id=$1 AND event_id=$2", - ) - .bind(community.as_uuid()) - .bind(b.id.as_bytes().as_slice()) - .fetch_one(&db.pool) - .await - .expect("count B mentions after Rust replacement"); - assert_eq!(b_mentions, 0); - - sqlx::query( - "INSERT INTO event_mentions \ - (community_id, pubkey_hex, event_id, event_created_at, event_kind) \ - VALUES ($1, $2, $3, to_timestamp($4), 30078)", - ) - .bind(community.as_uuid()) - .bind("f".repeat(64)) - .bind(c.id.as_bytes().as_slice()) - .bind(c.created_at.as_secs() as f64) - .execute(&db.pool) - .await - .expect("insert C mention"); - - // Exercise legacy UPDATE-trigger deletion with the same barrier. While - // deletion waits on C's KEY SHARE lock, an exact replay must already be - // a zero-row trigger no-op; it must not wait for deletion or resurrect C. - let mut legacy_mention_tx = db - .pool - .begin() - .await - .expect("begin legacy mention transaction"); - sqlx::query( - "INSERT INTO event_mentions \ - (community_id, pubkey_hex, event_id, event_created_at, event_kind) \ - VALUES ($1, $2, $3, to_timestamp($4), 30078) ON CONFLICT DO NOTHING", - ) - .bind(community.as_uuid()) - .bind("f".repeat(64)) - .bind(c.id.as_bytes().as_slice()) - .bind(c.created_at.as_secs() as f64) - .execute(&mut *legacy_mention_tx) - .await - .expect("hold C live-event key-share lock"); - - let delete_pool = db.pool.clone(); - let delete_pubkey = keys.public_key().to_bytes(); - let delete_d_tag = d_tag.clone(); - let delete_task = tokio::spawn(async move { - sqlx::query( - "UPDATE events SET deleted_at=NOW() \ - WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3 AND deleted_at IS NULL", - ) - .bind(community.as_uuid()) - .bind(delete_pubkey) - .bind(delete_d_tag) - .execute(&delete_pool) - .await - }); - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - assert!( - !delete_task.is_finished(), - "legacy delete should wait for mention lock" - ); - - let replay_while_delete_waits = legacy_insert(&db.pool, community, &c, &d_tag) - .await - .expect("concurrent exact C replay is skipped"); - assert_eq!(replay_while_delete_waits.rows_affected(), 0); - - legacy_mention_tx - .commit() - .await - .expect("release legacy mention lock"); - tokio::time::timeout(std::time::Duration::from_secs(2), delete_task) - .await - .expect("legacy delete deadlocked with mention insert") - .expect("delete task panicked") - .expect("legacy NIP-09 delete C"); - - let payloads: i64 = sqlx::query_scalar( - "SELECT count(*) FROM events WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(&d_tag) - .fetch_one(&db.pool) - .await - .expect("count retained payloads"); - assert_eq!( - payloads, 0, - "legacy soft deletes must not retain NIP-RS payloads" - ); - - // Opposite commit order: deletion has committed before exact replay. - // Equality remains an observable zero-row no-op, never a resurrection. - let replay_c = legacy_insert(&db.pool, community, &c, &d_tag) - .await - .expect("post-delete exact C replay is skipped"); - assert_eq!(replay_c.rows_affected(), 0); - let payloads_after_exact_replay: i64 = sqlx::query_scalar( - "SELECT count(*) FROM events WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(&d_tag) - .fetch_one(&db.pool) - .await - .expect("count payloads after exact replay"); - assert_eq!(payloads_after_exact_replay, 0); - - let replay = legacy_insert(&db.pool, community, &x, &d_tag).await; - assert!( - replay.is_err(), - "database guard must reject A < X < C replay" - ); - - let watermark: (chrono::DateTime, Vec) = sqlx::query_as( - "SELECT created_at, event_id FROM parameterized_event_watermarks \ - WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(&d_tag) - .fetch_one(&db.pool) - .await - .expect("read C watermark"); - assert_eq!(watermark.0.timestamp(), base as i64 + 3); - assert_eq!(watermark.1, c.id.as_bytes().as_slice()); -} - #[tokio::test] #[ignore = "requires Postgres"] async fn migration_schema_operator_listener_outbox_is_not_tenant_scoped() { @@ -2236,7 +1926,7 @@ async fn saturated_reader_spends_one_acquire_budget_and_rejects_history_reads() seed.close().await; let scratch_url = scratch.url().to_owned(); - // `Db::new` so the writer arms the floor guard and the reader is the + // `Db::new` so the writer uses production session policy and the reader is the // real lazy `connect_read_pool` pool (warm floor of 1, 150ms // acquire timeout). Reader is sized 1 so holding one connection // saturates it. @@ -2570,9 +2260,8 @@ async fn routed_reads_are_confined_to_the_requested_community() { } /// D4: a LAZY reader pool (connect_lazy, never yet -/// used) must still let [`Db::spawn_fence_probe`] verify the writer's -/// floor guard and spawn — reader-down or reader-idle at boot must not -/// disable fence probing. +/// used) must still let [`Db::spawn_fence_probe`] spawn — reader-down or +/// reader-idle at boot must not disable fence probing. #[tokio::test] #[ignore = "requires Postgres"] async fn lazy_reader_pool_still_spawns_fence_probe() { @@ -2580,11 +2269,7 @@ async fn lazy_reader_pool_still_spawns_fence_probe() { seed.close().await; let writer_url = scratch.url().to_owned(); - // `Db::new` (not `from_pools`) so the WRITER pool arms the - // `buzz.created_at_floor` GUC — `spawn_fence_probe` verifies the - // floor guard on a writer connection, and `ScratchDb::migrated`'s - // plain `PgPool::connect` never arms it. The reader is still the - // lazy `connect_read_pool` pool this test is about. + // Use the production writer policy and lazy `connect_read_pool`. let db = Db::new(&DbConfig { database_url: writer_url.clone(), read_database_url: Some(writer_url), @@ -2592,12 +2277,9 @@ async fn lazy_reader_pool_still_spawns_fence_probe() { ..DbConfig::default() }) .await - .expect("connect armed Db with lazy reader"); + .expect("connect Db with lazy reader"); - let spawned = db - .spawn_fence_probe() - .await - .expect("floor-guard verification must pass on the migrated writer"); + let spawned = db.spawn_fence_probe(); assert!(spawned, "a configured (lazy) reader must spawn the probe"); } @@ -2623,7 +2305,7 @@ async fn fence_probe_beats_while_serving_writer_pool_is_exhausted() { .await .expect("connect armed Db with one serving writer connection"); assert!( - db.spawn_fence_probe().await.expect("verification passes"), + db.spawn_fence_probe(), "a configured reader must spawn the probe" ); @@ -2930,95 +2612,6 @@ async fn thread_full_replica_page_above_fence_is_reverified_on_writer() { ); } -/// Commit-time floor guard (migration 0021), exact held-transaction -/// adversary: a channel-bearing row whose `created_at` is older than the -/// floor at COMMIT time must abort the transaction — the guard runs -/// inside commit processing with `clock_timestamp()`, so holding the -/// transaction open cannot outrun it. channel_id-NULL rows are -/// structurally exempt, and sessions without the GUC are unaffected. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn created_at_floor_guard_aborts_old_channel_rows_at_commit() { - let (pool, _scratch) = ScratchDb::migrated(&admin_url().await, "floor_guard").await; - - let author = nostr::Keys::generate(); - let community = Uuid::new_v4(); - let channel = Uuid::new_v4(); - seed_community_channel(&pool, community, channel, &author).await; - - let insert_raw = |ev: nostr::Event, channel_id: Option| { - let pool = pool.clone(); - async move { - let mut tx = pool.begin().await.expect("begin"); - // Arm the guard for this transaction only (the relay's - // writer pool arms it per connection; tests are explicit). - sqlx::query("SELECT set_config('buzz.created_at_floor', $1, true)") - .bind(crate::replica_fence::CREATED_AT_FLOOR_SECS.to_string()) - .execute(&mut *tx) - .await - .expect("arm guard"); - sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, \ - content, sig, received_at, channel_id) \ - VALUES ($1, $2, $3, to_timestamp($4), 9, '[]', $5, $6, NOW(), $7)", - ) - .bind(community) - .bind(ev.id.as_bytes().as_slice()) - .bind(ev.pubkey.to_bytes().as_slice()) - .bind(ev.created_at.as_secs() as f64) - .bind(&ev.content) - .bind(ev.sig.serialize().as_slice()) - .bind(channel_id) - .execute(&mut *tx) - .await - .expect("insert inside tx (guard is deferred to commit)"); - // Hold the transaction "open" past the insert, then commit — - // the deferred guard must still see the stale created_at. - sqlx::query("SELECT pg_sleep(0.05)") - .execute(&mut *tx) - .await - .expect("hold tx"); - tx.commit().await - } - }; - - let now_secs = chrono::Utc::now().timestamp() as u64; - let floor = crate::replica_fence::CREATED_AT_FLOOR_SECS as u64; - - // Old channel-bearing row → COMMIT aborts with check_violation. - let old = signed_event_at(&author, "old-held-tx", now_secs - floor - 60); - let err = insert_raw(old, Some(channel)) - .await - .expect_err("below-floor channel row must abort at COMMIT"); - let code = match &err { - sqlx::Error::Database(db_err) => db_err.code().map(|c| c.to_string()), - other => panic!("expected database error, got {other:?}"), - }; - assert_eq!( - code.as_deref(), - Some("23514"), - "guard raises check_violation" - ); - - // Fresh channel-bearing row → commits. - let fresh = signed_event_at(&author, "fresh", now_secs); - insert_raw(fresh, Some(channel)) - .await - .expect("fresh row commits under the armed guard"); - - // Old row WITHOUT a channel (push lease / profile shapes) → - // structurally exempt, commits. - let old_global = signed_event_at(&author, "old-global", now_secs - floor - 60); - insert_raw(old_global, None) - .await - .expect("channel_id-NULL rows are exempt from the floor"); - - // Unarmed session (no GUC) → guard inert; backfills stay possible - // (and must hold the fence closed, per the migration header). - let old_backfill = signed_event_at(&author, "old-backfill", now_secs - floor - 60); - insert_top_level(&pool, community, channel, &old_backfill).await; -} - #[test] fn writer_pool_safety_hook_is_single_and_composed() { let source = include_str!("mod.rs"); @@ -3032,13 +2625,10 @@ fn writer_pool_safety_hook_is_single_and_composed() { 1, "SQLx replaces after_connect hooks; writer safety must use exactly one" ); - assert!(connect_pool.contains("buzz.created_at_floor")); assert!(connect_pool.contains("SHOW transaction_isolation")); assert!(connect_pool.contains("'lock_timeout'")); assert!(connect_pool.contains("'idle_in_transaction_session_timeout'")); assert!(connect_pool.contains("'statement_timeout'")); - assert!(!connect_pool.contains("arm_floor_guard")); - assert!(!connect_pool.contains("_arm_floor_guard")); assert!(!connect_pool.contains("allow(unused_variables)")); let reader_doc = source @@ -3095,7 +2685,6 @@ async fn writer_pool_metrics_record_every_initial_connection_ready() { 2 ); for step in [ - DbConnectionStep::CreatedAtFloor, DbConnectionStep::SessionTimeouts, DbConnectionStep::Isolation, ] { @@ -3530,100 +3119,6 @@ async fn session_timeouts_install_through_db_new_and_bound_lock_waits() { drop(holder); } -/// The armed writer pool (`Db::new`) must enforce the floor end-to-end -/// through the public insert APIs, and the session GUC must be verifiably -/// set on pooled connections. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn armed_pool_rejects_old_channel_inserts_through_public_api() { - let (seed_pool, scratch) = ScratchDb::migrated(&admin_url().await, "floor_pool").await; - - let author = nostr::Keys::generate(); - let community = Uuid::new_v4(); - let channel = Uuid::new_v4(); - seed_community_channel(&seed_pool, community, channel, &author).await; - - // Connect a Db the production way: after_connect arms the guard. - let scratch_url = scratch.url().to_owned(); - let db = Db::new(&DbConfig { - database_url: scratch_url, - max_connections: 2, - ..DbConfig::default() - }) - .await - .expect("connect armed Db"); - let cid = CommunityId::from_uuid(community); - - // Perci nit: assert the effective session value, not the intent. - let effective: String = sqlx::query_scalar("SHOW buzz.created_at_floor") - .fetch_one(&db.pool) - .await - .expect("SHOW guard GUC"); - assert_eq!( - effective, - crate::replica_fence::CREATED_AT_FLOOR_SECS.to_string(), - "writer pool must arm the floor guard on every connection" - ); - let isolation: String = sqlx::query_scalar("SHOW transaction_isolation") - .fetch_one(&db.pool) - .await - .expect("SHOW writer isolation"); - assert_eq!( - isolation, "read committed", - "the same writer after_connect hook must enforce the isolation premise" - ); - - let now_secs = chrono::Utc::now().timestamp() as u64; - let floor = crate::replica_fence::CREATED_AT_FLOOR_SECS as u64; - - // insert_event (single INSERT, autocommit): old channel row rejected. - let old = signed_event_at(&author, "old-direct", now_secs - floor - 60); - let err = event::insert_event(&db.pool, cid, &old, Some(channel)) - .await - .expect_err("armed pool must reject below-floor channel inserts"); - assert!( - err.to_string().contains("below the replica-fence floor"), - "unexpected error: {err}" - ); - - // insert_event_with_thread_metadata (multi-statement tx): same. - let old2 = signed_event_at(&author, "old-thread-meta", now_secs - floor - 90); - let ts = - chrono::DateTime::from_timestamp(old2.created_at.as_secs() as i64, 0).expect("valid ts"); - let err = event::insert_event_with_thread_metadata( - &db.pool, - cid, - &old2, - Some(channel), - Some(event::ThreadMetadataParams { - event_id: old2.id.as_bytes(), - event_created_at: ts, - channel_id: channel, - parent_event_id: None, - parent_event_created_at: None, - root_event_id: None, - root_event_created_at: None, - depth: 0, - broadcast: true, - }), - ) - .await - .expect_err("armed pool must reject below-floor thread-metadata inserts"); - assert!( - err.to_string().contains("below the replica-fence floor"), - "unexpected error: {err}" - ); - - // Fresh events pass through both APIs. - let fresh = signed_event_at(&author, "fresh-direct", now_secs); - event::insert_event(&db.pool, cid, &fresh, Some(channel)) - .await - .expect("fresh insert passes the armed guard"); - - // Close before the `scratch` guard force-drops the database on return. - db.pool.close().await; -} - /// A writer transaction holding the shared replica-floor advisory lock, the /// shape a floor-compliant writer takes before the exclusive probe can run. async fn begin_replica_floor_locked_writer(db: &Db) -> sqlx::Transaction<'static, sqlx::Postgres> { @@ -3631,7 +3126,7 @@ async fn begin_replica_floor_locked_writer(db: &Db) -> sqlx::Transaction<'static .pool .begin() .await - .expect("begin floor-guarded writer tx"); + .expect("begin floor-compliant writer tx"); sqlx::query("SELECT pg_advisory_xact_lock_shared($1)") .bind(crate::replica_fence::REPLICA_FLOOR_LOCK_KEY) .execute(&mut *tx) @@ -3749,172 +3244,6 @@ async fn cluster_global_replica_floor_probe_waits_for_shared_writer_and_records_ db.pool.close().await; } -/// `spawn_fence_probe` must verify the floor guard before letting the -/// probe run — catalog shape AND observed behavior — and refuse on -/// sabotage. This is the production gate for a relay running with -/// `BUZZ_AUTO_MIGRATE` off: an armed GUC with no enforcing trigger must -/// never yield an open fence. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn fence_probe_refuses_to_start_without_verified_floor_guard() { - let (seed_pool, writer_db) = ScratchDb::migrated(&admin_url().await, "fence_gate_w").await; - let (replica_pool, replica_db) = ScratchDb::migrated(&admin_url().await, "fence_gate_r").await; - seed_pool.close().await; - replica_pool.close().await; - - let writer_url = writer_db.url().to_owned(); - let replica_url = replica_db.url().to_owned(); - - // Healthy schema: verification passes, probe starts. A SEPARATE Db - // instance, because its background probe legitimately opens its own - // fence (the heartbeat probe is writer-side only) — the refusal - // assertions below must run against a fence whose spawns were all - // refused. - let db_healthy = Db::new(&DbConfig { - database_url: writer_url.clone(), - read_database_url: Some(replica_url.clone()), - max_connections: 2, - ..DbConfig::default() - }) - .await - .expect("connect armed Db with replica"); - assert!( - db_healthy - .spawn_fence_probe() - .await - .expect("verification passes"), - "probe must start on a verified schema" - ); - - let db = Db::new(&DbConfig { - database_url: writer_url, - read_database_url: Some(replica_url), - max_connections: 2, - ..DbConfig::default() - }) - .await - .expect("connect armed Db with replica"); - - // Sabotage A: catalog-shaped no-op — same trigger, gutted function - // body. Catalog check alone would pass; behavior check must refuse. - sqlx::query( - "CREATE OR REPLACE FUNCTION events_created_at_floor_guard() RETURNS trigger \ - LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END $$", - ) - .execute(&db.pool) - .await - .expect("gut the guard function"); - let err = db - .spawn_fence_probe() - .await - .expect_err("inert guard body must refuse the probe"); - assert!( - err.to_string().contains("floor guard is inert"), - "unexpected error: {err}" - ); - - // Sabotage B: trigger dropped entirely (the BUZZ_AUTO_MIGRATE=off / - // 0021-unapplied shape). Catalog check must refuse. - sqlx::query("DROP TRIGGER events_created_at_floor ON events") - .execute(&db.pool) - .await - .expect("drop the guard trigger"); - let err = db - .spawn_fence_probe() - .await - .expect_err("missing trigger must refuse the probe"); - assert!( - err.to_string().contains("missing or mis-shaped"), - "unexpected error: {err}" - ); - - // In both refusal states the fence never opened. - assert!( - db.fence().verified_through().is_none(), - "fence must remain closed when verification refuses the probe" - ); -} - -/// The `UPDATE OF` arm of the floor guard (Perci's second structural -/// hole): an old row legitimately admitted with `channel_id` NULL must -/// not be movable into keyset windows, and a channel row's `created_at` -/// must not be movable below the fence — through raw SQL, at COMMIT. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn floor_guard_blocks_updates_that_move_rows_below_the_fence() { - let (pool, _scratch) = ScratchDb::migrated(&admin_url().await, "floor_upd").await; - - let author = nostr::Keys::generate(); - let community = Uuid::new_v4(); - let channel = Uuid::new_v4(); - seed_community_channel(&pool, community, channel, &author).await; - - let now_secs = chrono::Utc::now().timestamp() as u64; - let floor = crate::replica_fence::CREATED_AT_FLOOR_SECS as u64; - - // Seed via unarmed session: one old channel-NULL row, one fresh - // channel row. - let old_null = signed_event_at(&author, "old-null", now_secs - floor - 120); - insert_top_level(&pool, community, channel, &old_null).await; - sqlx::query("UPDATE events SET channel_id = NULL WHERE community_id = $1 AND id = $2") - .bind(community) - .bind(old_null.id.as_bytes().as_slice()) - .execute(&pool) - .await - .expect("detach channel (unarmed seed)"); - let fresh = signed_event_at(&author, "fresh-row", now_secs); - insert_top_level(&pool, community, channel, &fresh).await; - - // Armed transaction, deferred to COMMIT (the production shape). - let run_armed_update = |sql: &'static str, id: Vec, age: Option| { - let pool = pool.clone(); - async move { - let mut tx = pool.begin().await.expect("begin"); - sqlx::query("SELECT set_config('buzz.created_at_floor', $1, true)") - .bind(crate::replica_fence::CREATED_AT_FLOOR_SECS.to_string()) - .execute(&mut *tx) - .await - .expect("arm guard"); - let q = sqlx::query(sql).bind(community).bind(id); - let q = match age { - Some(a) => q.bind(a as f64), - None => q, - }; - q.execute(&mut *tx) - .await - .expect("update inside tx (deferred)"); - tx.commit().await - } - }; - - // channel-NULL → channel-bearing on an old row: COMMIT must abort. - let err = run_armed_update( - "UPDATE events SET channel_id = community_id WHERE community_id = $1 AND id = $2", - old_null.id.as_bytes().to_vec(), - None, - ) - .await - .expect_err("moving an old channel-NULL row into a channel must abort at COMMIT"); - assert!( - matches!(&err, sqlx::Error::Database(e) if e.code().as_deref() == Some("23514")), - "unexpected error: {err}" - ); - - // created_at rewrite below the floor on a channel row: COMMIT must abort. - let err = run_armed_update( - "UPDATE events SET created_at = clock_timestamp() - make_interval(secs => $3::double precision) \ - WHERE community_id = $1 AND id = $2", - fresh.id.as_bytes().to_vec(), - Some(floor + 120), - ) - .await - .expect_err("rewriting created_at below the floor must abort at COMMIT"); - assert!( - matches!(&err, sqlx::Error::Database(e) if e.code().as_deref() == Some("23514")), - "unexpected error: {err}" - ); -} - // ---- Statement-deadline cancellation vs. replica fallback ---------------- // // A replica read cancelled by `statement_timeout` (SQLSTATE 57014) must be diff --git a/crates/buzz-db/src/runtime/tests/floor_retirement.rs b/crates/buzz-db/src/runtime/tests/floor_retirement.rs new file mode 100644 index 0000000000..01cac27ae9 --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/floor_retirement.rs @@ -0,0 +1,145 @@ +//! Contract-migration coverage; application insert coverage belongs to phase 1. + +use super::*; + +async fn floor_objects(pool: &PgPool) -> (i64, i64) { + sqlx::query_as( + "SELECT (SELECT count(*) FROM pg_trigger WHERE tgname = 'events_created_at_floor'), \ + (SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace \ + WHERE n.nspname = 'public' AND p.proname = 'events_created_at_floor_guard')", + ) + .fetch_one(pool) + .await + .expect("read floor catalog") +} + +async fn retained_guards(pool: &PgPool) -> Vec<(String, String)> { + sqlx::query_as( + "SELECT c.relname, pg_get_triggerdef(t.oid) FROM pg_trigger t \ + JOIN pg_class c ON c.oid = t.tgrelid \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + WHERE n.nspname = 'public' AND t.tgname <> 'events_created_at_floor' \ + UNION ALL \ + SELECT c.relname, pg_get_constraintdef(k.oid) FROM pg_constraint k \ + JOIN pg_class c ON c.oid = k.conrelid \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + WHERE n.nspname = 'public' AND k.contype = 'f' \ + ORDER BY 1, 2", + ) + .fetch_all(pool) + .await + .expect("read retained triggers and foreign keys") +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_floor_retirement_drops_parent_and_partition_clones() { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect isolated migration database"); + crate::migration::run_migrations_through(&pool, 88) + .await + .expect("apply pre-contract schema"); + let partitions: i64 = + sqlx::query_scalar("SELECT count(*) FROM pg_partition_tree('events'::regclass)") + .fetch_one(&pool) + .await + .expect("count parent and partitions"); + assert_eq!(floor_objects(&pool).await, (partitions, 1)); + let before = retained_guards(&pool).await; + crate::migration::run_migrations_through(&pool, 89) + .await + .expect("apply contract migration"); + assert_eq!(floor_objects(&pool).await, (0, 0)); + assert_eq!(retained_guards(&pool).await, before); + crate::migration::run_migrations(&pool) + .await + .expect("apply later migrations and retained startup checks"); + assert_eq!(floor_objects(&pool).await, (0, 0)); + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_floor_retirement_cleans_child_copies_idempotently() { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect isolated migration database"); + crate::migration::run_migrations_through(&pool, 88) + .await + .expect("apply pre-contract schema"); + // Model independently attached copies after the parent guard was removed. + sqlx::raw_sql( + "DROP TRIGGER events_created_at_floor ON events; \ + CREATE CONSTRAINT TRIGGER events_created_at_floor \ + AFTER INSERT OR UPDATE OF created_at, channel_id ON events_p_past \ + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW \ + EXECUTE FUNCTION events_created_at_floor_guard();", + ) + .execute(&pool) + .await + .expect("install independent child copy"); + assert_eq!(floor_objects(&pool).await, (1, 1)); + let before = retained_guards(&pool).await; + crate::migration::run_migrations_through(&pool, 89) + .await + .expect("retire independent copy"); + assert_eq!(floor_objects(&pool).await, (0, 0)); + let mut tx = pool.begin().await.expect("begin idempotence check"); + sqlx::raw_sql(include_str!( + "../../../../../migrations/0089_retire_created_at_floor.sql" + )) + .execute(&mut *tx) + .await + .expect("repeat contract SQL after retirement"); + tx.commit().await.expect("commit repeated retirement"); + assert_eq!(floor_objects(&pool).await, (0, 0)); + assert_eq!(retained_guards(&pool).await, before); + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn floor_retirement_desired_state_has_no_floor_objects() { + // The nextest wrapper bootstraps this database through real pgschema apply + // and reconciliation; desired-state/migration parity is checked by + // `admin_schema_parity_between_desired_state_and_migrations`. + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect desired-state database"); + assert_eq!(floor_objects(&pool).await, (0, 0)); + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cluster_global_floor_retirement_writer_and_probe_run_on_retired_schema() { + let url = crate::test_support::database_url(); + let db = Db::new(&DbConfig { + database_url: url.clone(), + read_database_url: Some(url), + max_connections: 2, + min_connections: 1, + ..DbConfig::default() + }) + .await + .expect("connect production writer with retired schema"); + let armed: Option = + sqlx::query_scalar("SELECT nullif(current_setting('buzz.created_at_floor', true), '')") + .fetch_one(&db.pool) + .await + .expect("inspect writer session setting"); + assert_eq!(armed, None, "writer must no longer arm the retired guard"); + assert_eq!(floor_objects(&db.pool).await, (0, 0)); + assert!(db.spawn_fence_probe()); + crate::replica_fence::probe_once(&db.pool, db.fence()) + .await + .expect("retired schema still supports the ordered heartbeat"); + + db.pool.close().await; + db.read_pool + .as_ref() + .expect("reader configured") + .close() + .await; +} diff --git a/crates/buzz-db/src/runtime/tests/schema_fence_bootstrap_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/schema_fence_bootstrap_postgres_tests.rs deleted file mode 100644 index 67eb9a9a99..0000000000 --- a/crates/buzz-db/src/runtime/tests/schema_fence_bootstrap_postgres_tests.rs +++ /dev/null @@ -1,39 +0,0 @@ -use sqlx::PgPool; - -/// A fresh bootstrap keeps the declared backstops but never discovers new -/// community tables and silently attaches a trigger to them. -#[tokio::test] -#[ignore = "requires Postgres"] -async fn migration_schema_bootstrap_keeps_only_explicit_legacy_fences() { - let pool = PgPool::connect(&crate::test_support::database_url()) - .await - .unwrap(); - sqlx::raw_sql("CREATE TABLE new_tenant_probe (community_id UUID NOT NULL)") - .execute(&pool) - .await - .unwrap(); - // Only checked-in schema files contribute SQL to this test bootstrap. - sqlx::raw_sql(sqlx::AssertSqlSafe( - crate::test_support::desired_state_schema_sql(), - )) - .execute(&pool) - .await - .unwrap(); - - for (table, expected) in [ - ("new_tenant_probe", false), - ("events", true), - ("users", true), - ] { - let fenced: bool = sqlx::query_scalar( - "SELECT EXISTS (SELECT 1 FROM pg_trigger \ - WHERE tgrelid = $1::regclass \ - AND tgfoid = 'enforce_community_write_fence()'::regprocedure)", - ) - .bind(table) - .fetch_one(&pool) - .await - .unwrap(); - assert_eq!(fenced, expected, "unexpected fence on {table}"); - } -} diff --git a/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs index 93e61bde7a..ac31f6043f 100644 --- a/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs +++ b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs @@ -237,7 +237,7 @@ async fn migration_schema_thread_window_prebuild_does_not_queue_behind_writer() .unwrap(); // Model an ingestion transaction already holding the table's writer lock. - // It stays held through every control: releasing it would hide the convoy. + // It stays held through the 0049 index controls that this test exercises. let mut writer = pool.begin().await.unwrap(); sqlx::query("LOCK TABLE thread_metadata IN ROW EXCLUSIVE MODE") .execute(&mut *writer) @@ -283,8 +283,10 @@ async fn migration_schema_thread_window_prebuild_does_not_queue_behind_writer() .await .unwrap(); - // Also bind the public migrator: the advisory schema/destruction lock, - // ledger write and post-migration catalog checks must work with ingestion. + // Later migrations include table DDL such as the universal-fence trigger + // retirement, which correctly waits for writers. Release this writer after + // proving 0049 does not queue, then validate the full public migrator. + writer.rollback().await.unwrap(); let production_result = migration::run_migrations(&pool).await; sqlx::query(insert) .bind(community) @@ -309,7 +311,6 @@ async fn migration_schema_thread_window_prebuild_does_not_queue_behind_writer() .await .unwrap(); drop(witness); - writer.rollback().await.unwrap(); assert!( result.is_ok(), diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 0cc325f4f7..76e8f87b30 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -165,9 +165,7 @@ pub const APPROVAL_FORWARD_TABLES: &[&str] = &[ const EXCLUDED_SCOPED_TABLES: &[&str] = &[ "community_deletion_requests", "community_deletion_approvals", - "community_deletion_checkpoints", "community_serving_write_leases", - "community_deletion_executor_heartbeats", "product_feedback", "rate_limit_violations", "operator_listener_outbox", @@ -438,7 +436,7 @@ pub struct SchemaManifest { /// Per-table row counts for the target. pub row_counts: BTreeMap, /// Legacy fence snapshot retained for existing frozen inventory digests. - /// Populated from the live catalog while mixed-version executors need it. + /// New inventories leave it empty after trigger retirement. #[serde(default)] pub fenced_tables: Vec, } @@ -1322,7 +1320,6 @@ impl DeletionStore { pub async fn inventory_schema(&self, community: CommunityId) -> Result { self.validate_catalog().await?; let live_tables = self.live_scoped_tables().await?; - let fenced_tables = self.live_fenced_tables().await?; let mut row_counts = BTreeMap::new(); for table in &live_tables { let sql = format!("SELECT count(*)::BIGINT FROM {table} WHERE community_id = $1"); @@ -1338,7 +1335,7 @@ impl DeletionStore { Ok(SchemaManifest { scoped_tables: live_tables.into_iter().collect(), row_counts, - fenced_tables: fenced_tables.into_iter().collect(), + fenced_tables: Vec::new(), }) } @@ -2356,12 +2353,6 @@ impl DeletionStore { validate_catalog_on(&mut tx).await?; verify_lease_and_fence(&mut tx, token, DeletionStage::BindingsRemoved, generation).await?; set_executor_gucs(&mut tx, token.community_id, generation).await?; - // Migration 0011 fences hard deletion of NIP-RS rows against legacy - // writers. Whole-community deletion is an intentional hard-delete path, - // and the transaction is already bound to an approved, fenced tenant. - sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") - .execute(&mut *tx) - .await?; // Preserve deployment-global operator evidence while severing tenant provenance. for table in ["product_feedback", "rate_limit_violations"] { @@ -3402,11 +3393,6 @@ impl DeletionStore { let mut conn = self.pool.acquire().await?; live_scoped_tables_on(&mut conn).await } - - async fn live_fenced_tables(&self) -> Result> { - let mut conn = self.pool.acquire().await?; - live_fenced_tables_on(&mut conn).await - } } async fn lock_community_deletion( @@ -3568,32 +3554,6 @@ async fn live_scoped_tables_on(conn: &mut PgConnection) -> Result Result> { - let rows: Vec = sqlx::query_scalar( - r#" - SELECT c.relname - FROM pg_trigger trigger - JOIN pg_class c ON c.oid = trigger.tgrelid - JOIN pg_namespace n ON n.oid = c.relnamespace - JOIN pg_proc procedure ON procedure.oid = trigger.tgfoid - WHERE n.nspname = 'public' - AND NOT trigger.tgisinternal - AND NOT c.relispartition - AND procedure.proname = 'enforce_community_write_fence' - AND trigger.tgenabled = 'O' - AND (trigger.tgtype & 1) = 1 - AND (trigger.tgtype & 2) = 2 - AND (trigger.tgtype & 4) = 4 - AND (trigger.tgtype & 8) = 8 - AND (trigger.tgtype & 16) = 16 - ORDER BY c.relname - "#, - ) - .fetch_all(conn) - .await?; - Ok(rows.into_iter().collect()) -} - /// Fail closed when a community-prefix inventory has an unsafe shape. pub fn validate_storage_manifest(manifest: &StorageManifest) -> Result<()> { if !matches!(manifest.version, 4 | 5) { @@ -4056,24 +4016,6 @@ mod tests { } } - #[test] - fn scoped_table_exclusions_match_sql_during_transition() { - let sql = - include_str!("../../../../schema/functions/community_write_fence_excluded_table.sql"); - let sql_names = sql - .split("ARRAY[") - .nth(1) - .expect("SQL exclusion array") - .split(']') - .next() - .expect("SQL exclusion names") - .split(',') - .map(|name| name.trim().trim_matches('\'')) - .collect::>(); - assert_eq!(sql_names.len(), 8); - assert_eq!(sql_names, EXCLUDED_SCOPED_TABLES.iter().copied().collect()); - } - fn empty_prefix(prefix: &str) -> PrefixManifest { PrefixManifest { prefix: prefix.to_string(), @@ -4654,6 +4596,94 @@ mod postgres_tests { (db, store) } + /// Replaces the SQL-parity check retired with the fence functions. + /// + /// A name in `EXCLUDED_SCOPED_TABLES` hides that table from deletion + /// catalog drift detection, so the list is pinned against control-plane + /// tables written out here, not derived from either tenant manifest, and + /// each must still exist with community provenance. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn excluded_scoped_tables_are_live_control_plane_tables() { + const COMMUNITY_SCOPED_CONTROL_PLANE_TABLES: [&str; 6] = [ + "community_deletion_approvals", + "community_deletion_requests", + "community_serving_write_leases", + "operator_listener_outbox", + "product_feedback", + "rate_limit_violations", + ]; + let control_plane = BTreeSet::from(COMMUNITY_SCOPED_CONTROL_PLANE_TABLES); + let excluded = EXCLUDED_SCOPED_TABLES + .iter() + .copied() + .collect::>(); + assert_eq!(excluded, control_plane); + for table in EXPECTED_SCOPED_TABLES.iter().chain(PURGE_SCOPED_TABLES) { + assert!( + !control_plane.contains(table), + "tenant table {table} must not be excluded" + ); + } + + let (db, _) = store().await; + let live: BTreeSet = sqlx::query_scalar( + "SELECT c.relname FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + JOIN pg_attribute a ON a.attrelid = c.oid \ + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') \ + AND NOT c.relispartition AND a.attname = 'community_id' \ + AND NOT a.attisdropped", + ) + .fetch_all(&db.pool) + .await + .expect("community provenance tables") + .into_iter() + .collect(); + for table in COMMUNITY_SCOPED_CONTROL_PLANE_TABLES { + assert!(live.contains(table), "stale exclusion {table}"); + } + let accounted = EXPECTED_SCOPED_TABLES + .iter() + .chain(COMMUNITY_SCOPED_CONTROL_PLANE_TABLES.iter()) + .map(|table| (*table).to_owned()) + .collect::>(); + assert_eq!(live, accounted); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn desired_state_catalog_has_no_universal_fence_and_still_boots() { + let (db, store) = store().await; + store + .validate_serving_catalog() + .await + .expect("serving startup catalog"); + store.validate_catalog().await.expect("deletion catalog"); + let retired_count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname LIKE 'community_write_fence_%'", + ) + .fetch_one(&db.pool) + .await + .expect("count retired triggers"); + assert_eq!(retired_count, 0); + let retired_function: bool = sqlx::query_scalar( + "SELECT to_regprocedure('community_write_allowed(uuid)') IS NOT NULL", + ) + .fetch_one(&db.pool) + .await + .expect("lookup retired function"); + assert!(!retired_function); + let retained: (bool, bool) = sqlx::query_as( + "SELECT to_regprocedure('community_deletion_lock_key(uuid)') IS NOT NULL, \ + EXISTS(SELECT 1 FROM pg_trigger WHERE tgname = 'communities_deletion_tombstone')", + ) + .fetch_one(&db.pool) + .await + .expect("lookup retained guards"); + assert_eq!(retained, (true, true)); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn migration_schema_fence_objects_are_optional_for_serving_and_deletion() { @@ -4665,16 +4695,12 @@ mod postgres_tests { }) .await .expect("connect isolated migration DB"); - crate::migration::run_migrations_through(&db.pool, 66) + // Stop just before the retirement migration so every current table + // exists and the universal fence objects are still present. + crate::migration::run_migrations_through(&db.pool, 89) .await .expect("migrate with fence objects present"); let store = db.deletion_store(); - let legacy_fenced_tables = store.live_fenced_tables().await.expect("legacy fences"); - // Include current tables without requiring new application-admitted - // tables to acquire legacy database fence triggers. - db.migrate() - .await - .expect("migrate current deletion catalog"); let community = db .ensure_configured_community("optional-fences.example") .await @@ -4743,14 +4769,7 @@ DROP FUNCTION community_deletion_lock_key(UUID); store.validate_catalog().await.expect("deletion catalog"); let inventory = store.inventory_schema(community).await.expect("inventory"); assert_eq!(inventory.scoped_tables.len(), EXPECTED_SCOPED_TABLES.len()); - assert_eq!( - inventory.fenced_tables.into_iter().collect::>(), - if objects_present { - legacy_fenced_tables.clone() - } else { - BTreeSet::new() - } - ); + assert!(inventory.fenced_tables.is_empty()); let lease = store .acquire_serving_write_lease( community, @@ -7527,56 +7546,6 @@ DROP FUNCTION community_deletion_lock_key(UUID); .expect("quiesce after writer release"); } - #[tokio::test] - #[ignore = "requires Postgres"] - async fn fence_waits_for_open_write_and_rejects_it_after_transition() { - let (db, store) = store().await; - let (request, _) = inventoried_request(&db, &store).await; - store - .approve(request.id, "approver", None) - .await - .expect("approve"); - let claim = store - .claim_specific(request.id, "executor", DEFAULT_LEASE_DURATION) - .await - .expect("claim") - .expect("won claim"); - - // A raw writer transaction on purpose: this pins that the fenced-table - // trigger itself takes the shared deletion lock, not the chokepoint. - let mut open_write = db.pool.begin().await.expect("open write transaction"); - sqlx::query("INSERT INTO pubkey_allowlist (community_id, pubkey) VALUES ($1, $2)") - .bind(request.community_id.as_uuid()) - .bind(vec![7_u8; 32]) - .execute(&mut *open_write) - .await - .expect("write acquires shared deletion lock"); - - let store_for_fence = store.clone(); - let lease = claim.lease.clone(); - let fencing = tokio::spawn(async move { - store_for_fence.begin_quiescing(&lease).await?; - store_for_fence.fence(&lease).await - }); - tokio::time::sleep(Duration::from_millis(50)).await; - assert!( - !fencing.is_finished(), - "exclusive fence must wait for open writer" - ); - open_write - .commit() - .await - .expect("pre-fence writer commits first"); - fencing.await.expect("fence task").expect("fence completes"); - - assert!( - db.add_to_allowlist(request.community_id, &[8_u8; 32], &[9_u8; 32], None) - .await - .is_err(), - "post-fence serving write must fail" - ); - } - #[tokio::test] #[ignore = "requires Postgres"] async fn deletion_lock_admission_rejects_pinned_snapshot_isolation() { @@ -8708,12 +8677,10 @@ DROP FUNCTION community_deletion_lock_key(UUID); let probe_table = format!("deletion_probe_{}", Uuid::new_v4().simple()); let create_probe = format!("CREATE TABLE {probe_table} (community_id UUID NOT NULL, payload TEXT)"); - let attach_probe = - format!("SELECT attach_community_write_fence('{probe_table}'::regclass)"); let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>(); let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); let migration_pool = db.pool.clone(); - let (create_probe_sql, attach_probe_sql) = (create_probe.clone(), attach_probe.clone()); + let create_probe_sql = create_probe.clone(); let migration_run = tokio::spawn(async move { crate::migration::with_exclusive_schema_destruction_lock( &migration_pool, @@ -8727,9 +8694,6 @@ DROP FUNCTION community_deletion_lock_key(UUID); sqlx::query(AssertSqlSafe(create_probe_sql)) .execute(&mut *ddl) .await?; - sqlx::query(AssertSqlSafe(attach_probe_sql)) - .execute(&mut *ddl) - .await?; ddl.commit().await?; Ok(()) } @@ -8747,7 +8711,7 @@ DROP FUNCTION community_deletion_lock_key(UUID); "purge must wait for the in-flight migration instead of validating a stale surface" ); - // The migration commits its new fenced scoped table, then finishes. + // The migration commits its new scoped table, then finishes. release_tx.send(()).expect("unpark migration"); migration_run .await @@ -8787,10 +8751,6 @@ DROP FUNCTION community_deletion_lock_key(UUID); .execute(&db.pool) .await .expect("recreate probe scoped table"); - sqlx::query(AssertSqlSafe(attach_probe)) - .execute(&db.pool) - .await - .expect("attach probe fence again"); let verify_denied = store.verify_postgres_logically_deleted(&token).await; let verify_denied_on_probe = matches!( &verify_denied, diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index 8c165c7732..4183437c65 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -1687,7 +1687,10 @@ fn count_events_sql(q: &EventQuery) -> QueryBuilder { } // Preserve the public event-store deletion API after the focused extraction. -pub(crate) use super::event_deletion::soft_delete_event_and_update_thread_in_tx; +pub(crate) use super::event_deletion::{ + is_nip_rs_event, remove_coordinate_versions_in_tx, soft_delete_event_and_update_thread_in_tx, + CoordinateRemoval, +}; pub use super::event_deletion::{ soft_delete_by_coordinate, soft_delete_event_and_update_thread, DeletionTarget, }; @@ -2605,7 +2608,7 @@ impl Db { /// /// Counts route on the BOUNDED arm only, never covered: the covered /// arm bounds insert-completeness but not deletion visibility (soft - /// deletes are UPDATEs outside the floor guard), and a count has no + /// deletes are UPDATEs outside the floor check), and a count has no /// downstream per-row re-filter to absorb extra rows — a silently /// inflated number for up to `FENCE_STALENESS` is a different product /// statement than a page briefly showing a deleted row. `Bounded` ties diff --git a/crates/buzz-db/src/store/event_deletion.rs b/crates/buzz-db/src/store/event_deletion.rs index 44f0dfee15..06a0a8d56e 100644 --- a/crates/buzz-db/src/store/event_deletion.rs +++ b/crates/buzz-db/src/store/event_deletion.rs @@ -10,37 +10,88 @@ use crate::{ AdmittedTx, }; +/// SQL predicate over an `events` row for a conforming NIP-RS read-state +/// coordinate: kind 30078, a `read-state:<32 lowercase hex>` d-tag carried by +/// exactly one `d` tag, and exactly one `["t", "read-state"]` tag. +macro_rules! nip_rs_event_predicate { + () => { + "(kind = 30078 \ + AND d_tag ~ '^read-state:[0-9a-f]{32}$' \ + AND (SELECT count(*) \ + FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ + WHERE jsonb_typeof(tag) = 'array' AND tag->0 = '\"d\"'::jsonb) = 1 \ + AND EXISTS (SELECT 1 \ + FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ + WHERE jsonb_typeof(tag) = 'array' AND jsonb_array_length(tag) >= 2 \ + AND jsonb_typeof(tag->1) = 'string' AND tag->>0 = 'd' AND tag->>1 = d_tag) \ + AND (SELECT count(*) \ + FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ + WHERE tag = '[\"t\", \"read-state\"]'::jsonb) = 1)" + }; +} + +/// SQL predicate over an `events` row for a Buzz mesh heartbeat: kind 30003, +/// a `buzz-mesh-member-status:` d-tag, and a tag containing both `k` and +/// `buzz-mesh-status` (jsonb containment, so extra or reordered elements still +/// match). +macro_rules! mesh_status_event_predicate { + () => { + "(kind = 30003 \ + AND d_tag LIKE 'buzz-mesh-member-status:%' \ + AND tags @> '[[\"k\", \"buzz-mesh-status\"]]'::jsonb)" + }; +} + /// SQL predicate over an `events` row for coordinates that carry no /// historical value: NIP-RS read state and Buzz mesh heartbeats. Their /// deletion is physical, including the mention index, so soft-deleted payloads -/// never accumulate. This is exactly the classification used by the migration -/// 0011 / 0019 purge triggers this path replaces. +/// never accumulate. These predicates are the only definition of the class: +/// every removal path decides row by row through +/// [`remove_coordinate_versions_in_tx`] rather than re-implementing them in Rust. macro_rules! retention_free_event_predicate { () => { - "((kind = 30078 \ - AND d_tag ~ '^read-state:[0-9a-f]{32}$' \ - AND (SELECT count(*) \ - FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ - WHERE jsonb_typeof(tag) = 'array' AND tag->0 = '\"d\"'::jsonb) = 1 \ - AND EXISTS (SELECT 1 \ - FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ - WHERE jsonb_typeof(tag) = 'array' AND jsonb_array_length(tag) >= 2 \ - AND jsonb_typeof(tag->1) = 'string' AND tag->>0 = 'd' AND tag->>1 = d_tag) \ - AND (SELECT count(*) \ - FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ - WHERE tag = '[\"t\", \"read-state\"]'::jsonb) = 1) \ - OR (kind = 30003 \ - AND d_tag LIKE 'buzz-mesh-member-status:%' \ - AND tags @> '[[\"k\", \"buzz-mesh-status\"]]'::jsonb))" + concat!( + "(", + nip_rs_event_predicate!(), + " OR ", + mesh_status_event_predicate!(), + ")" + ) }; } /// Kinds that can hold a retention-free coordinate. Cheap Rust gate so -/// ordinary deletions skip the purge statement entirely. +/// ordinary writes skip the classification and purge statements entirely. fn may_be_retention_free(kind: i32) -> bool { kind == 30078 || kind == 30003 } +/// Whether an event that has not been written yet is a conforming NIP-RS +/// read-state coordinate, which advances the stale-write watermark. Uses the +/// same SQL predicate as the purge and delete paths so the two cannot drift. +pub(crate) async fn is_nip_rs_event( + conn: &mut sqlx::PgConnection, + kind: i32, + d_tag: &str, + tags: &serde_json::Value, +) -> Result { + if kind != 30078 { + return Ok(false); + } + let nip_rs: bool = sqlx::query_scalar(concat!( + "SELECT COALESCE(", + nip_rs_event_predicate!(), + ", false) \ + FROM (SELECT $1::integer AS kind, $2::text AS d_tag, $3::jsonb AS tags) event_row" + )) + .bind(kind) + .bind(d_tag) + .bind(tags) + .fetch_one(conn) + .await?; + Ok(nip_rs) +} + /// Soft-delete the live row for an addressable coordinate /// `(kind, pubkey, d_tag)` — the NIP-33 replacement key — provided it is not /// newer than the deletion request. @@ -86,14 +137,55 @@ pub async fn soft_delete_by_coordinate( crate::observability::WriterOperation::EventWrite, ) .await?; + let deleted = remove_coordinate_versions_in_tx( + &mut tx, + kind, + pubkey, + d_tag, + deletion_created_at, + CoordinateRemoval::Deletion, + ) + .await?; + tx.commit().await?; + Ok(deleted) +} + +/// Why [`remove_coordinate_versions_in_tx`] retires a coordinate's versions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CoordinateRemoval { + /// NIP-09 coordinate deletion. Soft-deleted versions keep their mention + /// rows, like every other deletion path. + Deletion, + /// Parameterized replacement. Soft-deleted versions leave with their + /// mention rows, as `superseded_with_mentions_sql!` does for the other + /// replacement paths. + Supersede, +} + +/// Remove every live version of `(kind, pubkey, d_tag)` created at or before +/// `created_at_or_before`, in the caller's transaction. Each row is classified +/// by its own stored shape: retention-free rows are purged physically with +/// their mentions, every other row is soft-deleted. NIP-09 coordinate deletion +/// and parameterized replacement both remove versions through this function. +/// +/// Returns `true` if any row was removed. +pub(crate) async fn remove_coordinate_versions_in_tx( + tx: &mut AdmittedTx, + kind: i32, + pubkey: &[u8], + d_tag: &str, + created_at_or_before: DateTime, + removal: CoordinateRemoval, +) -> Result { + let community_id = tx.community(); let purged = if may_be_retention_free(kind) { purge_retention_free_events( - &mut tx, + tx, RetentionFreeTarget::Coordinate { kind, pubkey, d_tag, - created_at_or_before: deletion_created_at, + created_at_or_before, }, ) .await? @@ -104,26 +196,50 @@ pub async fn soft_delete_by_coordinate( // statement order: under READ COMMITTED this UPDATE takes a fresh snapshot, // so a retention-free head committed by a racing replacement after the // purge ran is spared instead of soft-deleted (the "deletion arrived - // first" outcome documented above). COALESCE keeps a NULL predicate - // (e.g. NULL `d_tag`) on the ordinary soft-delete path, as the triggers do. - let result = sqlx::query(concat!( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ - AND created_at <= $5 AND NOT COALESCE(", - retention_free_event_predicate!(), - ", false)" - )) - .bind(community_id.as_uuid()) - .bind(kind) - .bind(pubkey) - .bind(d_tag) - .bind(deletion_created_at) - .execute(tx.conn()) - .await?; + // first" outcome documented on [`soft_delete_by_coordinate`]). COALESCE + // keeps a NULL predicate (e.g. NULL `d_tag`) on the ordinary soft-delete + // path. + let soft_deleted: i64 = match removal { + CoordinateRemoval::Deletion => sqlx::query(concat!( + "UPDATE events SET deleted_at = NOW() \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ + AND created_at <= $5 AND NOT COALESCE(", + retention_free_event_predicate!(), + ", false)" + )) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey) + .bind(d_tag) + .bind(created_at_or_before) + .execute(tx.conn()) + .await? + .rows_affected() as i64, + CoordinateRemoval::Supersede => { + sqlx::query_scalar(concat!( + "WITH superseded AS ( \ + UPDATE events SET deleted_at = NOW() \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ + AND created_at <= $5 AND NOT COALESCE(", + retention_free_event_predicate!(), + ", false) RETURNING id \ + ), superseded_mentions AS ( \ + DELETE FROM event_mentions mention USING superseded \ + WHERE mention.community_id = $1 AND mention.event_id = superseded.id \ + ) \ + SELECT count(*) FROM superseded" + )) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey) + .bind(d_tag) + .bind(created_at_or_before) + .fetch_one(tx.conn()) + .await? + } + }; - tx.commit().await?; - - Ok(purged > 0 || result.rows_affected() > 0) + Ok(purged > 0 || soft_deleted > 0) } /// Purge live retention-free rows matching `$target`, plus their mention rows, @@ -189,13 +305,6 @@ async fn purge_retention_free_events( target: RetentionFreeTarget<'_>, ) -> Result { let community_id = tx.community(); - // Migration 0011 fences NIP-RS hard deletes behind a transaction-local - // opt-in. The fence and this opt-in are removed together once the - // migration-only triggers are dropped. - sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") - .execute(tx.conn()) - .await?; - let purged: i64 = match target { RetentionFreeTarget::Event { event_id, diff --git a/crates/buzz-db/src/store/event_floor_postgres_tests.rs b/crates/buzz-db/src/store/event_floor_postgres_tests.rs index 24898fa7a1..ba5e1b7aab 100644 --- a/crates/buzz-db/src/store/event_floor_postgres_tests.rs +++ b/crates/buzz-db/src/store/event_floor_postgres_tests.rs @@ -1,4 +1,4 @@ -//! App-floor regressions with every floor-trigger clone disabled in the +//! App-floor regressions with no enabled floor-trigger clone in the //! nextest-provided per-test database, so the DB backstop cannot mask a bypass. use buzz_core::CommunityId; @@ -18,19 +18,14 @@ async fn fixture() -> (Db, CommunityId, Uuid, Keys) { .connect(&crate::test_support::database_url()) .await .expect("isolated test database"); - sqlx::query("ALTER TABLE events DISABLE TRIGGER events_created_at_floor") - .execute(&pool) - .await - .expect("disable floor trigger recursively on the partitioned table"); - let (total, enabled): (i64, i64) = sqlx::query_as( - "SELECT count(*), count(*) FILTER (WHERE tgenabled <> 'D') FROM pg_trigger \ - WHERE tgname = 'events_created_at_floor' \ + let enabled: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_trigger \ + WHERE tgname = 'events_created_at_floor' AND tgenabled <> 'D' \ AND tgrelid IN (SELECT relid FROM pg_partition_tree('events'))", ) .fetch_one(&pool) .await .expect("check every trigger clone"); - assert!(total > 0, "the test must disable an existing backstop"); assert_eq!(enabled, 0, "no partition may mask a missing app check"); let community = CommunityId::from_uuid(Uuid::new_v4()); sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") diff --git a/crates/buzz-db/src/store/push.rs b/crates/buzz-db/src/store/push.rs index 44f693c411..78a1ab3740 100644 --- a/crates/buzz-db/src/store/push.rs +++ b/crates/buzz-db/src/store/push.rs @@ -2669,10 +2669,6 @@ mod postgres_tests { #[ignore = "requires Postgres"] async fn matcher_claim_skips_quiescing_tenant_while_active_bystanders_progress() { let pool = setup_pool().await; - sqlx::query("DELETE FROM push_match_queue") - .execute(&pool) - .await - .expect("drain active matcher queue"); let active_a = make_community(&pool).await; let target = make_community(&pool).await; let active_x = make_community(&pool).await; @@ -2699,10 +2695,6 @@ mod postgres_tests { #[ignore = "requires Postgres"] async fn exhausted_match_reaper_skips_quiescing_tenant_and_reaps_active_bystanders() { let pool = setup_pool().await; - sqlx::query("DELETE FROM push_match_queue") - .execute(&pool) - .await - .expect("drain active matcher queue"); let active_a = make_community(&pool).await; let target = make_community(&pool).await; let active_x = make_community(&pool).await; diff --git a/crates/buzz-db/src/store/relay_invite.rs b/crates/buzz-db/src/store/relay_invite.rs index 327beb32ab..390ecb15c2 100644 --- a/crates/buzz-db/src/store/relay_invite.rs +++ b/crates/buzz-db/src/store/relay_invite.rs @@ -185,9 +185,9 @@ async fn mint( let expires_at = now + chrono::Duration::seconds(ttl_secs as i64); // Mint a v2 opaque invite inside the same lifecycle gate as every other - // community-scoped database write. The trigger remains the final backstop, - // but this typed guard keeps a quiescing community from surfacing as an - // opaque SQLSTATE/HTTP 500 at the API boundary. + // community-scoped database write. The app-side guard is the community + // fence: it holds the shared deletion lock and refuses quiescing writes + // before the insert. let mut tx = crate::begin_community_write_transaction( pool, community, 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 b9cb3bce3e..b74daf6c45 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 @@ -418,10 +418,12 @@ async fn assert_admission_column(pool: &PgPool) { } async fn apply_pgschema_to_existing_database(pool: &PgPool) { - // The pinned migration history has retired triggers on the partitioned - // events parent and auto-named deletion-request checks that the desired - // schema replaces. pgschema orders child-trigger drops before their parent - // and schedules a replacement check before dropping its same-named copy. + // The pinned migration history has retired triggers on partitioned + // parents (events, delivery_log), including the floor trigger 0089 + // drops, and auto-named deletion-request checks that the desired schema + // replaces. pgschema orders child-trigger drops + // before their parent (Postgres refuses with 2BP01) and schedules a + // replacement check before dropping its same-named copy. // Remove only those stale objects in this disposable fixture; pgschema // still applies desired state; historical repair is a separate reviewed // operation after deployment. @@ -430,6 +432,9 @@ async fn apply_pgschema_to_existing_database(pool: &PgPool) { DROP TRIGGER IF EXISTS trg_events_nip_rs_watermark ON events; \ DROP TRIGGER IF EXISTS trg_events_purge_soft_deleted_nip_rs ON events; \ DROP TRIGGER IF EXISTS trg_events_purge_soft_deleted_buzz_mesh_status ON events; \ + DROP TRIGGER IF EXISTS events_created_at_floor ON events; \ + DROP TRIGGER IF EXISTS community_write_fence_events ON events; \ + DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log; \ ALTER TABLE community_deletion_requests \ DROP CONSTRAINT IF EXISTS community_deletion_requests_check1; \ ALTER TABLE community_deletion_requests \ diff --git a/crates/buzz-db/src/store/replaceable.rs b/crates/buzz-db/src/store/replaceable.rs index 36cc4a5d7a..c7ca35e517 100644 --- a/crates/buzz-db/src/store/replaceable.rs +++ b/crates/buzz-db/src/store/replaceable.rs @@ -132,40 +132,8 @@ async fn replace_parameterized_event_in_transaction_impl( ) .await?; - let d_tag_count = event - .tags - .iter() - .filter(|tag| tag.as_slice().first().is_some_and(|part| part == "d")) - .count(); - let has_exact_d_tag = event.tags.iter().any(|tag| { - let parts = tag.as_slice(); - parts.len() >= 2 && parts[0] == "d" && parts[1] == d_tag - }); - let read_state_t_tag_count = event - .tags - .iter() - .filter(|tag| { - let parts = tag.as_slice(); - parts.len() == 2 && parts[0] == "t" && parts[1] == "read-state" - }) - .count(); - let is_nip_rs = kind_i32 == buzz_core::kind::KIND_READ_STATE as i32 - && d_tag_count == 1 - && has_exact_d_tag - && d_tag.strip_prefix("read-state:").is_some_and(|slot| { - slot.len() == 32 - && slot - .bytes() - .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) - }) - && read_state_t_tag_count == 1; - let is_buzz_mesh_status = kind_i32 == buzz_core::kind::KIND_BOOKMARK_SET as i32 - && d_tag.starts_with("buzz-mesh-member-status:") - && event.tags.iter().any(|tag| { - let parts = tag.as_slice(); - parts.len() == 2 && parts[0] == "k" && parts[1] == "buzz-mesh-status" - }); - let hard_delete_superseded = is_nip_rs || is_buzz_mesh_status; + let tags_json = serde_json::to_value(&event.tags)?; + let is_nip_rs = crate::event::is_nip_rs_event(tx.conn(), kind_i32, d_tag, &tags_json).await?; let existing: Option<(DateTime, Vec)> = sqlx::query_as( "SELECT created_at, id FROM events \ @@ -264,46 +232,20 @@ async fn replace_parameterized_event_in_transaction_impl( crate::channel_members::guard_channel_roster_event(tx, kind_i32, channel_id, &tags_json) .await?; if existing.is_some() { - let previous_nip_rs_hard_delete: Option = if is_nip_rs { - sqlx::query_scalar( - "SELECT NULLIF(current_setting('buzz.nip_rs_hard_delete', true), '')", - ) - .fetch_one(tx.conn()) - .await? - } else { - None - }; - if is_nip_rs { - sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") - .execute(tx.conn()) - .await?; - } - let statement = if hard_delete_superseded { - superseded_with_mentions_sql!( - "DELETE FROM events \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" - ) - } else { - superseded_with_mentions_sql!( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" - ) - }; - sqlx::query(statement) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(d_tag) - .execute(tx.conn()) - .await?; - - if is_nip_rs { - let previous_value = previous_nip_rs_hard_delete.as_deref().unwrap_or_default(); - sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', $1, true)") - .bind(previous_value) - .execute(tx.conn()) - .await?; - } + // Every live version is at or before the incoming event (dominance + // was checked above). Each is removed by its own stored shape, so + // a retention-free head superseded by a nonconforming event is + // still purged, and a nonconforming head keeps legacy retention. + // Superseded versions leave with their mention rows. + crate::event::remove_coordinate_versions_in_tx( + tx, + kind_i32, + pubkey_bytes.as_slice(), + d_tag, + created_at, + crate::event::CoordinateRemoval::Supersede, + ) + .await?; } let sig_bytes = event.sig.serialize(); @@ -400,7 +342,9 @@ async fn replace_parameterized_event_in_transaction_impl( )) } -/// The `WHERE` scope of one replaceable coordinate's head read and supersede. +/// The `WHERE` predicate (after the keyword, which each caller spells so the +/// floor policy can see where a `SET` list ends) of one replaceable +/// coordinate's head read and supersede. /// `in_channel` binds the channel as `$4`; `global` binds three parameters. /// /// The channel predicate is spelled per case, never `IS NOT DISTINCT FROM $4`: @@ -410,11 +354,11 @@ async fn replace_parameterized_event_in_transaction_impl( /// write would scan the whole community's. macro_rules! replacement_scope { (in_channel) => { - "WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + "community_id = $1 AND kind = $2 AND pubkey = $3 \ AND channel_id = $4 AND deleted_at IS NULL" }; (global) => { - "WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + "community_id = $1 AND kind = $2 AND pubkey = $3 \ AND channel_id IS NULL AND deleted_at IS NULL" }; } @@ -423,7 +367,7 @@ macro_rules! replacement_scope { macro_rules! replacement_head_sql { ($scope:tt) => { concat!( - "SELECT created_at, id FROM events ", + "SELECT created_at, id FROM events WHERE ", replacement_scope!($scope), " ORDER BY created_at DESC, id ASC LIMIT 1" ) @@ -484,7 +428,7 @@ pub(crate) async fn replace_addressable_event_under_lock( ( replacement_head_sql!(in_channel), superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() ", + "UPDATE events SET deleted_at = NOW() WHERE ", replacement_scope!(in_channel) )), ) @@ -492,7 +436,7 @@ pub(crate) async fn replace_addressable_event_under_lock( ( replacement_head_sql!(global), superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() ", + "UPDATE events SET deleted_at = NOW() WHERE ", replacement_scope!(global) )), ) @@ -775,7 +719,7 @@ mod postgres_tests { use crate::test_support::ScratchDb; use crate::{event, migration, replaceable}; use sqlx::postgres::PgPoolOptions; - use sqlx::{Acquire, PgPool}; + use sqlx::PgPool; use std::time::Duration; const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials @@ -1078,7 +1022,7 @@ mod postgres_tests { true, replacement_head_sql!(in_channel), superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() ", + "UPDATE events SET deleted_at = NOW() WHERE ", replacement_scope!(in_channel) )), ), @@ -1086,7 +1030,7 @@ mod postgres_tests { false, replacement_head_sql!(global), superseded_with_mentions_sql!(concat!( - "UPDATE events SET deleted_at = NOW() ", + "UPDATE events SET deleted_at = NOW() WHERE ", replacement_scope!(global) )), ), @@ -1560,32 +1504,46 @@ mod postgres_tests { .expect("count NIP-RS rows"); assert_eq!(rows, 1, "superseded payload must be physically deleted"); - sqlx::query( - "UPDATE events SET deleted_at=NOW() WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(&d_tag) - .execute(&db.pool) - .await - .expect("simulate NIP-09 coordinate deletion"); - assert!( - !db.replace_parameterized_event(community, &old, &d_tag, None) - .await - .expect("replay old") - .1 + event::soft_delete_by_coordinate( + &db.pool, + community, + i32::from(buzz_core::kind::KIND_READ_STATE as u16), + &keys.public_key().to_bytes(), + &d_tag, + (base + 1) as i64, + ) + .await + .expect("NIP-09 coordinate deletion"), + "coordinate deletion must remove the live head" ); - let live: i64 = sqlx::query_scalar( - "SELECT count(*) FROM events WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3 AND deleted_at IS NULL", + + // Neither the superseded head nor an exact replay of the deleted head + // may come back: the watermark holds the deleted head's (created_at, id). + for (label, replay) in [("old", &old), ("deleted head", &new)] { + assert!( + !db.replace_parameterized_event(community, replay, &d_tag, None) + .await + .expect("replay") + .1, + "replay of {label} must be rejected" + ); + } + let (rows, live): (i64, i64) = sqlx::query_as( + "SELECT count(*), count(*) FILTER (WHERE deleted_at IS NULL) FROM events \ + WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3", ) .bind(community.as_uuid()) .bind(keys.public_key().to_bytes()) .bind(&d_tag) .fetch_one(&db.pool) .await - .expect("count live NIP-RS rows"); - assert_eq!(live, 0, "watermark must block stale resurrection"); + .expect("count NIP-RS rows"); + assert_eq!( + (rows, live), + (0, 0), + "deletion is physical and the watermark blocks resurrection" + ); } #[tokio::test] @@ -1698,90 +1656,6 @@ mod postgres_tests { ); } - #[tokio::test] - #[ignore = "requires Postgres"] - async fn migration_schema_nip_rs_transaction_operation_restores_hard_delete_opt_in() { - use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; - - let db = setup_db().await; - let community = CommunityId::from_uuid(make_community(&db.pool).await); - let keys = Keys::generate(); - let base = Timestamp::now().as_secs(); - let replace_d_tag = format!("read-state:{}", "b".repeat(32)); - let victim_d_tag = format!("read-state:{}", "c".repeat(32)); - let event = |d_tag: &str, content: &str, timestamp: u64| { - EventBuilder::new( - Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), - content, - ) - .tags(vec![ - Tag::parse(["d", d_tag]).expect("d tag"), - Tag::parse(["t", "read-state"]).expect("t tag"), - ]) - .custom_created_at(Timestamp::from(timestamp)) - .sign_with_keys(&keys) - .expect("sign read state") - }; - let old = event(&replace_d_tag, "old", base); - let new = event(&replace_d_tag, "new", base + 1); - let victim = event(&victim_d_tag, "victim", base); - - assert!( - db.replace_parameterized_event(community, &old, &replace_d_tag, None) - .await - .expect("insert old head") - .1 - ); - assert!( - db.replace_parameterized_event(community, &victim, &victim_d_tag, None) - .await - .expect("insert victim head") - .1 - ); - - let mut tx = db - .begin_event_write_transaction(community) - .await - .expect("begin caller transaction"); - let result = db - .replace_parameterized_event_in_transaction( - &mut tx, - &new, - &replace_d_tag, - None, - replaceable::ParameterizedReplacePrecondition::Unconditional, - ) - .await - .expect("replace inside caller transaction"); - assert_eq!( - result.status, - replaceable::ParameterizedReplaceStatus::Inserted - ); - - let leaked: Option = sqlx::query_scalar( - "SELECT NULLIF(current_setting('buzz.nip_rs_hard_delete', true), '')", - ) - .fetch_one(tx.conn()) - .await - .expect("read hard-delete opt-in after replacement"); - assert_ne!(leaked.as_deref(), Some("on")); - - let unauthorized = sqlx::query( - "DELETE FROM events WHERE community_id=$1 AND kind=30078 \ - AND pubkey=$2 AND d_tag=$3 AND deleted_at IS NULL", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(&victim_d_tag) - .execute(tx.conn()) - .await; - assert!( - unauthorized.is_err(), - "replacement opt-in must not authorize later caller SQL" - ); - tx.rollback().await.expect("roll back caller transaction"); - } - #[tokio::test] #[ignore = "requires Postgres"] async fn parameterized_replacement_in_existing_transaction_honors_revision_and_rollback() { @@ -2142,7 +2016,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] - async fn migration_schema_mesh_status_replacement_keeps_one_physical_row() { + async fn mesh_status_replacement_keeps_one_physical_row() { use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; let db = setup_db().await; @@ -2182,31 +2056,6 @@ mod postgres_tests { .await .expect("count mesh status rows"); assert_eq!((rows, live), (1, 1)); - - sqlx::query( - "UPDATE events SET deleted_at=NOW() \ - WHERE community_id=$1 AND kind=30003 AND pubkey=$2 AND d_tag=$3", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(d_tag) - .execute(&db.pool) - .await - .expect("simulate old relay soft delete"); - let rows_after_legacy_delete: i64 = sqlx::query_scalar( - "SELECT count(*) FROM events \ - WHERE community_id=$1 AND kind=30003 AND pubkey=$2 AND d_tag=$3", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(d_tag) - .fetch_one(&db.pool) - .await - .expect("count rows after old relay soft delete"); - assert_eq!( - rows_after_legacy_delete, 0, - "migration trigger must purge soft-deleted mesh status" - ); } #[tokio::test] @@ -2303,168 +2152,139 @@ mod postgres_tests { } } + /// Replacement removes each superseded row by its own stored shape, not by + /// the incoming event's: a conforming read-state head superseded by a + /// nonconforming event is still purged with its mentions, and a + /// nonconforming head superseded by a conforming event keeps legacy + /// retention (a soft-deleted row) but, like every superseded head, loses + /// its mention rows. #[tokio::test] #[ignore = "requires Postgres"] - async fn migration_schema_nip_rs_hard_delete_fence_fails_closed_and_scopes_opt_in_to_transaction( - ) { + async fn mixed_shape_replacement_classifies_each_superseded_row() { use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; let db = setup_db().await; let community = CommunityId::from_uuid(make_community(&db.pool).await); - let keys = Keys::generate(); let base = Timestamp::now().as_secs(); - let conforming_d = format!("read-state:{}", "6".repeat(32)); - let conforming = EventBuilder::new( - Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), - "fenced-conforming", - ) - .tags(vec![ - Tag::parse(["d", conforming_d.as_str()]).expect("d tag"), - Tag::parse(["t", "read-state"]).expect("t tag"), - ]) - .custom_created_at(Timestamp::from(base)) - .sign_with_keys(&keys) - .expect("sign conforming event"); - assert!( - db.replace_parameterized_event(community, &conforming, &conforming_d, None) - .await - .expect("insert conforming event") - .1 - ); - sqlx::query( - "INSERT INTO event_mentions \ - (community_id, pubkey_hex, event_id, event_created_at, event_kind) \ - VALUES ($1, $2, $3, to_timestamp($4), 30078)", - ) - .bind(community.as_uuid()) - .bind("6".repeat(64)) - .bind(conforming.id.as_bytes().as_slice()) - .bind(conforming.created_at.as_secs() as f64) - .execute(&db.pool) - .await - .expect("insert mention"); + let conforming = |d_tag: &str| { + vec![ + Tag::parse(["d", d_tag]).expect("d tag"), + Tag::parse(["t", "read-state"]).expect("t tag"), + ] + }; + let duplicate_t = |d_tag: &str| { + vec![ + Tag::parse(["d", d_tag]).expect("d tag"), + Tag::parse(["t", "read-state"]).expect("first t tag"), + Tag::parse(["t", "read-state"]).expect("second t tag"), + ] + }; - // Model ce10's first destructive statement. RAISE aborts the transaction, - // so its later mention delete and incoming insert can never commit. - let mut old_writer = db.pool.begin().await.expect("begin old-writer tx"); - let rejected = sqlx::query( - "DELETE FROM events WHERE community_id=$1 AND kind=30078 \ - AND pubkey=$2 AND d_tag=$3 AND deleted_at IS NULL", - ) - .bind(community.as_uuid()) - .bind(keys.public_key().to_bytes()) - .bind(&conforming_d) - .execute(&mut *old_writer) - .await; - assert!(rejected.is_err(), "old-writer hard delete must be rejected"); - old_writer.rollback().await.expect("rollback rejected tx"); - let preserved: (i64, i64) = sqlx::query_as( - "SELECT (SELECT count(*) FROM events WHERE community_id=$1 AND id=$2), \ - (SELECT count(*) FROM event_mentions WHERE community_id=$1 AND event_id=$2)", - ) - .bind(community.as_uuid()) - .bind(conforming.id.as_bytes().as_slice()) - .fetch_one(&db.pool) - .await - .expect("count preserved payload and mention"); - assert_eq!(preserved, (1, 1)); + for (case, old_tags, new_tags, expected_old) in [ + ( + "conforming then nonconforming", + conforming as fn(&str) -> Vec, + duplicate_t as fn(&str) -> Vec, + (0, 0, 0), + ), + ( + "nonconforming then conforming", + duplicate_t as fn(&str) -> Vec, + conforming as fn(&str) -> Vec, + (1, 0, 0), + ), + ] { + let keys = Keys::generate(); + let d_tag = format!("read-state:{}", "f".repeat(32)); + let sign = |content: &str, tags: Vec, at: u64| { + EventBuilder::new( + Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), + content, + ) + .tags(tags) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(&keys) + .expect("sign event") + }; + let old = sign("old", old_tags(&d_tag), base); + let new = sign("new", new_tags(&d_tag), base + 1); - let nonconforming_d = format!("read-state:{}", "7".repeat(32)); - let nonconforming = EventBuilder::new( - Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), - "fenced-nonconforming", - ) - .tags(vec![ - Tag::parse(["d", nonconforming_d.as_str()]).expect("first d tag"), - Tag::parse(["d", "other"]).expect("second d tag"), - Tag::parse(["t", "read-state"]).expect("t tag"), - ]) - .custom_created_at(Timestamp::from(base + 1)) - .sign_with_keys(&keys) - .expect("sign nonconforming event"); - assert!( - db.replace_parameterized_event(community, &nonconforming, &nonconforming_d, None,) - .await - .expect("insert nonconforming event") - .1 - ); - let rejected_nonconforming = sqlx::query( - "DELETE FROM events WHERE community_id=$1 AND id=$2 AND created_at=to_timestamp($3)", - ) - .bind(community.as_uuid()) - .bind(nonconforming.id.as_bytes().as_slice()) - .bind(nonconforming.created_at.as_secs() as f64) - .execute(&db.pool) - .await; - assert!( - rejected_nonconforming.is_err(), - "fence must cover a nonconforming OLD row at a regex coordinate" - ); - - let unrelated_d = format!("read-state:{}", "8".repeat(32)); - let unrelated = EventBuilder::new(Kind::Custom(30023), "unrelated") - .tags(vec![Tag::parse(["d", unrelated_d.as_str()]).expect("d tag")]) - .custom_created_at(Timestamp::from(base + 2)) - .sign_with_keys(&keys) - .expect("sign unrelated event"); - assert!( - db.replace_parameterized_event(community, &unrelated, &unrelated_d, None) - .await - .expect("insert unrelated event") - .1 - ); - let unrelated_delete = sqlx::query( - "DELETE FROM events WHERE community_id=$1 AND id=$2 AND created_at=to_timestamp($3)", - ) - .bind(community.as_uuid()) - .bind(unrelated.id.as_bytes().as_slice()) - .bind(unrelated.created_at.as_secs() as f64) - .execute(&db.pool) - .await - .expect("delete unrelated event"); - assert_eq!(unrelated_delete.rows_affected(), 1); - - // Check both transaction exits on one physical session; pool selection - // cannot accidentally hide a leaked session-local authorization value. - let mut conn = db.pool.acquire().await.expect("acquire dedicated session"); - for commit in [true, false] { - let mut tx = conn.begin().await.expect("begin GUC transaction"); - let value: String = - sqlx::query_scalar("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") - .fetch_one(&mut *tx) + assert!( + db.replace_parameterized_event(community, &old, &d_tag, None) .await - .expect("set transaction-local GUC"); - assert_eq!(value, "on"); - if commit { - tx.commit().await.expect("commit GUC transaction"); - } else { - tx.rollback().await.expect("rollback GUC transaction"); - } - let leaked: Option = sqlx::query_scalar( - "SELECT NULLIF(current_setting('buzz.nip_rs_hard_delete', true), '')", + .expect("insert old") + .1, + "{case}: old head stored" + ); + sqlx::query( + "INSERT INTO event_mentions \ + (community_id, pubkey_hex, event_id, event_created_at, channel_id, event_kind) \ + SELECT community_id, $3, id, created_at, NULL, kind \ + FROM events WHERE community_id = $1 AND id = $2", ) - .fetch_one(&mut *conn) + .bind(community.as_uuid()) + .bind(old.id.as_bytes().as_slice()) + .bind("c".repeat(64)) + .execute(&db.pool) .await - .expect("read GUC after transaction"); - assert_ne!(leaked.as_deref(), Some("on")); + .expect("index mention"); + assert!( + db.replace_parameterized_event(community, &new, &d_tag, None) + .await + .expect("replace") + .1, + "{case}: newer head replaces" + ); + + let (rows, live): (i64, i64) = sqlx::query_as( + "SELECT count(*), count(*) FILTER (WHERE deleted_at IS NULL) \ + FROM events WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(old.id.as_bytes().as_slice()) + .fetch_one(&db.pool) + .await + .expect("count old rows"); + let mentions: i64 = sqlx::query_scalar( + "SELECT count(*) FROM event_mentions WHERE community_id=$1 AND event_id=$2", + ) + .bind(community.as_uuid()) + .bind(old.id.as_bytes().as_slice()) + .fetch_one(&db.pool) + .await + .expect("count old mentions"); + assert_eq!( + (rows, live, mentions), + expected_old, + "{case}: superseded row classified by its own shape" + ); + let coordinate_live: i64 = sqlx::query_scalar( + "SELECT count(*) FROM events WHERE community_id=$1 AND kind=30078 \ + AND pubkey=$2 AND d_tag=$3 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(keys.public_key().to_bytes()) + .bind(&d_tag) + .fetch_one(&db.pool) + .await + .expect("count live heads"); + assert_eq!(coordinate_live, 1, "{case}: exactly the newer head is live"); } } - /// NIP-09 deletion of a retention-free coordinate (NIP-RS read state, mesh - /// status) is physical in application code, so it holds on desired-state - /// databases that never installed the migration 0009/0019 purge triggers. - /// Ordinary addressable events, and look-alikes that fail classification, - /// keep the soft-delete contract. + /// NIP-09 deletion and replacement of a retention-free coordinate (NIP-RS + /// read state, mesh status) are physical in application code; no database + /// trigger takes part. Ordinary addressable events, and look-alikes that + /// fail classification, keep the soft-delete contract. Every removal path + /// classifies through the same SQL predicate, so one table pins all three. #[tokio::test] #[ignore = "requires Postgres"] async fn nip09_deletion_purges_retention_free_rows_and_mentions() { assert_nip09_deletion_purges_retention_free_rows_and_mentions(false).await; } - /// The same contract on a migration-built database, where the 0009/0011/ - /// 0019 purge and hard-delete fence triggers are still installed. Each row - /// shape is also soft-deleted the way a pre-0009 writer would, so the - /// table proves the app classification agrees with the triggers. + /// The same contract on a migration-built database, where migration 0091 + /// dropped the 0009/0011/0019 purge and hard-delete fence triggers. #[tokio::test] #[ignore = "requires Postgres"] async fn migration_schema_nip09_deletion_purges_retention_free_rows_and_mentions() { @@ -2478,20 +2298,30 @@ mod postgres_tests { enum Delete { Coordinate, Id, + /// Supersede through `replace_parameterized_event` with a newer + /// event of the same shape at the same coordinate. + Replace, } let db = setup_db().await; - let triggers_installed: bool = sqlx::query_scalar( - "SELECT EXISTS(SELECT 1 FROM pg_trigger \ - WHERE tgname = 'trg_events_purge_soft_deleted_nip_rs')", + let migrated: bool = + sqlx::query_scalar("SELECT to_regclass('_sqlx_migrations') IS NOT NULL") + .fetch_one(&db.pool) + .await + .expect("inspect migration ledger"); + assert_eq!( + migrated, migration, + "schema mode must match the test variant (run through the Postgres wrapper)" + ); + let purge_triggers: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_trigger \ + WHERE tgname IN ('trg_events_purge_soft_deleted_nip_rs', \ + 'trg_events_purge_soft_deleted_buzz_mesh_status')", ) .fetch_one(&db.pool) .await - .expect("inspect purge trigger"); - assert_eq!( - triggers_installed, migration, - "schema mode must match the test variant (run through the Postgres wrapper)" - ); + .expect("inspect purge triggers"); + assert_eq!(purge_triggers, 0, "the app alone classifies and purges"); let community = CommunityId::from_uuid(make_community(&db.pool).await); let nip_rs = buzz_core::kind::KIND_READ_STATE as u16; let mesh = buzz_core::kind::KIND_BOOKMARK_SET as u16; @@ -2577,7 +2407,7 @@ mod postgres_tests { true, ), ( - // Containment semantics (`tags @>`), shared by trigger and app. + // Containment semantics (`tags @>`) of the SQL predicate. "mesh-status k tag with extra element", mesh, mesh_d.clone(), @@ -2680,36 +2510,36 @@ mod postgres_tests { (rows, live, mentions) } }; - let expected = |purged: bool| -> (i64, i64, i64) { - if purged { - (0, 0, 0) - } else { - (1, 0, 1) + // A soft-deleted (non-purged) row keeps its mentions after a NIP-09 + // deletion, but a superseded head leaves with its mention rows. + let expected = |purged: bool, mode: Delete| -> (i64, i64, i64) { + match (purged, mode) { + (true, _) => (0, 0, 0), + (false, Delete::Replace) => (1, 0, 0), + (false, _) => (1, 0, 1), } }; for (label, kind, d_tag, tags, purged) in cases { - if migration { - // Trigger half of the parity table: a pre-0009 writer's plain - // soft delete, classified only by the 0009/0011/0019 triggers. - let (_, id, _) = store(label, kind, d_tag.clone(), tags.clone()).await; - sqlx::query("UPDATE events SET deleted_at = NOW() WHERE community_id=$1 AND id=$2") - .bind(community.as_uuid()) - .bind(&id) - .execute(&db.pool) - .await - .expect("legacy soft delete"); - assert_eq!( - state(id).await, - expected(purged), - "{label}: trigger classification" - ); - } - - for mode in [Delete::Coordinate, Delete::Id] { + for mode in [Delete::Coordinate, Delete::Id, Delete::Replace] { let (keys, id, created_at) = store(label, kind, d_tag.clone(), tags.clone()).await; + let newer = EventBuilder::new(Kind::Custom(kind), format!("{label}-newer")) + .tags( + tags.iter() + .map(|tag| Tag::parse(tag.clone()).expect("tag")) + .collect::>(), + ) + .custom_created_at(Timestamp::from(created_at + 1)) + .sign_with_keys(&keys) + .expect("sign newer event"); let delete = || async { match mode { + Delete::Replace => { + db.replace_parameterized_event(community, &newer, &d_tag, None) + .await + .expect("replace") + .1 + } Delete::Coordinate => event::soft_delete_by_coordinate( &db.pool, community, @@ -2733,7 +2563,7 @@ mod postgres_tests { ); assert_eq!( state(id.clone()).await, - expected(purged), + expected(purged, mode), "{label}/{mode:?}: app classification" ); assert!( @@ -2746,7 +2576,7 @@ mod postgres_tests { // A mesh-status-shaped row whose `d_tag` column was never backfilled: // `kind = 30003 AND NULL LIKE … AND tags @> …` makes the purge // predicate NULL (a read-state row cannot: its tag/column EXISTS is - // false), which the triggers treat as false. The id path must still + // false). The id path must still // soft-delete it (the `COALESCE` in the generic soft delete), not // silently skip it. Coordinate deletes key on `d_tag`, so only the id // path can reach this row. @@ -2766,20 +2596,6 @@ mod postgres_tests { .expect("clear d_tag column"); id }; - if migration { - let id = null_d_tag_row().await; - sqlx::query("UPDATE events SET deleted_at = NOW() WHERE community_id=$1 AND id=$2") - .bind(community.as_uuid()) - .bind(&id) - .execute(&db.pool) - .await - .expect("legacy soft delete"); - assert_eq!( - state(id).await, - expected(false), - "NULL d_tag: trigger classification" - ); - } let id = null_d_tag_row().await; assert!( event::soft_delete_event_and_update_thread(&db.pool, community, &id, None, None) @@ -2789,7 +2605,7 @@ mod postgres_tests { ); assert_eq!( state(id).await, - expected(false), + expected(false, Delete::Id), "NULL d_tag/Id: app classification" ); } @@ -2834,10 +2650,6 @@ mod postgres_tests { // The replacement: insert a newer head (still at or before the // tombstone), hard-delete the old head, and hold the transaction open. let mut replacement = db.pool.begin().await.expect("begin replacement"); - sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") - .execute(&mut *replacement) - .await - .expect("opt in to hard delete"); sqlx::query( "INSERT INTO events \ (community_id, id, pubkey, created_at, kind, tags, content, sig, channel_id, d_tag) \ diff --git a/crates/buzz-db/src/test_support.rs b/crates/buzz-db/src/test_support.rs index b7b80752f7..93a25a0ff8 100644 --- a/crates/buzz-db/src/test_support.rs +++ b/crates/buzz-db/src/test_support.rs @@ -184,8 +184,9 @@ fn drop_cluster_object(admin_url: &str, object: &str, statement: String) { eprintln!("warning: failed to drop {object}: {error}"); } -/// One-session fixture that bypasses ordinary write-fence triggers while -/// retaining application admission. Communities are active, quiescing, fenced. +/// One-session fixture with ordinary triggers disabled, so application +/// admission is the only community write fence it exercises (as it is in +/// production after migration 0090). Communities are active, quiescing, fenced. pub(crate) async fn admission_fixture() -> (crate::Db, [buzz_core::CommunityId; 3]) { use buzz_core::CommunityId; use uuid::Uuid; @@ -222,13 +223,6 @@ pub(crate) async fn admission_fixture() -> (crate::Db, [buzz_core::CommunityId; .await .expect("read replication role"); assert_eq!(role, "replica"); - // A raw write to the fenced tenant proves the DB backstop is bypassed. - sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)") - .bind(communities[2].as_uuid()) - .bind(vec![0xfe_u8; 32]) - .execute(pool) - .await - .expect("raw fenced insert succeeds with triggers disabled"); (db, communities) } @@ -446,7 +440,7 @@ pub(crate) async fn quiesce_community_for_tests( } /// Whether `error` is the community-admission rejection taken at transaction -/// entry, as opposed to a later commit-time trigger rejection. +/// entry, as opposed to a later database constraint rejection. pub(crate) fn is_admission_rejection(error: &crate::DbError) -> bool { matches!(error, crate::DbError::AccessDenied(message) if message.contains("write-fenced (quiescing)")) } diff --git a/crates/buzz-db/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index 022291b8ab..4f720e7382 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -466,22 +466,11 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { let runtime = include_str!("../src/runtime/mod.rs"); assert!(runtime.contains("observability::refresh_pool_waiters(self.read_pool.is_some())")); - assert!(runtime.contains("self.verify_replica_fence_at_boot().await?")); - let fence_boot = runtime - .split_once("pub(crate) async fn verify_replica_fence_at_boot") - .expect("runtime must expose attributed boot fence verification") - .1 - .split_once("/// The pool for lag-tolerant reads") - .expect("boot fence verification must precede routed-read plumbing") - .0; - assert!(fence_boot.contains("WriterOperation::Bootstrap")); - let replica_fence = include_str!("../src/runtime/replica_fence.rs"); let replica_fence_production = replica_fence .split("\n#[cfg(test)]") .next() .expect("replica-fence production source"); - assert!(replica_fence_production.contains("WriterOperation::Bootstrap")); // The heartbeat probe runs on its own pool, never a serving writer // checkout: queued behind request traffic, its beat goes stale exactly // when the writer is saturated. @@ -901,9 +890,6 @@ fn has_any_tenant_local_chokepoint(source: &str) -> bool { const ADMITTED_TX_SIGNATURE_MARKERS: [&str; 2] = ["&mut AdmittedTx", "&mut crate::AdmittedTx"]; -// Narrow reviewed exceptions for non-serving verification probes only. -const GUARDED_WRITE_FUNCTION_EXCEPTIONS: [&str; 1] = ["pub async fn verify_floor_guard_behavior("]; - const GUARDED_TX_ADAPTER_METHOD_PINS: [(&str, &str); 1] = [( "pub async fn replace_member_event(", "pub async fn lock_member_snapshot(", @@ -982,12 +968,6 @@ fn function_header(function_source: &str) -> &str { .trim() } -fn function_is_guarded_write_exception(function_header: &str) -> bool { - GUARDED_WRITE_FUNCTION_EXCEPTIONS - .iter() - .any(|exception| function_header.starts_with(exception)) -} - fn function_accepts_admitted_transaction(function_source: &str) -> bool { let signature = function_source.split('{').next().unwrap_or(function_source); ADMITTED_TX_SIGNATURE_MARKERS @@ -1030,9 +1010,7 @@ fn syntactic_guarded_write_route_violations(production_source: &str) -> Vec bool { fn mask_comments_and_literals(source: &str) -> String { let bytes = source.as_bytes(); let mut masked = bytes.to_vec(); - let mut blank = |from: usize, to: usize| { - for byte in &mut masked[from..to.min(bytes.len())] { + for span in source_spans(source) { + for byte in &mut masked[span.start..span.end] { if *byte != b'\n' { *byte = b' '; } } - }; + } + String::from_utf8(masked).expect("masking replaces whole ASCII-delimited spans") +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SpanKind { + Comment, + /// A plain (`"…"`) string literal; `start` is its opening quote. + Str, + /// A raw string literal; `start` is its `r`, followed by `hashes` `#`s. + RawStr { + hashes: usize, + }, + Char, +} + +struct SourceSpan { + start: usize, + end: usize, + kind: SpanKind, +} + +impl SourceSpan { + /// The text between a string literal's delimiters, escapes left as written. + fn string_body<'a>(&self, source: &'a str) -> Option<&'a str> { + match self.kind { + SpanKind::Str => source.get(self.start + 1..self.end.saturating_sub(1)), + SpanKind::RawStr { hashes } => { + source.get(self.start + 2 + hashes..self.end.saturating_sub(1 + hashes)) + } + SpanKind::Comment | SpanKind::Char => None, + } + } +} + +/// Every comment, string, raw string, and char literal in `source`, in order. +fn source_spans(source: &str) -> Vec { + let bytes = source.as_bytes(); + let mut spans = Vec::new(); let mut index = 0usize; while index < bytes.len() { let start = index; - match bytes[index] { + let kind = match bytes[index] { b'/' if bytes.get(index + 1) == Some(&b'/') => { while index < bytes.len() && bytes[index] != b'\n' { index += 1; } + SpanKind::Comment } b'/' if bytes.get(index + 1) == Some(&b'*') => { let mut depth = 0usize; @@ -1509,6 +1522,7 @@ fn mask_comments_and_literals(source: &str) -> String { index += 1; } } + SpanKind::Comment } b'r' if matches!(bytes.get(index + 1), Some(b'"' | b'#')) && raw_literal_prefix_starts_token(bytes, index) @@ -1530,6 +1544,7 @@ fn mask_comments_and_literals(source: &str) -> String { index = source[body..] .find(&close) .map_or(bytes.len(), |offset| body + offset + close.len()); + SpanKind::RawStr { hashes } } b'"' => { index += 1; @@ -1537,18 +1552,24 @@ fn mask_comments_and_literals(source: &str) -> String { index += if bytes[index] == b'\\' { 2 } else { 1 }; } index += 1; + SpanKind::Str } b'\'' if char_literal_end(source, index).is_some() => { index = char_literal_end(source, index).expect("guard matched"); + SpanKind::Char } _ => { index += 1; continue; } - } - blank(start, index); + }; + spans.push(SourceSpan { + start, + end: index.min(bytes.len()), + kind, + }); } - String::from_utf8(masked).expect("masking replaces whole ASCII-delimited spans") + spans } /// The end (exclusive) of the char literal whose opening quote is at `start`, @@ -1642,19 +1663,29 @@ fn normalized_sql(source: &str) -> String { normalized } -/// The normalized SQL that follows each `INSERT INTO events` in `source`. +/// Whether an unqualified table name is `events` or one of its partitions +/// (`events_p_past`, `events_p2026_01`, …): a direct partition write skips +/// nothing the parent's writers must do. +fn is_events_table(table: &str) -> bool { + table == "events" + || table + .strip_prefix("events_p") + .is_some_and(|rest| rest.starts_with(|ch: char| ch == '_' || ch.is_ascii_digit())) +} + +/// The normalized SQL that follows each `INSERT INTO events` (or one of its +/// partitions) in `source`. fn events_insert_tails(source: &str) -> Vec { let normalized = normalized_sql(source); let mut tails = Vec::new(); for marker in ["insert into events", "insert into public.events"] { for (index, marker) in normalized.match_indices(marker) { - let tail = &normalized[index + marker.len()..]; - if tail - .chars() - .next() - .is_none_or(|next| !(next.is_ascii_alphanumeric() || next == '_')) - { - tails.push(tail.to_owned()); + let table_start = index + marker.len() - "events".len(); + let table_len = normalized[table_start..] + .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) + .unwrap_or(normalized.len() - table_start); + if is_events_table(&normalized[table_start..table_start + table_len]) { + tails.push(normalized[table_start + table_len..].to_owned()); } } } @@ -1677,12 +1708,7 @@ fn event_insert_follow_up_violations(production_source: &str) -> Vec { function_slices(production_source) .into_iter() .filter(|function_source| { - let header = function_header(function_source); - inserts_events_row(function_source) - && !EVENT_INSERT_FOLLOW_UP_EXCEPTIONS - .iter() - .any(|exception| header.starts_with(exception)) - && !runs_event_follow_ups(function_source) + inserts_events_row(function_source) && !runs_event_follow_ups(function_source) }) .map(|function_source| function_header(function_source).to_owned()) .collect() @@ -1735,12 +1761,6 @@ pub(crate) async fn mention_writer(tx: &mut AdmittedTx) { .await .expect("write"); } -pub async fn verify_floor_guard_behavior(pool: &PgPool) { - sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") - .execute(pool) - .await - .expect("probe"); -} pub(crate) async fn lowercase_writer(tx: &mut AdmittedTx) { sqlx::query("insert into public.events (community_id, id) VALUES ($1, $2)") @@ -2002,17 +2022,14 @@ fn event_insert_hook_inventory_carries_the_insert_timestamp() { assert_eq!(actual, expected); } -// Fixed channel-less kinds cannot be channel rosters, and the replica-floor -// startup probe rolls back all its writes. +// Fixed channel-less kinds cannot be channel rosters. // Exemptions match by function header, so a kind 39002 insert added inside one // of these functions would pass the policy; keep them single-purpose. -const EVENT_INSERT_ROSTER_GUARD_EXCEPTIONS: [&str; 3] = [ +const EVENT_INSERT_ROSTER_GUARD_EXCEPTIONS: [&str; 2] = [ // NIP-43 membership is kind 13534 with channel_id NULL. "pub(crate) async fn write_nip43_membership_snapshot(", // Push leases are kind 30350 with channel_id NULL. "pub async fn accept_lease_event(", - // Rolled-back replica-floor startup probe. - "pub async fn verify_floor_guard_behavior(", ]; fn event_insert_roster_guard_violations(production_source: &str) -> Vec { @@ -2064,9 +2081,6 @@ pub(crate) async fn write_nip43_membership_snapshot(tx: &mut AdmittedTx) { pub async fn accept_lease_event(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } -pub async fn verify_floor_guard_behavior(pool: &PgPool) { - sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); -} #[cfg(test)] mod tests { fn fixture() { @@ -2110,16 +2124,13 @@ fn every_production_event_insert_runs_the_roster_guard() { violations.is_empty(), "production `INSERT INTO events` writers must run the app-side roster guard: {violations:?}" ); - // Five guarded writers plus the three explicitly exempt writers/probes. + // Five guarded writers plus the two explicitly exempt writers. assert!( - checked_writers >= 8, - "expected at least eight event writers, found {checked_writers}" + checked_writers >= 7, + "expected at least seven event writers, found {checked_writers}" ); } -// The rolled-back replica-floor probe writes a kind 9 row, which has no `d`. -const EVENT_INSERT_D_TAG_EXCEPTIONS: [&str; 1] = ["pub async fn verify_floor_guard_behavior("]; - /// Whether an `INSERT INTO events` tail names `d_tag` in an explicit column /// list. An insert without a column list does not count. fn events_insert_names_d_tag(tail: &str) -> bool { @@ -2133,13 +2144,9 @@ fn event_insert_d_tag_violations(production_source: &str) -> Vec { function_slices(production_source) .into_iter() .filter(|function_source| { - let header = function_header(function_source); - !EVENT_INSERT_D_TAG_EXCEPTIONS + !events_insert_tails(function_source) .iter() - .any(|exception| header.starts_with(exception)) - && !events_insert_tails(function_source) - .iter() - .all(|tail| events_insert_names_d_tag(tail)) + .all(|tail| events_insert_names_d_tag(tail)) }) .map(|function_source| function_header(function_source).to_owned()) .collect() @@ -2174,9 +2181,6 @@ pub(crate) async fn second_insert_without_d_tag(tx: &mut AdmittedTx) { pub(crate) async fn mention_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO event_mentions (community_id, event_id) VALUES ($1, $2)"); } -pub async fn verify_floor_guard_behavior(pool: &PgPool) { - sqlx::query("INSERT INTO events (community_id, id, kind) VALUES ($1, $2, 9)"); -} #[cfg(test)] mod tests { fn fixture() { @@ -2233,8 +2237,8 @@ fn every_production_event_insert_names_d_tag() { // The same writer set as the roster-guard scan. A lower count means the // scan stopped seeing a writer, not that one was removed safely. assert!( - checked_writers >= 8, - "expected at least eight event writers, found {checked_writers}" + checked_writers >= 7, + "expected at least seven event writers, found {checked_writers}" ); } @@ -2270,13 +2274,8 @@ fn every_search_hydrator_preserves_the_exact_hit_timestamp() { } } -// These startup probes always roll back; they deliberately exercise the DB -// backstops rather than the app check. The two serving writers are exempt only -// while their INSERT remains structurally channel-NULL (checked below). -const EVENT_FLOOR_PROBE_EXCEPTIONS: [&str; 2] = [ - "pub async fn verify_floor_guard_behavior(", - "pub async fn verify_channel_roster_fence_behavior(", -]; +// The two serving channel-NULL writers are exempt only while their INSERT +// remains structurally channel-NULL (checked below). fn is_channel_null_event_writer(function: &str) -> bool { let header = function_header(function); @@ -2292,29 +2291,66 @@ fn is_channel_null_event_writer(function: &str) -> bool { false } -fn updates_event_floor_columns(function: &str) -> bool { - let normalized = normalized_sql(function); - normalized.match_indices("update ").any(|(index, marker)| { - let Some((target, assignments)) = normalized[index + marker.len()..].split_once(" set ") - else { - return false; - }; - let mut target = target.split_whitespace(); - let mut table = target.next(); - if table == Some("only") { - table = target.next(); +/// The assignments of a `SET` list, and whether this literal ends them: the +/// list stops at the first `WHERE` or (for an upsert with no `WHERE`) +/// `RETURNING` outside parentheses, so a subquery's `WHERE` does not hide +/// the assignments after it. +fn set_list(assignments: &str) -> (&str, bool) { + let mut depth = 0usize; + for (index, ch) in assignments.char_indices() { + match ch { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + ' ' if depth == 0 => { + let rest = &assignments[index..]; + if rest.starts_with(" where ") || rest.starts_with(" returning ") { + return (&assignments[..index], true); + } + } + _ => {} } - if !matches!(table, Some("events" | "public.events")) { - return false; - } - // The target may have an alias, with or without AS. - let alias = target.collect::>(); - if !matches!(alias.as_slice(), [] | [_] | ["as", _]) { - return false; - } - let assignments = assignments.split(" where ").next().expect("first part"); - let mut depth = 0usize; - assignments + } + (assignments, false) +} + +/// Whether a `SET` list assigns `created_at` or `channel_id`, including the +/// row form `(a, b) = (...)`, or a column it cannot read (a `{…}` +/// placeholder). +fn assigns_event_floor_column(assignments: &str) -> bool { + let (assignments, _) = set_list(assignments); + let mut depth = 0usize; + assignments + .split(|ch| { + match ch { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + _ => {} + } + ch == ',' && depth == 0 + }) + .any(|assignment| { + assignment.split_once('=').is_some_and(|(columns, _)| { + columns + .trim() + .trim_start_matches('(') + .trim_end_matches(')') + .split(',') + .map(str::trim) + .any(|column| { + matches!(column, "created_at" | "channel_id") || column.starts_with('{') + }) + }) + }) +} + +/// Whether a `SET` list (see [`set_list`]) is missing from its literal: +/// empty, or holding an item with no `=`, such as a `{…}` placeholder or a +/// column whose value follows in another literal. +fn set_list_is_unreadable(assignments: &str) -> bool { + let (assignments, _) = set_list(assignments); + let mut depth = 0usize; + assignments.trim().is_empty() + || assignments .split(|ch| { match ch { '(' => depth += 1, @@ -2323,30 +2359,399 @@ fn updates_event_floor_columns(function: &str) -> bool { } ch == ',' && depth == 0 }) - .any(|assignment| { - assignment.split_once('=').is_some_and(|(columns, _)| { - columns - .trim() - .trim_start_matches('(') - .trim_end_matches(')') - .split(',') - .any(|column| matches!(column.trim(), "created_at" | "channel_id")) - }) - }) - }) + .any(|assignment| !assignment.contains('=')) } -fn event_floor_policy_violations(production: &str) -> Vec { - function_slices(production) - .into_iter() - .filter(|function| { - let header = function_header(function); - if EVENT_FLOOR_PROBE_EXCEPTIONS - .iter() - .any(|exception| header.starts_with(exception)) +/// The table a write targets, without its schema (a literal or a `{…}` +/// placeholder; any schema may hold an `events` table). +fn unqualified_table(target: &str) -> &str { + target.rsplit_once('.').map_or(target, |(_, table)| table) +} + +/// The table the last `INSERT INTO` in `sql` (normalized) targets, without +/// its schema. +fn last_insert_target(sql: &str) -> Option<&str> { + let index = sql.rfind("insert into ")?; + let target = sql[index + "insert into ".len()..] + .split(|ch: char| !(ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '{' | '}'))) + .next()?; + Some(unqualified_table(target)) +} + +/// Whether one SQL literal (normalized) assigns a floor column through a +/// direct `UPDATE` of `events`, or of a target it does not spell: a +/// placeholder, or a `SET` list whose `UPDATE` lies in another literal. +/// A `SET` list it cannot read counts as assigning one, and so does an +/// `UPDATE` list that runs to the end of the literal, since a later literal +/// (a `QueryBuilder` push) may continue it. An events upsert list that runs +/// to the end is read on through `later`, the function's later literals. +/// `prior_insert` is the target of the last `INSERT` in an earlier literal +/// of the same function, which an upsert continued here belongs to. +fn literal_updates_event_floor_columns(sql: &str, prior_insert: Option<&str>, later: &str) -> bool { + // `SET(` with no space is still a row assignment. + let sql = format!(" {} ", sql.trim()).replace(" set(", " set ("); + sql.match_indices(" set ").any(|(index, marker)| { + let (assignments, terminated) = set_list(&sql[index + marker.len()..]); + // A SET list continued in another literal or argument cannot be read. + let unreadable = set_list_is_unreadable(assignments); + let assigns = !unreadable && assigns_event_floor_column(assignments); + let before = &sql[..index]; + if before.ends_with(" do update") { + // The upsert check resolves a readable, complete list's INSERT, + // which may be in another literal of the same builder. An open + // events (or unresolved) upsert list is read on through the + // later literals, where a push may append a floor column. + if unreadable { + return true; + } + if terminated + || !last_insert_target(before) + .or(prior_insert) + .is_none_or(is_events_table) { return false; } + let continued = format!("{assignments} {later}"); + return set_list_is_unreadable(&continued) || assigns_event_floor_column(&continued); + } + if !unreadable && !assigns && terminated { + return false; + } + let Some(update) = before.rfind(" update ") else { + // A bare SET (Redis `SET`, prose) is not SQL unless it assigns. + return assigns; + }; + let mut target = before[update + " update ".len()..].split_whitespace(); + let mut table = target.next(); + if table == Some("only") { + table = target.next(); + } + // The target may have an alias, with or without AS. + let alias = target.collect::>(); + let (Some(table), [] | [_] | ["as", _]) = (table, alias.as_slice()) else { + // An unreadable target is a violation only when it assigns a + // floor column; prose ("update … is set") assigns nothing. + return assigns; + }; + let table = unqualified_table(table); + is_events_table(table) || table.contains('{') + }) +} + +fn updates_event_floor_columns(function: &str) -> bool { + let literals = source_spans(function) + .iter() + .filter_map(|span| span.string_body(function)) + .map(normalized_sql) + .collect::>(); + let direct_update = literals.iter().enumerate().any(|(index, sql)| { + let prior_insert = literals[..index] + .iter() + .rev() + .find_map(|earlier| last_insert_target(earlier)); + literal_updates_event_floor_columns(sql, prior_insert, &literals[index + 1..].join(" ")) + }); + // `ON CONFLICT ... DO UPDATE SET` names no table: it updates the target of + // the INSERT it belongs to, so an events upsert can re-home an existing row. + let normalized = normalized_sql(function).replace(" set(", " set ("); + let events_upsert = normalized + .match_indices("do update set ") + .any(|(index, marker)| { + last_insert_target(&normalized[..index]).is_some_and(is_events_table) + && assigns_event_floor_column(&normalized[index + marker.len()..]) + }); + direct_update || events_upsert +} + +/// Writes one SQL literal (normalized) hides from the per-function checks: +/// an INSERT whose target or tail is not literal, `events` written by a +/// statement other than INSERT, or a PREPARE. +fn literal_sql_violations(sql: &str) -> Vec<&'static str> { + let sql = format!(" {} ", sql.trim()); + let mut violations = Vec::new(); + for (index, _) in sql.match_indices(" into ") { + let rest = &sql[index + " into ".len()..]; + let target = rest.split([' ', '(']).next().expect("first part"); + let table = unqualified_table(target); + if sql[..index].ends_with(" insert") { + if target.is_empty() || table.contains('{') { + violations.push("INSERT target is not a literal table"); + } else if is_events_table(table) && rest.contains('{') { + violations.push("events INSERT with a non-literal part"); + } + } else if is_events_table(table) { + violations.push("events written by a statement other than INSERT"); + } + } + if sql.match_indices(" copy ").any(|(index, marker)| { + let target = sql[index + marker.len()..].split([' ', '(']).next(); + target.is_some_and(|target| is_events_table(unqualified_table(target))) + }) { + violations.push("events written by a statement other than INSERT"); + } + let words = sql.split_whitespace().collect::>(); + if words + .windows(2) + .any(|pair| pair[0] == "prepare" && (pair[1] == "transaction" || pair[1].starts_with('{'))) + || words.last() == Some(&"prepare") + { + violations.push("PREPARE TRANSACTION in a production writer"); + } + violations +} + +/// The offset of the delimiter that closes the bracket opened at `open` in +/// `masked` (comments and literals already blanked). +fn matching_close(masked: &str, open: usize) -> Option { + let mut depth = 0usize; + for (index, byte) in masked.bytes().enumerate().skip(open) { + match byte { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + return Some(index); + } + } + _ => {} + } + } + None +} + +/// `text` as a plain Rust string literal. +fn plain_literal(text: &str) -> String { + format!("\"{}\"", plain_body(text)) +} + +/// Raw `text` escaped as the body of a plain string literal. +fn plain_body(text: &str) -> String { + text.replace('\\', "\\\\").replace('"', "\\\"") +} + +/// A string literal's body, as written in a plain (escaped) literal. +fn plain_string_body(span: &SourceSpan, source: &str) -> Option { + let body = span.string_body(source)?; + Some(if matches!(span.kind, SpanKind::Str) { + body.to_owned() + } else { + plain_body(body) + }) +} + +/// The string literal that is the whole of `arg`, if it is one. +fn sole_string_literal(arg: &str) -> Option { + let trimmed = arg.trim(); + let offset = arg.len() - arg.trim_start().len(); + let mut spans = source_spans(trimmed).into_iter(); + let span = spans.next()?; + (spans.next().is_none() + && span.start == 0 + && span.end == trimmed.len() + && matches!(span.kind, SpanKind::Str | SpanKind::RawStr { .. })) + .then_some(SourceSpan { + start: span.start + offset, + end: span.end + offset, + kind: span.kind, + }) +} + +/// The opening delimiter of each `name!` macro call in `masked` (comments +/// and literals blanked), last first, with any path prefix (`::core::`) and +/// any of `(`, `[` or `{`: `(start of name, delimiter offset)`. +fn macro_calls(masked: &str, name: &str) -> Vec<(usize, usize)> { + let mut calls = masked + .match_indices(name) + .filter_map(|(at, _)| { + let starts_token = !masked[..at] + .chars() + .next_back() + .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); + let after = masked[at + name.len()..].strip_prefix('!')?; + let open = at + name.len() + 1 + (after.len() - after.trim_start().len()); + (starts_token && matches!(masked.as_bytes().get(open), Some(b'(' | b'[' | b'{'))) + .then_some((at, open)) + }) + .collect::>(); + calls.reverse(); + calls +} + +/// Bring SQL that per-function literal scans cannot see into view, so the +/// floor policy fails closed on it now that no trigger backs it up: each +/// `include_str!("…")` becomes one literal holding the included file +/// (resolved against `path`), and each `concat!` becomes one literal of its +/// arguments, with `{opaque}` standing in for any non-literal argument. The +/// SQL checks treat a placeholder in a write target or a `SET` column as +/// unattributable. An `include_str!` whose path is not one literal or +/// cannot be read is a violation, as is any `query_file` macro. +fn sql_visible_source(path: &std::path::Path, source: &str) -> (String, Vec) { + let mut violations = Vec::new(); + let mut text = source.to_owned(); + for (macro_name, expand_include) in [("include_str", true), ("concat", false)] { + // Last occurrence first: a rewrite never moves an earlier offset, and + // an inner `concat!` is joined before the one around it. + loop { + let masked = mask_comments_and_literals(&text); + let Some(&(at, open)) = macro_calls(&masked, macro_name).first() else { + break; + }; + let Some(close) = matching_close(&masked, open) else { + violations.push(format!("{macro_name}!…) is unterminated")); + break; + }; + let args = &text[open + 1..close]; + let replacement = if expand_include { + let included = sole_string_literal(args) + .and_then(|span| span.string_body(args).map(str::to_owned)) + .and_then(|relative| { + let resolved = path.parent()?.join(&relative); + std::fs::read_to_string(resolved).ok() + }); + match included { + Some(contents) => plain_literal(&contents), + None => { + violations.push(format!("include_str!({}) is opaque", args.trim())); + plain_literal("") + } + } + } else { + let masked_args = &masked[open + 1..close]; + let mut joined = String::new(); + let mut depth = 0usize; + let mut arg_start = 0usize; + for (index, byte) in masked_args.bytes().chain(std::iter::once(b',')).enumerate() { + match byte { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + b',' if depth == 0 => { + let arg = &args[arg_start..index.min(args.len())]; + arg_start = index + 1; + if arg.trim().is_empty() { + continue; + } + match sole_string_literal(arg) + .and_then(|span| plain_string_body(&span, arg)) + { + Some(body) => joined.push_str(&body), + None => joined.push_str("{opaque}"), + } + } + _ => {} + } + } + format!("\"{joined}\"") + }; + text.replace_range(at..=close, &replacement); + } + } + // sqlx's `query_file*!` macros load SQL from a file at compile time; + // nothing uses them, so ban them rather than resolve them. + let masked = mask_comments_and_literals(&text); + for (at, _) in masked.match_indices("query_file") { + let starts_token = !masked[..at] + .chars() + .next_back() + .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); + let name_len = masked[at..] + .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) + .unwrap_or(masked.len() - at); + if starts_token && masked[at + name_len..].trim_start().starts_with('!') { + violations.push(format!( + "{}! loads SQL from a file", + &masked[at..at + name_len] + )); + } + } + (text, violations) +} + +/// Length of the function item that starts `masked_function` (comments and +/// literals blanked): through the `}` closing its body, or through the `;` of +/// a bodiless declaration. Unlike [`cfg_test_item_len`], a `;` inside the +/// signature's parentheses or brackets (`[u8; 4]`) does not end it. Without a +/// body the whole input counts, so an unrecognized shape never hides SQL. +fn function_item_len(masked_function: &str) -> usize { + let mut nesting = 0usize; + for (index, byte) in masked_function.bytes().enumerate() { + match byte { + b'(' | b'[' => nesting += 1, + b')' | b']' => nesting = nesting.saturating_sub(1), + b';' if nesting == 0 => return index + 1, + b'{' if nesting == 0 => { + return matching_close(masked_function, index) + .map_or(masked_function.len(), |close| close + 1); + } + _ => {} + } + } + masked_function.len() +} + +/// Each function slice cut to the function's own item, so a const or static +/// after its body is not attributed to it (see [`item_level_literals`]). +fn function_items(production: &str) -> Vec<&str> { + function_slices(production) + .into_iter() + .map(|function| &function[..function_item_len(&mask_comments_and_literals(function))]) + .collect() +} + +/// String literals outside every function body (consts, statics and macro +/// bodies), as plain literals one per line. A function's floor guard cannot +/// be attributed to SQL there. +fn item_level_literals(production: &str) -> String { + let base = production.as_ptr() as usize; + let functions: Vec<(usize, usize)> = function_items(production) + .into_iter() + .map(|function| { + let start = function.as_ptr() as usize - base; + (start, start + function.len()) + }) + .collect(); + let mut literals = String::new(); + for span in source_spans(production) { + if functions + .iter() + .any(|(start, end)| *start <= span.start && span.end <= *end) + { + continue; + } + if let Some(body) = plain_string_body(&span, production) { + literals.push_str(&format!("\"{body}\"\n")); + } + } + literals +} + +/// Every floor-policy violation in one production file, after +/// [`sql_visible_source`] has exposed included and concatenated SQL. +fn file_event_floor_policy_violations(path: &std::path::Path, source: &str) -> Vec { + let (production, mut violations) = sql_visible_source(path, &strip_cfg_test_items(source)); + // The fence cannot bound a prepared transaction's rows without the + // retired trigger (see `replica_fence::sample_writer`), so no supported + // writer may prepare one. + for span in source_spans(&production) { + if let Some(body) = span.string_body(&production) { + for violation in literal_sql_violations(&normalized_sql(body)) { + if !violations.iter().any(|seen| seen == violation) { + violations.push(violation.to_owned()); + } + } + } + } + let item_level = item_level_literals(&production); + if inserts_events_row(&item_level) || updates_event_floor_columns(&item_level) { + violations.push("event-write SQL outside any function body".to_owned()); + } + violations.extend(event_floor_policy_violations(&production)); + violations +} + +fn event_floor_policy_violations(production: &str) -> Vec { + function_items(production) + .into_iter() + .filter(|function| { updates_event_floor_columns(function) || (inserts_events_row(function) && !is_channel_null_event_writer(function) @@ -2407,6 +2812,77 @@ async fn quoted_schema_update(tx: &mut AdmittedTx) { async fn delete_only(tx: &mut AdmittedTx) { sqlx::query("UPDATE events SET deleted_at=now() WHERE channel_id=$1 AND created_at<$2"); } +async fn row_time_no_space(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET(created_at,kind)=($1,1) WHERE id=$2"); +} +async fn guarded_upsert_rehome(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events (id, channel_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET channel_id = EXCLUDED.channel_id"); +} +async fn guarded_upsert_row_time(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET(kind, created_at) = (1, $2)"); +} +async fn guarded_upsert_rehome_returning(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events (id, channel_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET channel_id = EXCLUDED.channel_id RETURNING id, kind"); +} +async fn guarded_upsert_other_column(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET tags = EXCLUDED.tags"); +} +async fn guarded_upsert_do_nothing(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO NOTHING"); +} +async fn guarded_insert_then_other_table_upsert(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT DO NOTHING"); + sqlx::query("INSERT INTO parameterized_event_watermarks (d_tag, created_at) VALUES ($1, $2) ON CONFLICT (d_tag) DO UPDATE SET created_at = EXCLUDED.created_at"); +} +async fn other_table_upsert_returning(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO channel_members (pubkey, role) VALUES ($1, $2) ON CONFLICT (pubkey) DO UPDATE SET removed_at = NULL, role = EXCLUDED.role RETURNING pubkey, role, removed_at"); +} +async fn subquery_where_then_channel(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET tags = (SELECT tags FROM events e2 WHERE e2.id = $1), channel_id = $2 WHERE id = $3"); +} +async fn subquery_where_only(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET tags = (SELECT tags FROM events e2 WHERE e2.id = $1) WHERE id = $2"); +} +async fn guarded_upsert_subquery_then_rehome(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET content = (SELECT content FROM events e2 WHERE e2.id = $1), channel_id = EXCLUDED.channel_id"); +} +async fn builder_continues_set_list(tx: &mut AdmittedTx) { + QueryBuilder::new("UPDATE events SET tags = ").push_bind(t).push(", created_at = ").push_bind(c).push(" WHERE id = ").push_bind(id); +} +async fn builder_other_table_open_set_list(tx: &mut AdmittedTx) { + QueryBuilder::new("UPDATE channels SET name = ").push_bind(n).push(" WHERE id = ").push_bind(id); +} +async fn guarded_builder_upsert_continues_set_list(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + QueryBuilder::new("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET tags = EXCLUDED.tags").push(", channel_id = EXCLUDED.channel_id"); +} +async fn guarded_builder_upsert_continues_other_column(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + QueryBuilder::new("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET tags = EXCLUDED.tags").push(", kind = EXCLUDED.kind"); +} +async fn partition_update(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events_p_past SET created_at = $1 WHERE id = $2"); +} +async fn partition_insert(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO events_p_past (id) VALUES ($1)"); +} +async fn public_partition_insert(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO public.events_p2026_01 (id) VALUES ($1)"); +} +async fn guarded_partition_upsert_rehome(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO events_p_future (id, channel_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET channel_id = EXCLUDED.channel_id"); +} +async fn events_prefixed_table(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events_per_domain SET created_at = $1 WHERE id = $2"); +} "#; assert_eq!( event_floor_policy_violations(source), @@ -2424,6 +2900,18 @@ async fn delete_only(tx: &mut AdmittedTx) { "async fn quoted_schema_insert(tx: &mut AdmittedTx) {", "async fn quoted_update(tx: &mut AdmittedTx) {", "async fn quoted_schema_update(tx: &mut AdmittedTx) {", + "async fn row_time_no_space(tx: &mut AdmittedTx) {", + "async fn guarded_upsert_rehome(tx: &mut AdmittedTx) {", + "async fn guarded_upsert_row_time(tx: &mut AdmittedTx) {", + "async fn guarded_upsert_rehome_returning(tx: &mut AdmittedTx) {", + "async fn subquery_where_then_channel(tx: &mut AdmittedTx) {", + "async fn guarded_upsert_subquery_then_rehome(tx: &mut AdmittedTx) {", + "async fn builder_continues_set_list(tx: &mut AdmittedTx) {", + "async fn guarded_builder_upsert_continues_set_list(tx: &mut AdmittedTx) {", + "async fn partition_update(tx: &mut AdmittedTx) {", + "async fn partition_insert(tx: &mut AdmittedTx) {", + "async fn public_partition_insert(tx: &mut AdmittedTx) {", + "async fn guarded_partition_upsert_rehome(tx: &mut AdmittedTx) {", ] ); } @@ -2447,6 +2935,194 @@ pub(crate) async fn write_nip43_membership_snapshot(tx: &mut AdmittedTx) { ); } +#[test] +fn event_floor_policy_fails_closed_on_sql_it_cannot_attribute() { + let dir = std::env::temp_dir().join(format!("buzz-floor-policy-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).expect("fixture dir"); + std::fs::write( + dir.join("insert_event.sql"), + "INSERT INTO \"events\" (id) VALUES ($1)", + ) + .expect("sql fixture"); + std::fs::write(dir.join("notes.md"), "Prose that quotes nothing.").expect("md fixture"); + let path = dir.join("writer.rs"); + let source = r##" +const LEADING_INSERT: &str = "INSERT INTO events (id) VALUES ($1)"; +const USER_AGENT: &str = concat!("buzz-agent/", env!("CARGO_PKG_VERSION")); +static NOTES: &str = include_str!("notes.md"); +async fn joined_insert(tx: &mut AdmittedTx) { + sqlx::query(concat!("INSERT INTO ", "events (id) VALUES ($1)")); +} +async fn guarded_joined_insert(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query(concat!("INSERT INTO ", r#"events"#, " (id) VALUES ($1)")); +} +const TRAILING_REWRITE: &str = "UPDATE events SET created_at = $1 WHERE id = $2"; +async fn joined_rewrite(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query(concat!("UPDATE events ", "SET created_at = $1 WHERE id = $2")); +} +async fn included_insert(tx: &mut AdmittedTx) { + sqlx::query(include_str!("insert_event.sql")); +} +async fn guarded_included_insert(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query(include_str!("insert_event.sql")); +} +async fn opaque_include(tx: &mut AdmittedTx) { + sqlx::query(include_str!(concat!(env!("OUT_DIR"), "/insert.sql"))); +} +async fn opaque_concat(tx: &mut AdmittedTx) { + sqlx::query(concat!("INSERT INTO ", env!("EVENTS_TABLE"))); +} +async fn two_phase(tx: &mut AdmittedTx) { + sqlx::query("PREPARE TRANSACTION 'fence'"); +} +"##; + let violations = file_event_floor_policy_violations(&path, source); + + // One writer per shape: the SQL is split, assembled, loaded or spelled so + // the per-literal checks cannot read it whole. + const WRITER: &str = "async fn writer(tx: &mut AdmittedTx) {"; + const OPAQUE_INSERT: &str = "INSERT target is not a literal table"; + let shapes: [(&str, &[&str]); 23] = [ + // Controls: an opaque WHERE predicate (the retention deletes), a + // placeholder table with no floor column (tenant severing), and a + // builder whose upsert continues in another literal. + ( + r#"sqlx::query(concat!("UPDATE events SET deleted_at = NOW() WHERE NOT ", pred!(), ""))"#, + &[], + ), + ( + r#"format!("UPDATE {table} SET community_id = NULL WHERE community_id = $1")"#, + &[], + ), + ( + r#"QueryBuilder::new("INSERT INTO listeners (a) ").push(" ON CONFLICT (a) DO UPDATE SET created_at = EXCLUDED.created_at")"#, + &[], + ), + // A non-literal `concat!` argument as the target or a SET column. + ( + r#"concat!("UPDATE ", table!(), " SET created_at = $1")"#, + &[WRITER], + ), + ( + r#"concat!("UPDATE events SET ", cols!(), " = $1")"#, + &[WRITER], + ), + // Every macro delimiter. + ( + r#"concat!["INSERT INTO ", "events (id) VALUES ($1)"]"#, + &[WRITER], + ), + ( + r#"::core::concat!{"INSERT INTO ", "events (id) VALUES ($1)"}"#, + &[WRITER], + ), + (r#"include_str!["insert_event.sql"]"#, &[WRITER]), + (r#"include_str! {"insert_event.sql"}"#, &[WRITER]), + // Compile-time file SQL is banned outright. + ( + r#"sqlx::query_file!("insert_event.sql")"#, + &["query_file! loads SQL from a file"], + ), + ( + r#"sqlx::query_file_as!(Row, "insert_event.sql")"#, + &["query_file_as! loads SQL from a file"], + ), + // SQL assembled at runtime. + ( + r#"format!("{}{}", "INSERT INTO ", "events (id) VALUES ($1)")"#, + &[OPAQUE_INSERT], + ), + ( + r#"format!("INSERT INTO {t} (id) VALUES ($1)")"#, + &[OPAQUE_INSERT], + ), + ( + r#"["INSERT INTO ", "events (id) VALUES ($1)"].concat()"#, + &[OPAQUE_INSERT], + ), + ( + r#"format!("INSERT INTO events (id) VALUES ($1) {suffix}")"#, + &["events INSERT with a non-literal part", WRITER], + ), + ( + r#"format!("{}{}", "UPDATE ", "events SET created_at = $1")"#, + &[WRITER], + ), + ( + r#"format!("UPDATE public.events SET {column} = $1")"#, + &[WRITER], + ), + // A SET list continued in another literal or argument. + ( + r#"format!("UPDATE events SET {}", "created_at = $1")"#, + &[WRITER], + ), + ( + r#"["UPDATE events SET ", "channel_id = $1"].concat()"#, + &[WRITER], + ), + ( + r#"QueryBuilder::new("UPDATE events SET ").push("created_at = ")"#, + &[WRITER], + ), + ( + r#"QueryBuilder::new("INSERT INTO events (id) ").push(" ON CONFLICT (id) DO UPDATE SET ").push("channel_id = EXCLUDED.channel_id")"#, + &[WRITER], + ), + ( + r#"sqlx::query("MERGE INTO events e USING src ON e.id = src.id WHEN MATCHED THEN DO NOTHING")"#, + &["events written by a statement other than INSERT"], + ), + ( + r#"format!("{} TRANSACTION 'x'", "PREPARE")"#, + &["PREPARE TRANSACTION in a production writer"], + ), + ]; + let shape_violations = shapes.map(|(shape, _)| { + file_event_floor_policy_violations(&path, &format!("{WRITER}\n {shape};\n}}\n")) + }); + + // Each item-level form is caught on its own, wherever it sits. + std::fs::write( + dir.join("insert_event.sql"), + "insert into events (id) values ($1)", + ) + .expect("sql fixture"); + let items = [ + "const LEADING: &str = \"INSERT INTO events (id) VALUES ($1)\";\nfn f() {}\n", + "fn f() {}\nconst TRAILING: &str = \"UPDATE events SET channel_id = $1\";\nfn g() {}\n", + "fn f() {}\nstatic INCLUDED: &str = include_str!(\"insert_event.sql\");\n", + ]; + let item_violations = items.map(|item| file_event_floor_policy_violations(&path, item)); + std::fs::remove_dir_all(&dir).expect("remove fixture dir"); + + assert_eq!( + violations, + [ + r#"include_str!(concat!(env!("OUT_DIR"), "/insert.sql")) is opaque"#, + OPAQUE_INSERT, + "PREPARE TRANSACTION in a production writer", + "event-write SQL outside any function body", + "async fn joined_insert(tx: &mut AdmittedTx) {", + "async fn joined_rewrite(tx: &mut AdmittedTx) {", + "async fn included_insert(tx: &mut AdmittedTx) {", + ] + ); + for ((shape, expected), found) in shapes.iter().zip(&shape_violations) { + assert_eq!(found, expected, "shape `{shape}`"); + } + for (item, found) in items.iter().zip(&item_violations) { + assert_eq!( + found, + &["event-write SQL outside any function body"], + "item-level SQL in `{item}`" + ); + } +} + #[test] fn every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it() { let files = production_event_writer_source_files(); @@ -2460,8 +3136,9 @@ fn every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it( let mut guarded_writers = 0; let mut violations = Vec::new(); for path in files { - let production = strip_cfg_test_items(&std::fs::read_to_string(&path).expect("source")); - guarded_writers += function_slices(&production) + let source = std::fs::read_to_string(&path).expect("source"); + let (production, _) = sql_visible_source(&path, &strip_cfg_test_items(&source)); + guarded_writers += function_items(&production) .into_iter() .filter(|function| { inserts_events_row(function) @@ -2470,7 +3147,7 @@ fn every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it( }) .count(); violations.extend( - event_floor_policy_violations(&production) + file_event_floor_policy_violations(&path, &source) .into_iter() .map(|header| format!("{}: {header}", path.display())), ); @@ -2498,7 +3175,7 @@ fn event_floor_guard_uses_the_database_statement_clock_and_shared_floor() { ); assert!( guard.contains(".bind(CREATED_AT_FLOOR_SECS as f64)"), - "app check, GUC and fence wall must share the same floor constant" + "app check and fence wall must share the same floor constant" ); } diff --git a/crates/buzz-relay/src/api/admin/mod.rs b/crates/buzz-relay/src/api/admin/mod.rs index 8c0ed1b78f..c29797185b 100644 --- a/crates/buzz-relay/src/api/admin/mod.rs +++ b/crates/buzz-relay/src/api/admin/mod.rs @@ -9194,18 +9194,6 @@ mod postgres_tests { // `fail_outbox_row` (not `mark_outbox_delivered`) when the insert itself // fails — so nothing is durably persisted, and the row is NOT marked delivered. // - // The failure is induced AFTER tenant resolution, inside `emit_system_message`'s - // `insert_event` call, by: - // 1. Building a dedicated test pool whose `after_connect` sets the - // `buzz.created_at_floor` GUC session-locally (not database-globally). - // Every connection from that pool inherits the floor; no other pool or - // test is affected, and there is no cleanup race on panic. - // 2. Backdating the outbox row's `created_at` beyond that floor. - // `emit_system_message` derives the Nostr event's `created_at` from - // `row.created_at` (the idempotency timestamp). With the floor active, the - // deferrable trigger fires on INSERT and raises a check_violation, which - // `insert_event` propagates as `Err`. The `?` in `emit_system_message` then - // propagates it up through `deliver_tombstone → deliver_one → fail_outbox_row`. let pool = e2e_pool().await; let (community_id, _host) = e2e_community(&pool, "race-c3").await; let target = vec![24u8; 32]; @@ -9309,43 +9297,22 @@ mod postgres_tests { .await .expect("insert fail-outbox row"); - // Backdate the outbox row's created_at so emit_system_message uses an old - // idempotency_ts. The events_created_at_floor trigger will reject the INSERT - // once we arm the GUC below. - sqlx::query( - "UPDATE relay_admin_outbox SET created_at = now() - interval '10 seconds' WHERE id = $1", + // Inject a durable insert failure only in this per-test database. This + // exercises error propagation and retry state independently of the floor. + sqlx::raw_sql( + "CREATE FUNCTION reject_c3_system_message() RETURNS trigger LANGUAGE plpgsql AS $$ \ + BEGIN IF NEW.kind = 40099 THEN \ + RAISE EXCEPTION 'injected system-message insert failure' USING ERRCODE = '23514'; \ + END IF; RETURN NEW; END $$; \ + CREATE TRIGGER reject_c3_system_message BEFORE INSERT ON events \ + FOR EACH ROW EXECUTE FUNCTION reject_c3_system_message();", ) - .bind(fail_outbox_id) .execute(&pool) .await - .expect("backdate outbox created_at"); + .expect("install isolated insert failure"); + let fresh_state = state_from_pool(pool.clone()).await; - // Build a dedicated pool whose after_connect sets buzz.created_at_floor = 5 - // session-locally on each connection (set_config 3rd arg false = session scope). - // A floor of 5 s means any event with created_at > 5 s ago is rejected. - // Our outbox row's created_at is ~10 s ago → trigger fires on insert_event. - // This pool is fully isolated: no other pool or test is affected, and there - // is no cleanup dependence (dropping the pool closes all its connections). - let db_url = database_url(); - let floor_pool = sqlx::postgres::PgPoolOptions::new() - .max_connections(4) - .after_connect(|conn, _meta| { - Box::pin(async move { - sqlx::query("SELECT set_config('buzz.created_at_floor', '5', false)") - .execute(conn) - .await?; - Ok(()) - }) - }) - .connect(&db_url) - .await - .expect("connect floor pool"); - - // Build an AppState around the floor pool so deliver_one's insert_event call - // runs on a connection where the deferrable trigger is active. - let fresh_state = state_from_pool(floor_pool.clone()).await; - - // Claim the row via the floor pool so deliver_one has a real claim token. + // Claim the row so deliver_one has a real claim token. let lease_until = chrono::Utc::now() + chrono::Duration::seconds(30); let mut batch = fresh_state .db @@ -9358,14 +9325,18 @@ mod postgres_tests { .expect("fail_outbox_id must be in batch"); let row = batch.remove(row_idx); - // deliver_one fails inside emit_system_message at insert_event (deferrable - // floor-guard trigger → check_violation) and must call fail_outbox_row — + // deliver_one fails inside emit_system_message at insert_event and + // must call fail_outbox_row — // NOT mark_outbox_delivered. crate::handlers::admin_outbox_worker::deliver_one(&fresh_state, &row).await; - // Drop the floor pool — all its connections close, GUC vanishes with them. - // No ALTER DATABASE, no global state, no reset required. - drop(floor_pool); + sqlx::raw_sql( + "DROP TRIGGER reject_c3_system_message ON events; \ + DROP FUNCTION reject_c3_system_message();", + ) + .execute(&pool) + .await + .expect("remove isolated insert failure"); // No tombstone event was persisted — the failure was inside insert_event. let post_event_count: i64 = sqlx::query_scalar( diff --git a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs index 35318b0c61..7430d7d7a9 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs @@ -30,7 +30,7 @@ impl Fixture { .await .unwrap(); let mut state = (*state).clone(); - // Use production after_connect policy (floor guard, isolation and + // Use production after_connect policy (isolation and // session timeouts), not raw SQLx pools that mask deployed failures. state.db = production_db(buzz_db::DbConfig::default()).await; Arc::make_mut(&mut state.config).require_auth_token = true; diff --git a/crates/buzz-relay/src/api/git/transport.rs b/crates/buzz-relay/src/api/git/transport.rs index 24e8961066..74302ad5f7 100644 --- a/crates/buzz-relay/src/api/git/transport.rs +++ b/crates/buzz-relay/src/api/git/transport.rs @@ -2079,8 +2079,8 @@ async fn finalize_push_inner( } // An already-running receive-pack may cross the durable fence after - // request admission. Revalidate immediately before object-store CAS; DB - // trigger fencing alone cannot roll back an S3 pointer mutation. + // request admission. Revalidate immediately before object-store CAS; + // database admission alone cannot roll back an S3 pointer mutation. let serving_write = match buzz_deletion::acquire_serving_write( &state.db, ctx.tenant.community(), diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index ab591799fa..3d233bc25c 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -410,26 +410,11 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { info!("Community deletion serving fences verified"); step.finish(); - // Freshness fence probe: cursor pages route to the replica only for - // history the probe has verified as fully replayed. Deliberately AFTER - // the migration decision: spawn_fence_probe first verifies the - // commit-time floor guard (catalog shape + observed behavior through the - // armed pool) against the live schema, so a relay running with - // BUZZ_AUTO_MIGRATE off and migration 0021 unapplied can never open the - // fence over an unenforced floor. Verification failure is loud but - // non-fatal: the fence stays closed and every cursor page routes to the - // writer. - let mut step = StepTimer::start(StartupStep::ReplicaFenceProbe); - match db.spawn_fence_probe().await { - Ok(true) => info!("Replica fence probe started (floor guard verified)"), - Ok(false) => {} - Err(e) => { - step.degrade(); - error!( - "Replica fence disabled — floor guard verification failed: {e}. \ - All cursor reads stay on the writer." - ); - } + // The ordered heartbeat probe opens replica routing only after a + // successful sample. Errors keep cursor reads on the writer. + let step = StepTimer::start(StartupStep::ReplicaFenceProbe); + if db.spawn_fence_probe() { + info!("Replica fence probe started"); } step.finish(); diff --git a/crates/buzz-relay/src/startup_steps.rs b/crates/buzz-relay/src/startup_steps.rs index bdda346a61..9877645988 100644 --- a/crates/buzz-relay/src/startup_steps.rs +++ b/crates/buzz-relay/src/startup_steps.rs @@ -51,7 +51,7 @@ pub enum StartupStep { PartitionEnsure, /// Verify the community-deletion serving fences. DeletionFenceVerify, - /// Verify the replica floor guard and start the fence probe. + /// Start the replica freshness fence probe. ReplicaFenceProbe, /// Ensure the deployment community, backfill the allowlist, and bootstrap the owner. MembershipBootstrap, diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index 328307ec61..606b589529 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -362,7 +362,7 @@ can give it to a caller. | `buzz_db_connection_step_duration_seconds` | histogram | `pool_role`, `step` | | `buzz_db_connection_step_attempts_total` | counter | `pool_role`, `step`, `outcome` | -The fixed steps are `writer_pool`, `physical_connect`, `created_at_floor`, +The fixed steps are `writer_pool`, `physical_connect`, `session_timeouts`, `isolation`, and `ready`. Measurable phases emit start, duration, and terminal evidence. `physical_connect` and `ready` are success milestones: SQLx 0.9 exposes `after_connect` only after DNS, network, TLS, and @@ -376,8 +376,8 @@ start counter to derive the number of attempts currently in progress. The session phases run in order, so a later phase start also proves the earlier phases succeeded for that attempt. -Four start counters, four 13-series histograms, and fifteen terminal counters -create a hard ceiling of 71 raw Prometheus series per pod. Connection ordinals, +Three start counters, three 13-series histograms, and twelve terminal counters +create a hard ceiling of 54 raw Prometheus series per pod. Connection ordinals, database URLs, hosts, usernames, SQL, and raw errors are forbidden as metric labels. diff --git a/docs/buzz-v1-read-state.md b/docs/buzz-v1-read-state.md index f89e2e0774..07890364cd 100644 --- a/docs/buzz-v1-read-state.md +++ b/docs/buzz-v1-read-state.md @@ -259,8 +259,9 @@ no fixed context-count ceiling. Leaving/rejoining does not erase progress; revoked access hides it. Soft-deleted channels are inaccessible, while hard channel deletion cascades their frontiers. Deleting an account row cascades that actor's frontiers in the same community; -community erasure inventories both tables under the existing write fence. There -is no new public account export/reset endpoint. Operator-assisted erasure/export +community erasure inventories both tables, with serving writes fenced by the +app-side admission guard and the community deletion-lock protocol. There is no +new public account export/reset endpoint. Operator-assisted erasure/export must use the established authenticated operational process and explicitly scope both community and actor; never equate the read-time horizon with data erasure. diff --git a/docs/database.md b/docs/database.md index b573edec3c..43d62cdf23 100644 --- a/docs/database.md +++ b/docs/database.md @@ -76,9 +76,9 @@ transaction that owns the write: Dropping or narrowing an existing trigger or function is welcome. Follow the retirement sequence below. -**No exception for the community write fence.** A new table MUST NOT get a -fence trigger, including by calling the existing helper -`attach_community_write_fence`. Writers of a new tenant-owned table MUST be +**No exception for the community write fence.** Migration 0090 dropped the +universal fence triggers and their helper functions; a new table MUST NOT bring +a fence trigger back. Writers of a new tenant-owned table MUST be fenced in the application instead, by community admission. New serving work, including fleet sweeps (one community at a time), is admitted by `DeletionStore::guard_transaction`, which takes the shared community deletion @@ -93,33 +93,23 @@ a write that finishes under an already-admitted serving lease complete while the community is `quiescing`. Keep it. Helpers that take `&mut AdmittedTx` reject a raw transaction at compile time, -but crate code can still bypass the type, so the fence triggers remain the -database backstop until they are dropped (ARCHITECTURE.md § *Supported Writer -Contract*). A table without a trigger has no database backstop. Every serving -writer of a fenced table already goes through admission. The remaining -fence-retirement work drops the fence triggers and functions, and MUST also -update ARCHITECTURE.md § *Dual enforcement*. +but crate code can still bypass the type, and no table has a database fence +backstop (ARCHITECTURE.md § *Supported Writer Contract*). Every serving writer +of a tenant table goes through admission. **New tenant-owned tables use application admission.** Startup and deletion validation no longer require a fence on any table; they pass with every universal fence object dropped (`migration_schema_fence_objects_are_optional_for_serving_and_deletion` -in `crates/buzz-db/src/store/deletion.rs`). Two things still matter: +in `crates/buzz-db/src/store/deletion.rs`). Deletion's catalog check is an +exact set: a `community_id` table missing from `EXPECTED_SCOPED_TABLES` fails it +(`community deletion catalog drift (missing=…, unknown=…)`), and deletion fails +closed for every community, not only the new table's. Listing the table passes +once its release is deployed; a relay deployed before the migration needs the +table in `PENDING_SCOPED_TABLES` (see the checklist). -- Deletion's catalog check is an exact set. A `community_id` table missing from - `EXPECTED_SCOPED_TABLES`, fenced or not, fails it - (`community deletion catalog drift (missing=…, unknown=…)`), and deletion - fails closed for every community, not only the new table's. Listing the - table passes once its release is deployed; a relay deployed before the - migration needs the table in `PENDING_SCOPED_TABLES` (see the checklist). -- Desired-state bootstraps install only the legacy fences explicitly listed - under `schema/triggers/`. They do not discover and fence new tables. - Keep those existing backstops until their own retirement is verified; - new tables receive no fence in either schema path. - -The blanket desired-state fence attachment has been removed. A feature may -add a tenant-owned `community_id` table when it follows the checklist below. -Do not add a trigger, or an entry in -`community_write_fence_excluded_table` for a table the community owns. +A feature may add a tenant-owned `community_id` table when it follows the +checklist below. Do not add a trigger, or an entry in `EXCLUDED_SCOPED_TABLES` +(`crates/buzz-db/src/store/deletion.rs`) for a table the community owns. #### Checklist: adding a tenant-owned `community_id` table @@ -135,8 +125,7 @@ Then, all in the same PR: - [ ] Every writer of the table goes through community admission (`begin_community_write_transaction` or another constructor that returns `AdmittedTx`). Nothing writes the table outside it. -- [ ] No fence trigger: no `attach_community_write_fence` call in the - migration and no `schema/triggers/` file. +- [ ] No fence trigger in the migration or under `schema/triggers/`. - [ ] The table in `EXPECTED_SCOPED_TABLES` (`crates/buzz-db/src/store/deletion.rs`). - [ ] The table in `PURGE_SCOPED_TABLES` in the same file, ordered child before parent. A table missing here keeps its rows after the purge, and @@ -167,11 +156,10 @@ whose rows must stay writable while that community is being deleted, is not owned by that community and is not fenced. The existing ones (the deletion control plane, `product_feedback`, `rate_limit_violations`, and `operator_listener_outbox`) predate this rule and are listed in -`community_write_fence_excluded_table`. A new one MUST name its column -something other than `community_id`, as -`relay_admin_actions.report_community_id` does, so the catalog does not treat -the table as scoped. Adding a case to the exclusion function would widen an -existing function, which Rule 1 forbids. Renaming the +`EXCLUDED_SCOPED_TABLES`. A new one MUST name its column something other than +`community_id`, as `relay_admin_actions.report_community_id` does, so the +catalog does not treat the table as scoped. Do not grow the exclusion list for +a new table. Renaming the column also removes the table from every automatic deletion surface, so rows that name a deleted community survive deletion and no check fails, unless the PR follows this checklist. All in the same PR: @@ -252,9 +240,10 @@ holding a write-blocking lock. Scans that do not block writes, such as before taking the lock races with deletion. - A repair script that writes a channel-bearing `events` row older than the floor (inserting one, moving `created_at` backward, or setting `channel_id` - on an old row) is outside the replica-floor proof: an - operator session does not set `buzz.created_at_floor`, so the commit-time - floor guard lets it through (`migrations/0021`). Its PR MUST document a + on an old row) is outside the replica-floor proof: only the relay's + app-side floor check (`replica_fence::guard_event_created_at_floor`) + enforces the floor, and an operator session runs none of it, so nothing + in the database stops the write. Its PR MUST document a reviewed procedure that keeps replica routing closed from before the first batch until its WAL has replayed on every replica. - A script MUST NOT disable triggers or set `session_replication_role`. @@ -315,8 +304,8 @@ Every migration MUST be safe for the currently deployed release to read and write against. The relay has no general schema-version compatibility check. It verifies only -specific catalog surfaces, such as the deletion serving fence and the replica -floor guard, so the ordering below is the main protection. When +specific catalog surfaces, such as the deletion serving fence, so the ordering +below is the main protection. When `BUZZ_AUTO_MIGRATE` is on, an older binary refuses a database that has migrations it does not know (sqlx `VersionMissing`), so `helm rollback` with auto-migration on fails at startup, and so does any old pod that restarts diff --git a/docs/trigger-retirement-deployment.md b/docs/trigger-retirement-deployment.md new file mode 100644 index 0000000000..7955238743 --- /dev/null +++ b/docs/trigger-retirement-deployment.md @@ -0,0 +1,71 @@ +# Trigger retirement deployment + +Three migrations drop database triggers and functions whose work the relay +now does in application code. They ship in one release: + +| Migration | Drops | Application replacement | +| --- | --- | --- | +| `0089_retire_created_at_floor.sql` | the `events_created_at_floor` constraint trigger and its function (`0021`) | the insert-time floor check, [#8325](https://github.com/block/buzz/pull/8325) | +| `0090_retire_community_write_fence.sql` | the universal community write-fence triggers and functions | app-side write admission, [#8219](https://github.com/block/buzz/pull/8219), [#8318](https://github.com/block/buzz/pull/8318) and [#8322](https://github.com/block/buzz/pull/8322) | +| `0091_drop_nip_rs_mesh_migration_triggers.sql` | the migration-only NIP-RS watermark, purge, mention-liveness and mesh-status triggers | [#8128](https://github.com/block/buzz/pull/8128) | + +## Required stop + +**The first relay release that contains +[#8325](https://github.com/block/buzz/pull/8325) is a required stop.** It also +contains every other replacement above. `relay-v0.3.0` has the others but not +#8325, so it is not enough. + +Do not upgrade past the stop to the release with these migrations until no +older relay runs anywhere: every pod and job, not only a rollout's new pods. +The migrations cannot detect an older writer. If an operator upgrades straight +from an older release, the first new pod applies the migrations while older +pods are still serving: + +- a relay without #8325 has no floor check, so it accepts backdated channel + events that replica reads can then skip; +- a relay without #8318 fails its background jobs with + `42883 community_write_allowed(uuid) does not exist`; +- a relay without #8128 loses the NIP-RS watermark and superseded-row purge. + +## Procedure + +1. Deploy the stop release. Check the image of every relay pod and job, and + wait until none runs an older one. +2. Stop out-of-band writers (direct SQL, `COPY`, restores, seed scripts). Hold + the replica breaker closed from before the migrations until every replica + has replayed them. +3. Apply the migrations off-peak. Each one sets a 5s `lock_timeout`, and the + `DROP TRIGGER` statements take `ACCESS EXCLUSIVE` on `events` and its + partitions, so event reads and writes can stall for up to that long. A + lock timeout aborts that migration, which is safe to retry. + - **Auto-migration on:** deploy the new release. Its first pod applies the + migrations at startup. + - **Auto-migration off:** run `buzz-admin migrate` with the target + `DATABASE_URL`, confirm that it records 0089, 0090 and 0091, then deploy + the new release. The new release assumes 0091 has run: against a + database without it, NIP-RS hard deletes fail closed with + `check_violation`. The stop release works with all three applied. +4. Once every relay runs the new release, run the one-off cleanup SQL in + [#8211](https://github.com/block/buzz/pull/8211) once per database. While + stop-release pods served after 0091, a replacement could leave a + soft-deleted NIP-RS or mesh-status head that nothing purges any more. The + cleanup is idempotent. + +## Desired-state deployments + +A deployment that applies `schema/` with pgschema follows the same order. +Apply the migrations first, or first drop the triggers on the partitioned +parents: `events_created_at_floor` and `community_write_fence_events` on +`events`, and `community_write_fence_delivery_log` on `delivery_log`. +Otherwise pgschema plans the partition copies' drops before the parent's, and +PostgreSQL refuses with `2BP01`. + +## Rollback + +Roll back to the stop release, not further, and only with auto-migration off +(`BUZZ_AUTO_MIGRATE=false`, or `migrate.autoMigrate=false` in the Helm chart). +With it on, the stop release refuses a database that has migrations it does +not know (`VersionMissing`) and does not start. With it off, the stop release +serves, but its startup check finds the floor trigger gone and keeps the +replica fence closed, so cursor reads go to the writer. diff --git a/migrations/0089_retire_created_at_floor.sql b/migrations/0089_retire_created_at_floor.sql new file mode 100644 index 0000000000..76f2a9bbba --- /dev/null +++ b/migrations/0089_retire_created_at_floor.sql @@ -0,0 +1,30 @@ +SET LOCAL lock_timeout = '5s'; + +-- DESTRUCTIVE CONTRACT: deploy phase 1's application floor check to every +-- writer pod/job first, with no rollback expected. The first relay release +-- with it is a required stop (docs/trigger-retirement-deployment.md). Stop out-of-band writers +-- and hold the replica breaker closed through this drop until replay catches +-- up. Old pods that already started do not recheck the guard on each probe. +-- Keep the 960-second application floor and the ordered heartbeat handshake. +-- DROP TRIGGER takes ACCESS EXCLUSIVE on events and every partition, so it +-- can stall events reads/writes for up to lock_timeout. Run off-peak; a lock +-- timeout aborts the whole migration and is safe to retry. +-- No other trigger, function, FK, or tenant fence is retired here. +DROP TRIGGER IF EXISTS events_created_at_floor ON events; + +-- Dropping the parent removes its inherited clones (including partitions +-- created since 0021). Also remove any independently attached child copy. +DO $$ +DECLARE + partition_table regclass; +BEGIN + FOR partition_table IN + SELECT relid FROM pg_partition_tree('events'::regclass) + WHERE relid <> 'events'::regclass + LOOP + EXECUTE format('DROP TRIGGER IF EXISTS events_created_at_floor ON %s', partition_table); + END LOOP; +END +$$; + +DROP FUNCTION IF EXISTS events_created_at_floor_guard(); diff --git a/migrations/0090_retire_community_write_fence.sql b/migrations/0090_retire_community_write_fence.sql new file mode 100644 index 0000000000..43a0adf0ee --- /dev/null +++ b/migrations/0090_retire_community_write_fence.sql @@ -0,0 +1,44 @@ +SET LOCAL lock_timeout = '5s'; + +-- The fleet has moved to app-side admission for all supported serving writers. +-- Drop only the universal community write-fence triggers. The community +-- tombstone and all other table guards remain in place. +DROP TRIGGER IF EXISTS community_write_fence_api_tokens ON api_tokens; +DROP TRIGGER IF EXISTS community_write_fence_archived_identities ON archived_identities; +DROP TRIGGER IF EXISTS community_write_fence_artifact_heads ON artifact_heads; +DROP TRIGGER IF EXISTS community_write_fence_artifact_revisions ON artifact_revisions; +DROP TRIGGER IF EXISTS community_write_fence_audit_log ON audit_log; +DROP TRIGGER IF EXISTS community_write_fence_channel_members ON channel_members; +DROP TRIGGER IF EXISTS community_write_fence_channels ON channels; +DROP TRIGGER IF EXISTS community_write_fence_community_bans ON community_bans; +DROP TRIGGER IF EXISTS community_write_fence_community_nip_fi_issuers ON community_nip_fi_issuers; +DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log; +DROP TRIGGER IF EXISTS community_write_fence_event_mentions ON event_mentions; +DROP TRIGGER IF EXISTS community_write_fence_events ON events; +DROP TRIGGER IF EXISTS community_write_fence_git_repo_names ON git_repo_names; +DROP TRIGGER IF EXISTS community_write_fence_join_policy_acceptances ON join_policy_acceptances; +DROP TRIGGER IF EXISTS community_write_fence_moderation_actions ON moderation_actions; +DROP TRIGGER IF EXISTS community_write_fence_moderation_reports ON moderation_reports; +DROP TRIGGER IF EXISTS community_write_fence_parameterized_event_watermarks ON parameterized_event_watermarks; +DROP TRIGGER IF EXISTS community_write_fence_personal_read_accounts ON personal_read_accounts; +DROP TRIGGER IF EXISTS community_write_fence_personal_read_frontiers ON personal_read_frontiers; +DROP TRIGGER IF EXISTS community_write_fence_pubkey_allowlist ON pubkey_allowlist; +DROP TRIGGER IF EXISTS community_write_fence_push_leases ON push_leases; +DROP TRIGGER IF EXISTS community_write_fence_push_match_queue ON push_match_queue; +DROP TRIGGER IF EXISTS community_write_fence_push_wake_outbox ON push_wake_outbox; +DROP TRIGGER IF EXISTS community_write_fence_reactions ON reactions; +DROP TRIGGER IF EXISTS community_write_fence_relay_invites ON relay_invites; +DROP TRIGGER IF EXISTS community_write_fence_relay_members ON relay_members; +DROP TRIGGER IF EXISTS community_write_fence_scheduled_workflow_fires ON scheduled_workflow_fires; +DROP TRIGGER IF EXISTS community_write_fence_subscriptions ON subscriptions; +DROP TRIGGER IF EXISTS community_write_fence_thread_metadata ON thread_metadata; +DROP TRIGGER IF EXISTS community_write_fence_users ON users; +DROP TRIGGER IF EXISTS community_write_fence_workflow_approvals ON workflow_approvals; +DROP TRIGGER IF EXISTS community_write_fence_workflow_runs ON workflow_runs; +DROP TRIGGER IF EXISTS community_write_fence_workflows ON workflows; + +DROP FUNCTION attach_community_write_fence(REGCLASS); +DROP FUNCTION enforce_community_write_fence(); +DROP FUNCTION assert_community_write_allowed(UUID); +DROP FUNCTION community_write_allowed(UUID); +DROP FUNCTION community_write_fence_excluded_table(NAME); diff --git a/migrations/0091_drop_nip_rs_mesh_migration_triggers.sql b/migrations/0091_drop_nip_rs_mesh_migration_triggers.sql new file mode 100644 index 0000000000..cac8d46653 --- /dev/null +++ b/migrations/0091_drop_nip_rs_mesh_migration_triggers.sql @@ -0,0 +1,31 @@ +-- Drop the NIP-RS, mention-liveness and mesh-status triggers that exist only +-- in migration-managed databases. The application now owns each rule inside +-- the event transaction (crates/buzz-db/src/store/replaceable.rs and +-- crates/buzz-db/src/store/event.rs): +-- +-- - it advances parameterized_event_watermarks and rejects stale NIP-RS writes; +-- - it physically deletes superseded and NIP-09-deleted NIP-RS and mesh-status +-- rows, with their mentions; +-- - it indexes mentions in the same transaction as the event, so a mention +-- can no longer race a hard delete. +-- +-- schema/ never declared these objects, so desired-state databases already run +-- without them. Dropping a trigger on the partitioned parent also drops its +-- partition clones. Published migrations 0009, 0010, 0011 and 0019 stay +-- checksum-frozen. +-- +-- DROP TRIGGER takes ACCESS EXCLUSIVE on events and every partition; fail the +-- deployment rather than queue relay reads and writes behind a long holder. +SET LOCAL lock_timeout = '5s'; + +DROP TRIGGER trg_events_nip_rs_watermark ON events; +DROP TRIGGER trg_events_guard_nip_rs_hard_delete ON events; +DROP TRIGGER trg_events_purge_soft_deleted_nip_rs ON events; +DROP TRIGGER trg_events_purge_soft_deleted_buzz_mesh_status ON events; +DROP TRIGGER trg_event_mentions_require_live_event ON event_mentions; + +DROP FUNCTION guard_nip_rs_watermark(); +DROP FUNCTION guard_nip_rs_hard_delete(); +DROP FUNCTION purge_soft_deleted_nip_rs(); +DROP FUNCTION purge_soft_deleted_buzz_mesh_status(); +DROP FUNCTION guard_event_mention_live(); diff --git a/schema/functions/assert_community_write_allowed.sql b/schema/functions/assert_community_write_allowed.sql deleted file mode 100644 index f68b45091c..0000000000 --- a/schema/functions/assert_community_write_allowed.sql +++ /dev/null @@ -1,78 +0,0 @@ -CREATE FUNCTION assert_community_write_allowed(target UUID) RETURNS VOID -LANGUAGE plpgsql AS $$ -DECLARE - lifecycle TEXT; - generation BIGINT; - executor_community TEXT; - executor_generation TEXT; - serving_community TEXT; - serving_lease_id TEXT; - serving_owner TEXT; - serving_generation TEXT; - serving_fence_generation TEXT; - serving_lease_valid BOOLEAN := false; -BEGIN - -- The fence proof requires a fresh statement snapshot after lock grant; - -- pinned RR/Serializable snapshots can retain pre-fence authorization. - IF current_setting('transaction_isolation') <> 'read committed' THEN - RAISE EXCEPTION 'community writes require READ COMMITTED isolation' - USING ERRCODE = 'invalid_transaction_state'; - END IF; - - -- Nullable operator-attribution rows without a tenant are unrelated. - IF target IS NULL THEN - RETURN; - END IF; - - PERFORM pg_advisory_xact_lock_shared(community_deletion_lock_key(target)); - SELECT deletion_state, deletion_fence_generation - INTO lifecycle, generation - FROM communities - WHERE id = target; - IF NOT FOUND THEN - RAISE EXCEPTION 'community write rejected: community % is missing', target - USING ERRCODE = 'object_not_in_prerequisite_state'; - END IF; - - -- Authorization is evaluated independently for every community checked. - executor_community := current_setting('buzz.deletion_executor_community', true); - executor_generation := current_setting('buzz.deletion_fence_generation', true); - IF executor_community = target::TEXT - AND executor_generation ~ '^[0-9]+$' - AND executor_generation::BIGINT = generation THEN - RETURN; - END IF; - - -- A serving mutation admitted before quiescing may finish only while its - -- exact durable lease remains current and bound to this fence generation. - serving_community := current_setting('buzz.serving_write_community', true); - serving_lease_id := current_setting('buzz.serving_write_lease_id', true); - serving_owner := current_setting('buzz.serving_write_owner', true); - serving_generation := current_setting('buzz.serving_write_generation', true); - serving_fence_generation := current_setting('buzz.serving_write_fence_generation', true); - IF lifecycle IN ('active', 'quiescing') - AND serving_community = target::TEXT - AND serving_lease_id ~ '^[0-9a-fA-F-]{36}$' - AND serving_generation ~ '^[0-9]+$' - AND serving_fence_generation ~ '^[0-9]+$' - AND serving_fence_generation::BIGINT = generation THEN - SELECT EXISTS( - SELECT 1 FROM community_serving_write_leases lease - WHERE lease.id = serving_lease_id::UUID - AND lease.community_id = target - AND lease.owner = serving_owner - AND lease.generation = serving_generation::BIGINT - AND lease.fence_generation = serving_fence_generation::BIGINT - AND lease.lease_until >= now() - ) INTO serving_lease_valid; - IF serving_lease_valid THEN - RETURN; - END IF; - END IF; - - IF lifecycle <> 'active' THEN - RAISE EXCEPTION 'community write fenced: community % generation %', target, generation - USING ERRCODE = 'object_not_in_prerequisite_state'; - END IF; -END -$$; diff --git a/schema/functions/attach_community_write_fence.sql b/schema/functions/attach_community_write_fence.sql deleted file mode 100644 index 94d510f75c..0000000000 --- a/schema/functions/attach_community_write_fence.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Attach the legacy universal fence to one community-scoped relation. Only --- tables fenced before fence retirement use it; new tenant tables rely on --- application admission and must not call it (docs/database.md Rule 1). -CREATE FUNCTION attach_community_write_fence(target REGCLASS) RETURNS VOID -LANGUAGE plpgsql AS $$ -DECLARE - relation_name NAME; -BEGIN - SELECT c.relname - INTO relation_name - FROM pg_class c - JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE c.oid = target - AND n.nspname = current_schema() - AND c.relkind IN ('r', 'p') - AND NOT c.relispartition; - IF NOT FOUND THEN - RAISE EXCEPTION 'community write fence target % is not a table in the current schema', target - USING ERRCODE = 'wrong_object_type'; - END IF; - IF community_write_fence_excluded_table(relation_name) THEN - RETURN; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM pg_attribute - WHERE attrelid = target AND attname = 'community_id' AND NOT attisdropped - ) THEN - RAISE EXCEPTION 'community write fence target % has no community_id', target - USING ERRCODE = 'undefined_column'; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM pg_trigger - WHERE tgrelid = target - AND tgname = 'community_write_fence_' || relation_name - AND NOT tgisinternal - ) THEN - EXECUTE format( - 'CREATE TRIGGER %I BEFORE INSERT OR UPDATE OR DELETE ON %s ' - 'FOR EACH ROW EXECUTE FUNCTION enforce_community_write_fence()', - 'community_write_fence_' || relation_name, - target - ); - END IF; -END -$$; diff --git a/schema/functions/community_write_allowed.sql b/schema/functions/community_write_allowed.sql deleted file mode 100644 index 2de857de92..0000000000 --- a/schema/functions/community_write_allowed.sql +++ /dev/null @@ -1,24 +0,0 @@ --- Fleet-wide writers filter candidates through this VOLATILE predicate in --- the mutating statement so fenced tenants are skipped before row triggers run. -CREATE FUNCTION community_write_allowed(target UUID) RETURNS BOOLEAN -LANGUAGE plpgsql VOLATILE AS $$ -DECLARE - lifecycle TEXT; -BEGIN - IF current_setting('transaction_isolation') <> 'read committed' THEN - RAISE EXCEPTION 'community writes require READ COMMITTED isolation' - USING ERRCODE = 'invalid_transaction_state'; - END IF; - - IF target IS NULL THEN - RETURN true; - END IF; - - PERFORM pg_advisory_xact_lock_shared(community_deletion_lock_key(target)); - SELECT deletion_state - INTO lifecycle - FROM communities - WHERE id = target; - RETURN FOUND AND lifecycle = 'active'; -END -$$; diff --git a/schema/functions/community_write_fence_excluded_table.sql b/schema/functions/community_write_fence_excluded_table.sql deleted file mode 100644 index 34735522f8..0000000000 --- a/schema/functions/community_write_fence_excluded_table.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Keep the deletion control plane writable while its target tenant is fenced. --- This predicate is the single SQL source of truth used by attachment and live --- catalog validation. -CREATE FUNCTION community_write_fence_excluded_table(target NAME) RETURNS BOOLEAN -LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE AS $$ - SELECT target::TEXT = ANY (ARRAY[ - 'community_deletion_requests', 'community_deletion_approvals', - 'community_deletion_checkpoints', 'community_serving_write_leases', - 'community_deletion_executor_heartbeats', 'product_feedback', - 'rate_limit_violations', 'operator_listener_outbox' - ]::TEXT[]) -$$; diff --git a/schema/functions/enforce_community_write_fence.sql b/schema/functions/enforce_community_write_fence.sql deleted file mode 100644 index b7b5e8d641..0000000000 --- a/schema/functions/enforce_community_write_fence.sql +++ /dev/null @@ -1,24 +0,0 @@ -CREATE FUNCTION enforce_community_write_fence() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF TG_OP = 'INSERT' THEN - PERFORM assert_community_write_allowed(NEW.community_id); - ELSIF TG_OP = 'DELETE' THEN - PERFORM assert_community_write_allowed(OLD.community_id); - ELSIF OLD.community_id IS NOT DISTINCT FROM NEW.community_id THEN - PERFORM assert_community_write_allowed(OLD.community_id); - ELSIF OLD.community_id IS NULL THEN - PERFORM assert_community_write_allowed(NEW.community_id); - ELSIF NEW.community_id IS NULL THEN - PERFORM assert_community_write_allowed(OLD.community_id); - ELSIF OLD.community_id < NEW.community_id THEN - PERFORM assert_community_write_allowed(OLD.community_id); - PERFORM assert_community_write_allowed(NEW.community_id); - ELSE - PERFORM assert_community_write_allowed(NEW.community_id); - PERFORM assert_community_write_allowed(OLD.community_id); - END IF; - - RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END; -END -$$; diff --git a/schema/functions/events_created_at_floor_guard.sql b/schema/functions/events_created_at_floor_guard.sql deleted file mode 100644 index 263886f83f..0000000000 --- a/schema/functions/events_created_at_floor_guard.sql +++ /dev/null @@ -1,29 +0,0 @@ --- Replica-fence floor guard (keep in sync with migrations/0021). A deferred --- constraint trigger re-checks, inside COMMIT processing, that channel-bearing --- event rows are no older than `buzz.created_at_floor` seconds before commit --- time (clock_timestamp(), NOT the transaction-frozen now()). This turns the --- relay's ingest-time created_at envelope into a commit-time storage --- invariant, which is what lets keyset-cursor pages below the replica fence --- be served by a read replica without holes. Enforcement is armed per session --- via the GUC (set by the relay's writer pool on connect); sessions without --- the GUC (pg_restore, manual backfills) bypass it and must hold the replica --- fence closed for their duration. The only structural exemption is --- channel_id IS NULL: those rows never appear in keyset-paged windows. -CREATE FUNCTION events_created_at_floor_guard() RETURNS trigger -LANGUAGE plpgsql AS $$ -DECLARE - floor_secs numeric := nullif(current_setting('buzz.created_at_floor', true), '')::numeric; -BEGIN - IF floor_secs IS NOT NULL - AND floor_secs > 0 - AND NEW.channel_id IS NOT NULL - AND NEW.created_at < clock_timestamp() - make_interval(secs => floor_secs) - THEN - RAISE EXCEPTION - 'events.created_at % is more than % s before commit time %; below the replica-fence floor', - NEW.created_at, floor_secs, clock_timestamp() - USING ERRCODE = 'check_violation'; - END IF; - RETURN NULL; -END -$$; diff --git a/schema/schema.sql b/schema/schema.sql index f804fb0bc4..2c8ddeb16d 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -6,9 +6,8 @@ -- namespace, so nothing else may live under it. -- -- Everything SchemaBot cannot apply lives in this directory's other --- subdirectories: `types/`, `functions/`, `partitions/`, `triggers/` (including --- explicit legacy write-fence attachment), and `seeds/`. This file composes --- them into one fresh database, in load order: +-- subdirectories: `types/`, `functions/`, `partitions/`, `triggers/`, and +-- `seeds/`. This file composes them into one fresh database, in load order: -- types → functions → tables → partitions → triggers → seeds. -- -- `./bin/pgschema apply --file schema/schema.sql` resolves the `\i` includes @@ -65,17 +64,11 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; -- functions \i functions/channels_community_id_immutable.sql \i functions/guard_channel_roster_snapshot.sql -\i functions/events_created_at_floor_guard.sql \i functions/prevent_community_deletion_request_retargeting.sql \i functions/prevent_community_deletion_approval_removal.sql \i functions/protect_community_deletion_manifest_keys.sql \i functions/community_deletion_lock_key.sql -\i functions/community_write_fence_excluded_table.sql -\i functions/community_write_allowed.sql -\i functions/assert_community_write_allowed.sql -\i functions/enforce_community_write_fence.sql \i functions/enforce_community_tombstone.sql -\i functions/attach_community_write_fence.sql \i functions/profile_name_fields.sql -- tables @@ -153,37 +146,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i triggers/community_deletion_approvals.sql \i triggers/community_deletion_manifest_keys.sql \i triggers/communities.sql -\i triggers/api_tokens.sql -\i triggers/archived_identities.sql -\i triggers/audit_log.sql -\i triggers/channel_members.sql -\i triggers/community_bans.sql -\i triggers/community_nip_fi_issuers.sql -\i triggers/delivery_log.sql -\i triggers/event_mentions.sql -\i triggers/git_repo_names.sql -\i triggers/join_policy_acceptances.sql -\i triggers/moderation_actions.sql -\i triggers/moderation_reports.sql -\i triggers/parameterized_event_watermarks.sql -\i triggers/personal_read_accounts.sql -\i triggers/personal_read_frontiers.sql -\i triggers/pubkey_allowlist.sql -\i triggers/push_leases.sql -\i triggers/push_match_queue.sql -\i triggers/push_wake_outbox.sql -\i triggers/reactions.sql -\i triggers/relay_invites.sql -\i triggers/relay_members.sql -\i triggers/scheduled_workflow_fires.sql -\i triggers/subscriptions.sql -\i triggers/thread_metadata.sql -\i triggers/users.sql -\i triggers/workflow_approvals.sql -\i triggers/workflow_runs.sql -\i triggers/workflows.sql -\i triggers/artifact_heads.sql -\i triggers/artifact_revisions.sql -- seeds \i seeds/communities.sql diff --git a/schema/triggers/api_tokens.sql b/schema/triggers/api_tokens.sql deleted file mode 100644 index 214339212a..0000000000 --- a/schema/triggers/api_tokens.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('api_tokens'); diff --git a/schema/triggers/archived_identities.sql b/schema/triggers/archived_identities.sql deleted file mode 100644 index af7a0d4696..0000000000 --- a/schema/triggers/archived_identities.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('archived_identities'); diff --git a/schema/triggers/artifact_heads.sql b/schema/triggers/artifact_heads.sql deleted file mode 100644 index b5114f4fde..0000000000 --- a/schema/triggers/artifact_heads.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('artifact_heads'); diff --git a/schema/triggers/artifact_revisions.sql b/schema/triggers/artifact_revisions.sql deleted file mode 100644 index efdb38afa2..0000000000 --- a/schema/triggers/artifact_revisions.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('artifact_revisions'); diff --git a/schema/triggers/audit_log.sql b/schema/triggers/audit_log.sql deleted file mode 100644 index 39ea4644f0..0000000000 --- a/schema/triggers/audit_log.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('audit_log'); diff --git a/schema/triggers/channel_members.sql b/schema/triggers/channel_members.sql deleted file mode 100644 index 3dc104ace8..0000000000 --- a/schema/triggers/channel_members.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('channel_members'); diff --git a/schema/triggers/channels.sql b/schema/triggers/channels.sql index 0dd5f73ba4..0a7130cdb3 100644 --- a/schema/triggers/channels.sql +++ b/schema/triggers/channels.sql @@ -1,4 +1,3 @@ CREATE TRIGGER trg_channels_community_id_immutable BEFORE UPDATE ON channels FOR EACH ROW EXECUTE FUNCTION channels_community_id_immutable(); -SELECT attach_community_write_fence('channels'); diff --git a/schema/triggers/community_bans.sql b/schema/triggers/community_bans.sql deleted file mode 100644 index 063e3ab456..0000000000 --- a/schema/triggers/community_bans.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('community_bans'); diff --git a/schema/triggers/community_nip_fi_issuers.sql b/schema/triggers/community_nip_fi_issuers.sql deleted file mode 100644 index 7634ca372a..0000000000 --- a/schema/triggers/community_nip_fi_issuers.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('community_nip_fi_issuers'); diff --git a/schema/triggers/delivery_log.sql b/schema/triggers/delivery_log.sql deleted file mode 100644 index 7d0044a9cf..0000000000 --- a/schema/triggers/delivery_log.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('delivery_log'); diff --git a/schema/triggers/event_mentions.sql b/schema/triggers/event_mentions.sql deleted file mode 100644 index b5b5767d0f..0000000000 --- a/schema/triggers/event_mentions.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('event_mentions'); diff --git a/schema/triggers/events.sql b/schema/triggers/events.sql index 64d9bbdd5d..0e998c8b1e 100644 --- a/schema/triggers/events.sql +++ b/schema/triggers/events.sql @@ -1,16 +1,3 @@ CREATE TRIGGER trg_events_guard_channel_roster_snapshot BEFORE INSERT ON events FOR EACH ROW EXECUTE FUNCTION guard_channel_roster_snapshot(); - --- INSERT OR UPDATE OF: an UPDATE can move a previously exempt row into the --- guarded set (channel_id NULL -> NOT NULL) or move a channel row's --- created_at below the fence, so both mutation paths re-run the guard on the --- NEW row. A created_at rewrite that crosses partition bounds runs as --- DELETE + INSERT and hits the cloned AFTER INSERT guard on the destination --- partition; an in-partition rewrite fires the UPDATE OF arm. -CREATE CONSTRAINT TRIGGER events_created_at_floor - AFTER INSERT OR UPDATE OF created_at, channel_id ON events - DEFERRABLE INITIALLY DEFERRED - FOR EACH ROW - EXECUTE FUNCTION events_created_at_floor_guard(); -SELECT attach_community_write_fence('events'); diff --git a/schema/triggers/git_repo_names.sql b/schema/triggers/git_repo_names.sql deleted file mode 100644 index 3d3cdea862..0000000000 --- a/schema/triggers/git_repo_names.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('git_repo_names'); diff --git a/schema/triggers/join_policy_acceptances.sql b/schema/triggers/join_policy_acceptances.sql deleted file mode 100644 index e3baa7b247..0000000000 --- a/schema/triggers/join_policy_acceptances.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('join_policy_acceptances'); diff --git a/schema/triggers/moderation_actions.sql b/schema/triggers/moderation_actions.sql deleted file mode 100644 index a87bc0965b..0000000000 --- a/schema/triggers/moderation_actions.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('moderation_actions'); diff --git a/schema/triggers/moderation_reports.sql b/schema/triggers/moderation_reports.sql deleted file mode 100644 index 3755e4bdc8..0000000000 --- a/schema/triggers/moderation_reports.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('moderation_reports'); diff --git a/schema/triggers/parameterized_event_watermarks.sql b/schema/triggers/parameterized_event_watermarks.sql deleted file mode 100644 index 678759eff8..0000000000 --- a/schema/triggers/parameterized_event_watermarks.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('parameterized_event_watermarks'); diff --git a/schema/triggers/personal_read_accounts.sql b/schema/triggers/personal_read_accounts.sql deleted file mode 100644 index f8eef31200..0000000000 --- a/schema/triggers/personal_read_accounts.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('personal_read_accounts'); diff --git a/schema/triggers/personal_read_frontiers.sql b/schema/triggers/personal_read_frontiers.sql deleted file mode 100644 index 4655135502..0000000000 --- a/schema/triggers/personal_read_frontiers.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('personal_read_frontiers'); diff --git a/schema/triggers/pubkey_allowlist.sql b/schema/triggers/pubkey_allowlist.sql deleted file mode 100644 index 358256108c..0000000000 --- a/schema/triggers/pubkey_allowlist.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('pubkey_allowlist'); diff --git a/schema/triggers/push_leases.sql b/schema/triggers/push_leases.sql deleted file mode 100644 index 307e25e622..0000000000 --- a/schema/triggers/push_leases.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('push_leases'); diff --git a/schema/triggers/push_match_queue.sql b/schema/triggers/push_match_queue.sql deleted file mode 100644 index 57e3085077..0000000000 --- a/schema/triggers/push_match_queue.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('push_match_queue'); diff --git a/schema/triggers/push_wake_outbox.sql b/schema/triggers/push_wake_outbox.sql deleted file mode 100644 index b544ce5136..0000000000 --- a/schema/triggers/push_wake_outbox.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('push_wake_outbox'); diff --git a/schema/triggers/reactions.sql b/schema/triggers/reactions.sql deleted file mode 100644 index 8d51e860be..0000000000 --- a/schema/triggers/reactions.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('reactions'); diff --git a/schema/triggers/relay_invites.sql b/schema/triggers/relay_invites.sql deleted file mode 100644 index d6f658a54c..0000000000 --- a/schema/triggers/relay_invites.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('relay_invites'); diff --git a/schema/triggers/relay_members.sql b/schema/triggers/relay_members.sql deleted file mode 100644 index 1a4018a69c..0000000000 --- a/schema/triggers/relay_members.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('relay_members'); diff --git a/schema/triggers/scheduled_workflow_fires.sql b/schema/triggers/scheduled_workflow_fires.sql deleted file mode 100644 index 24ba3a936e..0000000000 --- a/schema/triggers/scheduled_workflow_fires.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('scheduled_workflow_fires'); diff --git a/schema/triggers/subscriptions.sql b/schema/triggers/subscriptions.sql deleted file mode 100644 index a9d80ddfdc..0000000000 --- a/schema/triggers/subscriptions.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('subscriptions'); diff --git a/schema/triggers/thread_metadata.sql b/schema/triggers/thread_metadata.sql deleted file mode 100644 index 68e53007dc..0000000000 --- a/schema/triggers/thread_metadata.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('thread_metadata'); diff --git a/schema/triggers/users.sql b/schema/triggers/users.sql deleted file mode 100644 index 5f65f3c763..0000000000 --- a/schema/triggers/users.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('users'); diff --git a/schema/triggers/workflow_approvals.sql b/schema/triggers/workflow_approvals.sql deleted file mode 100644 index 58b616f3cc..0000000000 --- a/schema/triggers/workflow_approvals.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('workflow_approvals'); diff --git a/schema/triggers/workflow_runs.sql b/schema/triggers/workflow_runs.sql deleted file mode 100644 index 5c9f54ed86..0000000000 --- a/schema/triggers/workflow_runs.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('workflow_runs'); diff --git a/schema/triggers/workflows.sql b/schema/triggers/workflows.sql deleted file mode 100644 index 9a136a071e..0000000000 --- a/schema/triggers/workflows.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT attach_community_write_fence('workflows'); diff --git a/scripts/backfill-d-tag.sql b/scripts/backfill-d-tag.sql deleted file mode 100644 index 8684accbf9..0000000000 --- a/scripts/backfill-d-tag.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Backfill d_tag for existing NIP-33 range events (kind 30000–39999). --- Idempotent: only updates rows where d_tag is still NULL. --- Includes soft-deleted rows so the column is fully populated. --- Run once after adding the d_tag column to the events table. --- --- Usage: psql $DATABASE_URL -f scripts/backfill-d-tag.sql - -UPDATE events -SET d_tag = COALESCE( - (SELECT elem->>1 - FROM jsonb_array_elements(tags) AS elem - WHERE elem->>0 = 'd' - LIMIT 1), - '' -) -WHERE kind BETWEEN 30000 AND 39999 - AND d_tag IS NULL; diff --git a/scripts/cutover/README.md b/scripts/cutover/README.md index 92fd2e0ff8..354870e124 100644 --- a/scripts/cutover/README.md +++ b/scripts/cutover/README.md @@ -30,9 +30,9 @@ steady-state path unless explicitly reviewed. replica-floor shared/exclusive lock ordering). - If a workflow cannot use those protocols yet, execute it under an explicitly reviewed procedure that keeps replica routing fences closed for the run. -- Existing trigger/function backstops remain the commit-time authority during - this transition. Their removal requires separate coverage and fleet gates; - this cutover does not authorize it. +- Community writes use application admission and the deletion-lock protocol. + Retained trigger/function guards remain authoritative for their invariants; + this cutover does not authorize their removal. - Role separation is deliberate: schema reconciliation scripts carry schema convergence only; serving admission/fencing semantics remain in runtime/store code paths with startup verification and metrics. diff --git a/scripts/reconcile-schema-after-pgschema.sql b/scripts/reconcile-schema-after-pgschema.sql index 0c84398aa3..04bd8e557a 100644 --- a/scripts/reconcile-schema-after-pgschema.sql +++ b/scripts/reconcile-schema-after-pgschema.sql @@ -16,8 +16,6 @@ BEGIN -- pgschema may copy parent triggers onto standalone children. Drop -- those copies before ATTACH; PostgreSQL recreates inherited parent -- triggers while attaching and rejects same-named child triggers. - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p_past; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p_past; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p_past; ALTER TABLE events ATTACH PARTITION events_p_past FOR VALUES FROM (MINVALUE) TO ('2026-01-01'); @@ -28,8 +26,6 @@ BEGIN WHERE inhparent = 'events'::regclass AND inhrelid = 'events_p2026_01'::regclass ) THEN - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_01; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p2026_01; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p2026_01; ALTER TABLE events ATTACH PARTITION events_p2026_01 FOR VALUES FROM ('2026-01-01') TO ('2026-02-01'); @@ -40,8 +36,6 @@ BEGIN WHERE inhparent = 'events'::regclass AND inhrelid = 'events_p2026_02'::regclass ) THEN - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_02; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p2026_02; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p2026_02; ALTER TABLE events ATTACH PARTITION events_p2026_02 FOR VALUES FROM ('2026-02-01') TO ('2026-03-01'); @@ -52,8 +46,6 @@ BEGIN WHERE inhparent = 'events'::regclass AND inhrelid = 'events_p2026_03'::regclass ) THEN - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_03; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p2026_03; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p2026_03; ALTER TABLE events ATTACH PARTITION events_p2026_03 FOR VALUES FROM ('2026-03-01') TO ('2026-04-01'); @@ -64,8 +56,6 @@ BEGIN WHERE inhparent = 'events'::regclass AND inhrelid = 'events_p2026_04'::regclass ) THEN - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_04; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p2026_04; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p2026_04; ALTER TABLE events ATTACH PARTITION events_p2026_04 FOR VALUES FROM ('2026-04-01') TO ('2026-05-01'); @@ -76,8 +66,6 @@ BEGIN WHERE inhparent = 'events'::regclass AND inhrelid = 'events_p2026_05'::regclass ) THEN - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_05; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p2026_05; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p2026_05; ALTER TABLE events ATTACH PARTITION events_p2026_05 FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); @@ -88,8 +76,6 @@ BEGIN WHERE inhparent = 'events'::regclass AND inhrelid = 'events_p2026_06'::regclass ) THEN - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p2026_06; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p2026_06; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p2026_06; ALTER TABLE events ATTACH PARTITION events_p2026_06 FOR VALUES FROM ('2026-06-01') TO ('2026-07-01'); @@ -100,8 +86,6 @@ BEGIN WHERE inhparent = 'events'::regclass AND inhrelid = 'events_p_future'::regclass ) THEN - DROP TRIGGER IF EXISTS events_created_at_floor ON events_p_future; - DROP TRIGGER IF EXISTS community_write_fence_events ON events_p_future; DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot ON events_p_future; ALTER TABLE events ATTACH PARTITION events_p_future FOR VALUES FROM ('2026-07-01') TO (MAXVALUE); @@ -120,7 +104,6 @@ BEGIN AND inhrelid = 'delivery_log_p_past'::regclass ) THEN ALTER TABLE delivery_log_p_past ALTER COLUMN id DROP IDENTITY IF EXISTS; - DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log_p_past; ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p_past FOR VALUES FROM (MINVALUE) TO ('2026-03-01'); END IF; @@ -131,7 +114,6 @@ BEGIN AND inhrelid = 'delivery_log_p2026_03'::regclass ) THEN ALTER TABLE delivery_log_p2026_03 ALTER COLUMN id DROP IDENTITY IF EXISTS; - DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log_p2026_03; ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_03 FOR VALUES FROM ('2026-03-01') TO ('2026-04-01'); END IF; @@ -142,7 +124,6 @@ BEGIN AND inhrelid = 'delivery_log_p2026_04'::regclass ) THEN ALTER TABLE delivery_log_p2026_04 ALTER COLUMN id DROP IDENTITY IF EXISTS; - DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log_p2026_04; ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_04 FOR VALUES FROM ('2026-04-01') TO ('2026-05-01'); END IF; @@ -153,7 +134,6 @@ BEGIN AND inhrelid = 'delivery_log_p2026_05'::regclass ) THEN ALTER TABLE delivery_log_p2026_05 ALTER COLUMN id DROP IDENTITY IF EXISTS; - DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log_p2026_05; ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_05 FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); END IF; @@ -164,7 +144,6 @@ BEGIN AND inhrelid = 'delivery_log_p2026_06'::regclass ) THEN ALTER TABLE delivery_log_p2026_06 ALTER COLUMN id DROP IDENTITY IF EXISTS; - DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log_p2026_06; ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p2026_06 FOR VALUES FROM ('2026-06-01') TO ('2026-07-01'); END IF; @@ -175,7 +154,6 @@ BEGIN AND inhrelid = 'delivery_log_p_future'::regclass ) THEN ALTER TABLE delivery_log_p_future ALTER COLUMN id DROP IDENTITY IF EXISTS; - DROP TRIGGER IF EXISTS community_write_fence_delivery_log ON delivery_log_p_future; ALTER TABLE delivery_log ATTACH PARTITION delivery_log_p_future FOR VALUES FROM ('2026-07-01') TO (MAXVALUE); END IF;