Commit Graph

10 Commits

Author SHA1 Message Date
Luke Tornquist
af8287d961 Fail CI on new triggers, functions, rules and foreign keys (#9812)
## Summary

Migrations up to `0104` dropped every trigger, function and foreign key.
`docs/database.md` Rules 1 and 2 forbid adding them back, but nothing
enforced that. This PR adds the guard.

- **Migration lint.**
`migrations_after_retirement_add_no_triggers_functions_or_foreign_keys`
scans each migration numbered after `0104`. It fails on `CREATE [OR
REPLACE] FUNCTION | PROCEDURE | TRIGGER | RULE`, `CREATE CONSTRAINT
TRIGGER`, `CREATE EVENT TRIGGER`, `REFERENCES` and `FOREIGN KEY`,
outside `--` comments. The error names the file and line, for example
`migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION`. Nested `/*
*/` comments are skipped. Quoted identifiers and string values are data,
except a string passed to `EXECUTE` or `format(`. Each dollar-quoted
body is scanned as SQL up to its closing delimiter, so DDL run through
`EXECUTE` in a `DO` block is caught, and an apostrophe inside `$$...$$`
cannot hide the rest of the file. It runs in the infra-free `buzz-db
--lib` unit lane.
- **Schema file check.**
`desired_state_schema_layout_is_complete_and_schemabot_shaped` allows
`schema/` files only under `tables/public/`, `types/`, `partitions/` and
`seeds/`, and runs the same scan on every file. A `functions/` or
`triggers/` file, or an inline `REFERENCES` in a table file, fails it.
- **Catalog check.**
`admin_schema_parity_between_desired_state_and_migrations` now asserts
that both bootstrap paths (pgschema + reconcile, and all migrations)
have zero non-internal triggers, event triggers, `public` functions and
procedures, rules and foreign keys. Extension members (pgcrypto) are
excluded. No allowlist is needed: main with all 104 migrations applied
has none of these objects.

Main now has `0105`, which passes the lint. Open PRs that add a
migration only need to renumber to `0106` or later. The two open ones
(https://github.com/block/buzz/pull/9621 and
https://github.com/block/buzz/pull/9690) add no forbidden object.

### What got simpler

- The parity test's per-table trigger comparisons (`events`,
`event_mentions`, and the five tables `0096` unguarded) and its separate
foreign-key check are replaced by one zero-object assertion.
- The scoped-key lint no longer parses foreign keys. None may exist, so
checking that they lead with `community_id` is dead logic.
- `schema/schema.sql` drops its empty `-- functions` and `-- triggers`
sections. Its header and `docs/database.md` stop describing `functions/`
and `triggers/` directories that no longer exist, and the doc's
"remaining triggers stay as a backstop" text now says they are gone.

### Checklist (`docs/database.md`)

- [x] Phase: none. Test and docs change only. No migration and no
runtime code.
- [x] No trigger, function, procedure, rule or foreign key is added.
- [x] No migration mutates rows.
- [x] Rule 4 locations: no schema change. `schema/schema.sql` changes
only comments.

### Related issue

None found.

### Testing

Run on a Linux workstation with PostgreSQL 17 at `b7254f90`, before the
review fixes. CI passed with the first review fixes at `0fed6b1b`.
`9749e618` adds dollar-quote, nested `EXECUTE $tag$` and `$1` cases to
`schema_object_lint_reports_each_construct_with_its_line`, and CI checks
it.

- `cargo fmt --check` and `cargo clippy -p buzz-db --all-targets -D
warnings`: pass.
- `cargo test -p buzz-db --lib` and `cargo nextest run -p buzz-db
--lib`: 223 passed.
- `scripts/postgres-test-run.sh` for
`admin_schema_parity_between_desired_state_and_migrations`,
`migrated_catalog_retires_universal_fences_but_keeps_deletion_guards`
and `pgschema_reapply_keeps_runtime_partitions`: 3 passed.
- Proof the lint can fail: a temporary `migrations/0105_probe.sql` with
a function and a `REFERENCES` column fails the lint with
`migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION` and
`migrations/0105_probe.sql:3: REFERENCES`.
- Proof the catalog check can fail: a temporary `0105` that creates
`probe()` fails the parity test with `the migrations leave a trigger,
function, rule or foreign key`, `left: ["function probe()"]`.
- The catalog on main at `9c0bcd62`, with all 104 migrations applied
through psql, has no triggers, functions, foreign keys, rules or event
triggers.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:56:50 -05:00
Luke Tornquist
7e94503fe9 Stop using the unused delivery_log and subscriptions tables (#9746)
## Summary

`delivery_log` and `subscriptions` came with the initial schema for a
delivery feature that was never built. No code has ever written to them.
This PR removes every reader, writer, partition-manager entry and
deletion selection, so a follow-up contract migration can drop both
tables (`docs/database.md` Rule 5: drop only after the release that
stops using a table is fully deployed).

- **Partition manager:** manages `events` only. It no longer creates or
audits `delivery_log` partitions.
- **User deletion:** the content, account and profile handlers no longer
select, delete or recheck rows in either table.
- **Community deletion:** both tables move from
`EXPECTED_SCOPED_TABLES`/`PURGE_SCOPED_TABLES` to a new
`RETIRING_SCOPED_TABLES` list. The catalog accepts each one present or
absent. The purge deletes its rows only while it exists.
`validate_approved_schema` accepts a frozen retiring table that has
since been dropped, and no other missing table. Without this, every
community deletion would fail its exact catalog check once the tables
are gone.
- **Docs:** a short "Retiring a tenant-owned table" section in
`docs/database.md`, plus partition-monitoring and cleanup docs.

The tables, their schema files, `.pgschemaignore` entries and the
partition primary-key lint exception stay until the drop migration.

### Rollout

1. Deploy this release to every relay, deletion executor and operator
CLI. Older binaries fail community deletion's exact catalog check after
the drop.
2. Then ship the drop migration and remove the schema entries. Operators
with external tooling that expects `delivery_log` to exist must update
it first.

The partition audit stops emitting `buzz_partition_audit_*` series with
`table="delivery_log"`. Alerts keyed on that label will go quiet.

### What got simpler

Two tables' worth of code paths are gone: partition management, the
audit, and five deletion handlers stop special-casing them. The
follow-up removes the tables and the `RETIRING_SCOPED_TABLES` entries.

### Testing

On a remote workstation at `3675ff17`: `cargo fmt --check`, `clippy -D
warnings` for buzz-db, buzz-deletion and buzz-relay (all targets), unit
tests for buzz-db (lib and tests), buzz-deletion and buzz-relay bins,
and `scripts/postgres-test-run.sh` for buzz-db
partition/deletion/migration tests (294 passed) and all buzz-deletion
Postgres tests (44 passed). The new tests cover: retiring tables purged
and verified while present; a request inventoried before a real `DROP
TABLE` still purges and verifies; `validate_approved_schema` tolerates
only retiring tables vanishing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:19:15 -05:00
Luke Tornquist
729cb10b78 buzz-db: drop the remaining relay foreign keys (#9740) 2026-11-19 17:51:45 -05:00
Luke Tornquist
379b501124 feat(push-gateway): declarative desired-state schema, one file per table (#8328)
## Summary

Gives the push gateway a declarative desired-state schema in the same
layout the relay uses since #8131: a `\i` manifest plus one file per
table, the shape SchemaBot reads.

- `crates/buzz-push-gateway/schema/schema.sql`: an ordered `\i` manifest
and nothing else.
- `crates/buzz-push-gateway/schema/tables/public/<table>.sql`: the end
state of migrations `0001`–`0008` for all six gateway tables. That
includes `0007`'s `installations.platform` column and `0008`'s dropped
delegation → installation foreign key (#9610), so the delegation table
declares no `REFERENCES`. Each file holds only its `CREATE TABLE` and
plain `CREATE [UNIQUE] INDEX` statements.
- `src/postgres.rs`: the six table names are now one `GATEWAY_TABLES`
constant shared by readiness and the runtime-role GRANT, instead of two
hand-copied lists.
- `src/postgres/desired_schema_postgres_tests.rs` adds two tests:
- `desired_state_schema_layout_is_complete_and_schemabot_shaped` (no
infra needed). It checks that the manifest includes every file exactly
once and holds only `\i` lines, that each table file creates exactly one
table, and that indexes use a plain `CREATE INDEX` on that table.
- `desired_state_schema_matches_migrations` (PostgreSQL lane). It builds
one probe database from `schema.sql` through the real `bin/pgschema
apply` and another through `GATEWAY_MIGRATOR`. It then requires the two
`public` catalogs to match: table set, columns from `pg_attribute` (full
type with typmod via `format_type`, default, nullability, identity,
generation, collation), table options (persistence, RLS flags,
`reloptions`), constraints (`pg_get_constraintdef`) and index shapes
(`pg_get_indexdef` + `indoption`). Neither probe may hold functions,
non-internal triggers, policies, views, sequences or user types, and the
declared table set must equal `GATEWAY_TABLES`. It compares the whole
`public` catalog, not a list of tables, so a future migration that
changes `public` tables, columns, table options, constraints or indexes
without a matching `schema/` change fails CI. It doesn't cover data-only
migrations or objects outside `public` (other schemas, roles, database
settings). Probe databases are created from `template0` and dropped even
when an assertion, `pgschema` or setup fails; the original failure is
re-raised unchanged. Connection details, including the password, come
from the resolved `PgConnectOptions`, so percent-encoded credentials,
`?password=` and Unix-socket URLs reach `pgschema` the way SQLx sees
them. `pgschema` 1.7.4 builds an unquoted keyword DSN, so a password or
socket path with whitespace, a quote, `=` or a backslash isn't supported
(noted in the test).

## Not changed

The gateway still migrates itself at startup: bootstrap guard, then SQLx
migrations, then runtime-role grants. The guard and grants are
operational steps, not desired-state DDL, so they stay in code. No
`schemabot.yaml` is added: SchemaBot isn't configured for the relay or
the gateway yet, so the yaml for both waits until that server-side setup
exists. The manifest header notes that the relay's post-pgschema
reconcile step (root `AGENTS.md` gotcha #7) doesn't apply, because the
gateway schema has no seed DML or storage parameters.

SchemaBot compatibility is not proven here. The parity test shows the
files are equivalent under `pgschema`. Since #9610 the gateway schema
has no foreign keys, so the earlier inline-FK caveat is gone.
`docs/database.md` Rule 4 now lists the gateway `schema/` directory as a
schema location.

## What got simpler

To read the gateway's schema today you have to replay eight migrations:
two CHECK rewrites, two dropped UNIQUE constraints, a dropped column, an
added column and a dropped foreign key. After this PR it's one
declarative file per table, in the same convention as the relay. There
is no new runtime path and no new abstraction, and the duplicated table
list in `postgres.rs` collapses to one constant.

## Testing

At `c4336392` (rebased on main after #9610; mirrors gateway
`0007`/`0008`; reads the `pgschema` password from a copy with a URL-safe
host and username, so a `PGHOST` or default-search socket no longer
panics and a `/role` username no longer drops the password):

- `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway
--all-targets -- -D warnings`: pass.
- `cargo test -p buzz-push-gateway --lib desired_schema`: pass,
including
`resolved_password_reads_through_a_socket_host_and_slash_username`.
Removing the username normalization makes that test fail.
- `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`:
17/17 passed, including `desired_state_schema_matches_migrations`.

At `df3ff104` (password from resolved connect options), same
workstation:

- fmt, clippy (`-D warnings`, with and without
`personal-dev-app-attest`): pass. `cargo nextest run -p
buzz-push-gateway`: 80/80, and 82/82 with the feature.
`scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`:
13/13.
- `?password=`: with `PGPASSWORD` unset,
`postgres://<role>:wrong@localhost/postgres?password=<encoded
p@ss:w/rd#x>` passes the parity test, so `pgschema` gets the
query-parameter password that SQLx uses. A wrong `?password=` is
rejected (`28P01`).
- The CHECK-bound falsification still fails with `constraint parity
mismatch`. Every run leaves 0 probe databases.

At `f937924a` (probe cleanup and connection-URL follow-up), on a Linux
workstation against PostgreSQL 16 with the repo's pinned `bin/pgschema`:

- `cargo fmt --all -- --check`, plus `cargo clippy -p buzz-push-gateway
--all-targets -- -D warnings` with and without `--features
personal-dev-app-attest`: pass.
- `cargo nextest run -p buzz-push-gateway`: 60/60 passed, and 62/62 with
`personal-dev-app-attest`. `scripts/postgres-test-run.sh -p
buzz-push-gateway --lib --tests`: 12/12 passed.
- Probe cleanup: with a CHECK bound changed (2048→4096), the previous
test code fails and leaves both `push_gateway_{desired,migrated}_*`
databases behind. The new code fails with the same `constraint parity
mismatch` panic and leaves none. A table file that makes `pgschema
apply` fail (`no_such_column`) also reports `pgschema apply failed: ...
column "no_such_column" does not exist` and leaves none.
- Connection URLs: the parity test passes as a role whose password is
`p@ss:w/rd#%x`, given percent-encoded in the URL with `PGPASSWORD`
unset. It also passes over
`postgres://<user>@%2Fvar%2Frun%2Fpostgresql:5432/postgres` (Unix
socket, peer auth).

Earlier, at `ee2745cb78`:

- `scripts/postgres-test-packages.sh` discovers `buzz-push-gateway`. The
parity test lives under a `*_postgres_tests` module so the `postgres-ci`
nextest filter selects it.
- `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway
--all-targets -- -D warnings` both pass.
- `cargo nextest run -p buzz-push-gateway`: 60/60 passed, including the
layout test.
- `scripts/postgres-test-run.sh -p buzz-push-gateway`: 12/12 passed,
including `desired_state_schema_matches_migrations`.
- Falsification checks:
- Dropping the partial predicate from
`push_gateway_installations_active_token` makes the parity test fail
with an index-shape mismatch.
- Adding an unmirrored `0007` migration (`ADD COLUMN probe TEXT`) makes
the parity test fail with a column mismatch. Mirroring the column in the
table file makes it pass again.
- Putting `CREATE TABLE` DDL in `schema.sql` makes the layout test fail.
- A `0007` adding `probe VARCHAR(64)` mirrored as `VARCHAR(128)` fails
with a column mismatch (typmod); mirroring it exactly passes.
- An unmirrored `0007` `ALTER COLUMN expires_at TYPE TIMESTAMP` fails
with a column mismatch.
- An unmirrored `0007` `ENABLE ROW LEVEL SECURITY` fails with a
table-option mismatch.
- A `0007` creating a function and trigger fails the "only tables and
indexes" check.

Known gap: `sqlx::migrate!` doesn't notice a *new* migration file on an
incremental build. The crate has no `build.rs` `rerun-if-changed`, and
neither does any other crate in the workspace. For the `0007` check
above I touched `src/postgres.rs` to force the macro to re-expand. Clean
CI builds aren't affected.





buzz-review-completed

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:50:39 -05:00
Luke Tornquist
598fcae0cd buzz-db: drop the created_at floor, community write-fence and migration-only NIP-RS triggers (contract) (#8326)
> **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 <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:49:29 -05:00
Phil Azar
db7d37107a Keep community deletion working across a new tenant table's migration (#9304)
## Why

The deletion engine compares the live set of `community_id` tables with
an exact list. An expand migration that adds a tenant table therefore
breaks community deletion for every community on the release that is
deployed. It breaks again after a rollback to that release. #9301's
migration 0087 adds three such tables.

I reproduced this with the actual `buzz-admin` from #9301's merge-base
(`838976d6e`):
- Once 0087 is applied, that binary blocks every deletion with `catalog
drift (missing=, unknown=identity_retirement_actions,…)`.
- A request it approved before 0087 then fails permanently on #9301 too,
with `approved structural catalog drifted before fencing`.

A short gap between migrating and deploying doesn't make this
compatible, so this release has to ship first.

## What

- **`PENDING_SCOPED_TABLES`**: tables a later migration adds (the three
identity retirement tables).
  - The catalog check accepts each of them whether it exists or not.
  - Purge and logical verification handle every one that is present.
- The lookup runs inside the transaction that uses it, under the shared
schema/destruction lock that migrations take exclusively.
- **`APPROVAL_FORWARD_TABLES`**: a bounded exception to the
approved-catalog check in `validate_approved_schema`.
- A live table missing from the frozen inventory is accepted only if it
is on this list. The list names only tables this binary purges and
verifies.
- A removed frozen table is still rejected before fencing, and so is any
other addition.
  - The frozen manifest and digest are never rewritten.
- Unlike `EXPECTED_SCOPED_TABLES`, a table stays on this list after the
release that ships it moves it into the required catalog.
- **`docs/database.md`**:
- The table row for a new tenant table now requires this precursor
release instead of "keep the gap short".
  - The checklist adds the matching step.
  - A paragraph documents the approval exception.

#9301 is rebased onto this branch: it moves the three tables to the
required catalog, empties `PENDING_SCOPED_TABLES`, and keeps
`APPROVAL_FORWARD_TABLES`.

## Evidence

All local runs, at head `21df5ece3` (on main `dd9da3ac6`).

**Postgres lane** (`scripts/postgres-test-run.sh -p buzz-db -p
buzz-deletion --lib --tests`): 782 passed, 258 skipped.

**Store test** `pending_scoped_tables_are_optional_purged_and_verified`:
- The catalog is accepted with the tables both absent and present.
- An unknown table fails.
- Purge deletes one target row per pending table.
- A straggler row fails verification and names its table.
- The bystander's rows survive.

**Executor test** `approval_before_an_expand_migration_completes`:
- It is in `external_infra_s3_tests` and needs Postgres, Redis and S3.
CI doesn't run it; I ran it locally against MinIO.
- It drives `execute_claim` on a request approved before the tables
exist, through `RetentionPending`.
- Target rows are gone and bystander rows survive.
- An unlisted added table blocks the request before fencing.
- A request whose frozen inventory includes the pending tables is
blocked before fencing once those tables are dropped, with `approved
structural catalog drifted`.
- The test runs in a scratch database of its own, because it changes the
catalog.

**Falsification**: each of these mutations makes the executor test fail.
- An exact approval comparison (the approved-legacy test fails too).
- Swapping the forward list for `EXPECTED_SCOPED_TABLES` (the
approved-legacy test fails too).
- Purge skipping the pending tables.
- Removing the catalog tolerance.
- Ignoring removed frozen tables.

The other S3 executor tests: `drained_stage…` and `final_storage…` pass.
`approved_stage_allows_post_inventory_row_churn_before_fencing` fails
here, and it fails the same way on `838976d6e`.

**CLI exercise**, kept separate from the store tests. These are real
`buzz-admin` binaries on a scratch database with local Redis and MinIO:
- R0 is `838976d6e` (pre-feature), R1 is this branch, R2 is #9301
rebased onto it.

| Step | Result |
|---|---|
| R0 migrates to 0086, then submits and approves c1, c2, c3 and c8 |
`approved`, with 0 of 36 frozen tables being retirement tables |
| R2 migrator applies 0087 and 0088 | at 88 |
| Retirement-shaped rows inserted for targets c1, c2, c5, c6 and
bystander c4 | 3 rows each |
| R0 runs c8 | blocked, unknown identity retirement tables (below the
floor) |
| Unknown `compat_unknown_scoped` table present: R1 runs c3, then R2
runs c3 | both blocked (`unknown=compat_unknown_scoped`), `fence=none` |
| R1 runs R0-approved c1 | `retention_pending` |
| R2 runs R0-approved c2 | `retention_pending` |
| R2 approves c5 (3 of 39 frozen tables are retirement tables), R1 runs
it | `retention_pending` |
| Rows afterwards | c1, c2, c5: 0; bystander c4: 3 |
| R2 approves c6, the three tables are dropped, R1 runs c6 | blocked,
`approved structural catalog drifted before fencing`, `fence=none` |

**R1 relay restart after 0087**, with `BUZZ_AUTO_MIGRATE=false`: the
relay starts, readiness returns 200, and it serves NIP-11 for a
configured community.

With auto-migration on, the same restart fails with `migration 87 was
previously applied but is missing`. That is the existing Rule 5
limitation, and this PR doesn't fix it. Operators keep auto-migration
off through the rollout.

**Agent review**: an independent review found one blocker. The executor
test changed the shared test database's catalog and left the tables
behind. It now uses its own database. The review's optional findings on
doc wording, checklist placement and removed-table executor coverage are
also addressed.

## Limits

- The migration of a later release still has to be applied with the
documented migrator, which holds the schema lock.
- A human has not tested this yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Philip Azar <pazar@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:57:23 -06:00
Luke Tornquist
745f7dac7c buzz-db: build the community deletion lock key in Rust (#9396)
## What

This is phase 1 of 2 for retiring the SQL function
`community_deletion_lock_key(uuid)`. Every relay caller now builds the
lock name in Rust, with
`buzz_db::deletion::community_deletion_lock_key(CommunityId) -> String`.
It then locks with the built-in `hashtextextended($1, 0)`, the same
pattern the other advisory locks here use (`channel_ttl_lock_key`,
`push_gate_lock_key`). The string is byte-for-byte the one the function
hashes (`'buzz-community-deletion:' || target::text`), so the lock is
identical. Old and new relays, and the fence functions still in the
database (`community_write_allowed`, `assert_community_write_allowed`),
keep excluding each other during a rolling deploy.

- **Production callers:** exclusive `lock_community_deletion`, shared
`lock_community_deletion_shared`, and the bulk shared lock in
`bind_nip_fi_issuers_to_active`. The bulk lock now binds a `text[]` of
keys, sorted by community id in Rust and locked `WITH ORDINALITY`. That
keeps the old `ORDER BY id` lock order, because `Uuid` and Postgres
`uuid` both compare bytewise.
- **Startup check:** `validate_serving_catalog_on` no longer requires
the function to exist, so the phase-2 drop can't make this release
refuse to serve or delete.
- **Tests and docs:** test lock holders use the helper.
`docs/database.md` gives repair scripts the inline expression, which
keeps working after the drop.
- The test-schema shims in `api/bridge.rs` and `handlers/ingest.rs`
stay. Test schemas still copy the fence functions that call the
function.

**Phase 2 (not here):** a migration and desired-state change drops the
function after this release is fully deployed and the fence functions
are gone (#8323). It also removes the two test shims.

## Tests

-
`deletion::postgres_tests::community_deletion_lock_key_matches_the_sql_function`
checks that `hashtextextended(rust_key, 0)` equals
`community_deletion_lock_key(uuid)` for the nil UUID, the max UUID and
64 random ones.
- `migration_schema_fence_objects_are_optional_for_serving_and_deletion`
already drops the universal fence objects by hand. It now also drops
`community_deletion_lock_key(UUID)`. With both present and absent, it
runs the startup and readiness checks, serving leases (shared lock),
`bind_nip_fi_issuers_to_active` (bulk shared lock) and
`lock_community_deletion` (exclusive lock).

Must-fail mutants, each run on Blox against its guarding test: a changed
key prefix, the shared, exclusive and bulk locks reverted to the SQL
function, and the startup check requiring the function again.

## What got simpler

No relay code path calls a database function to build this lock any
more. The key has one definition in Rust instead of one in SQL plus
about 20 SQL call sites. One fewer object stands between the schema and
declarative-only management (`docs/database.md` Rule 1).

## Verification

Blox, at `3020a44148d942f1502395640730cd0548a76400` (clean tree):

| Gate | Result |
|---|---|
| `cargo fmt --all --check` | pass |
| `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings` |
pass |
| `cargo nextest run -p buzz-db --lib` | 214/214 |
| `scripts/postgres-test-run.sh -p buzz-db --lib` over
`deletion::postgres_tests`, `nip_fi_binding::postgres_tests` and the
reaction and channel-member lock tests | 101/101 |
| Must-fail mutants (prefix, shared, exclusive, bulk, startup check) |
5/5 killed |

CI runs the full Postgres lanes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


buzz-review-completed

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:34:23 -05:00
Luke Tornquist
ff15c347c2 fix(db): auto-migrate prebuild-guarded indexes on small databases (#8802)
## Problem

Migrations `0076`, `0078` and `0081` raise an exception on any table
with at least one row unless its index was prebuilt with `CREATE INDEX
CONCURRENTLY`. A relay that runs migrations at startup
(`BUZZ_AUTO_MIGRATE`, on by default in the Helm chart) and has data in
those tables therefore crash-loops on upgrade:

```
migration error: while executing migration 81: error returned from database:
prebuild idx_nip_fi_profile_heads_names concurrently; see docs/profile-search.md
```

`0081` (#9019) hits every auto-migrating relay that has published NIP-FI
verified profiles. `0076`/`0078` (#8523) hit any relay with artifact
data or channel members. Each of these tables is small enough on such
relays that a plain index build takes milliseconds.

The root cause is `docs/database.md` Rule 6. It told authors that an
index on a populated table MUST be built concurrently by an operator
ahead of time, so migrations were written to refuse populated tables.
With auto-migration that refusal is a crash loop, not a safe stop.

## Fix

The migrations are already applied on some databases, so they can't be
edited: sqlx would reject the changed checksums. Instead,
`run_migrations_locked` builds their missing indexes first. For each
entry in `INLINE_INDEX_BUILDS` (`0076`, `0078`, `0081`), it runs
migrations through the version before it, then builds any missing index.

Each build is a plain `CREATE INDEX` in its own transaction, under the
same 1s `lock_timeout` and 5s `statement_timeout` the migrations use.
That is the bounded inline build `0049` already does:

- **Small populated databases** upgrade the same way empty ones do.
- **Large databases** still fail closed. Only a lock or statement
timeout (`55P03` / `57014`) gets the "prebuild concurrently" hint,
pointing at that migration's own doc. Other errors pass through
unchanged. The blocked migration is not recorded.
- **Prebuilt indexes** are found with `to_regclass` and skipped before
`CREATE INDEX`, so deployments that prebuilt concurrently never request
the writer-conflicting lock.
- **Invalid prebuilt indexes** are left for the migration to reject, as
before.

`CONCURRENTLY` is not used in this path. The runner holds the migration
advisory lock, and another replica blocked on that lock holds a snapshot
that a concurrent build would wait on.

### Rules

- `docs/database.md` Rule 6: with `BUZZ_AUTO_MIGRATE` on, every
migration must apply its own change on a populated database and must
never refuse one because it has rows. A new index is built inline under
the migration's budgets. Only deployments that apply migrations out of
band (auto-migration off) prebuild concurrently.
- Root `AGENTS.md` (step 4) and `migrations/AGENTS.md` repeat the
never-refuse rule.
- `docs/artifact-sync-deployment.md` and `docs/profile-search.md`
describe the startup behavior first and the concurrent prebuild as the
out-of-band path.

## Tests

- `populated_database_auto_migrates_through_every_migration` (Postgres)
migrates to `0075`, seeds artifact rows, and checks four phases:
1. **Lock held:** while a writer lock is held, the `0076` build fails
closed.
2. **Index prebuilt:** with the `0076` index prebuilt, the build is
skipped.
3. **Partial `0078`:** a blocked `0078` build keeps the builds before it
committed.
4. **Verified profile seeded:** with a verified profile head inserted
before `0081`, a final startup succeeds. It asserts that the applied
versions equal every embedded migration and that all six indexes are
valid, ready and live.
- `frozen_prebuild_guards_have_inline_builds` (no database) scans
`migrations/`. It fails if any migration refuses a populated table
(`RAISE EXCEPTION 'prebuild …`) without an inline build, and if a new
guard is added.
- `migration_execution_cannot_bypass_schema_destruction_lock` allows
exactly one production `run_to`, inside `run_migrations_locked`.

## What got simpler

- Auto-migrating relays no longer need a manual, operator-only prebuild
step for small deployments. That restores the chart README's contract
that `helm upgrade` is the whole upgrade procedure.
- Rule 6 no longer steers authors toward refusing populated tables, and
a test enforces that.
- The change adds one table-driven step for three frozen migrations and
no new configuration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 13:52:06 -05:00
ngoodger-block
f33ebaafa1 refactor(schema): stop auto-fencing new tables in desired-state bootstrap (#8620)
### Why?

This is a cleanup that brings the schema bootstrap in line with how the
codebase works today, as asked for by
[`docs/database.md`](dc25198d53/docs/database.md (L103-L124))
(#8273). Writes are now blocked during community deletion by application
admission (`begin_community_write_transaction`), and that doc's Rule 1
says new tables must not add triggers. But
`schema/community_write_fence.sql` still looped over every table with a
`community_id` column and attached the old fence trigger to it. That
meant a new table got a trigger on a fresh database and none on a
migrated one, so the two schema paths disagreed and new tenant tables
were blocked. The doc says this bootstrap change must land "before the
feature, or as the feature's first PR."

### What?

Deletes the blanket fence loop and its `\i` from `schema/schema.sql`.
Existing legacy tables keep their fences through their explicit
`schema/triggers/` files, so no current table loses its fence and
runtime behavior is unchanged. Adds a test that a new `community_id`
table stays unfenced while `events` and `users` stay fenced, and updates
`docs/database.md` and `ARCHITECTURE.md` to match. It stands on its own;
the media-sharing PRs (#8451, #8444) are the first to rely on it.

buzz-review-completed

---------

Signed-off-by: Nikolaj Goodger <ngoodger@squareup.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 09:26:41 +11:00
Luke Tornquist
fcdabcf774 docs(db): database target architecture and schema-change rules (#8273)
## Summary

Adds `docs/database.md`, which covers two things:

- **The target architecture.** `schema/tables/public/` is the
declarative source of truth, written within the constraints that
out-of-band, online schema tools can apply. Deployments at scale apply
schema changes out of band; auto-migration stays supported for smaller
and self-hosted deployments, and `migrations/` stays. The database has
no triggers, functions, or foreign keys; that behavior lives in the
owning application transaction or in durable application work. Data
repair runs through the backfill framework in `docs/data-backfills.md`,
not through migrations.
- **Rules for schema changes made now:**
1. Add no triggers, functions, procedures, rules, or foreign keys, with
no exceptions. New tenant-owned tables are fenced by community admission
in the application. Startup and deletion validation already tolerate
missing fences, but desired-state bootstraps still attach a fence
trigger to every `community_id` table, so a new tenant-owned table is
blocked until that loop stops (part of the fence-retirement work). The
doc includes checklists for adding a tenant-owned table and a
provenance-only table.
2. Migrations change schema only. They never mutate existing rows. Until
the backfill framework ships, a repair may be a reviewed, idempotent,
batched one-off script in `scripts/maintenance/` that takes the
community deletion lock and touches only active communities. A repair
that writes historical channel events must keep replica routing closed
until its WAL has replayed.
3. Update every schema location: `migrations/`, `schema/tables/public/`,
the manifest and sibling directories, the pgschema reconcile script
where it applies, and both homes of the existing `push_gateway_*` tables
(the target is for the gateway to own its tables alone). Never edit a
merged migration. Add catalog-level parity tests for what you touch.
4. Every migration must be safe for the relay that is currently
deployed, under both supported modes: auto-migration at startup and
out-of-band application. Either way the old relay runs against the new
schema for a while. Because auto-migration can apply expand and contract
in one boot, a contract migration must fail closed when its backfill has
not run, and a contract that depends on a writer release (such as
dropping a trigger whose work moved into the app) must name that release
as a required stop in the release notes, because no row check can prove
it. The order is expand, deploy, backfill, then contract. The doc
includes a table of changes that break the old relay and the safe form
of each.
5. Bound every lock, build `migrations/` indexes concurrently (the
declarative schema uses plain `CREATE INDEX`), and keep changes within
what out-of-band apply can make online.

AGENTS.md (Product Contract), ARCHITECTURE.md (buzz-db), and new
path-local `migrations/AGENTS.md`, `schema/AGENTS.md` (a pointer), and
`crates/buzz-push-gateway/migrations/AGENTS.md` point to the doc. The
path-local files mean agents editing those directories get the rules
automatically. AGENTS.md also had a stale claim that migrations are
"auto-applied on relay startup". This PR corrects it:
`BUZZ_AUTO_MIGRATE` defaults off in the binary and on in the Helm chart,
and both modes are supported.

## What got simpler

The rules were scattered across `schema/schema.sql` comments, AGENTS.md
Common Gotcha #7, the backfill spec, `docs/thread-window-deployment.md`,
and test names. They now live in one document, and the rest link to it.
No code changes.

## Testing

This PR changes documentation only. I checked links and diffs, and every
claim in the doc points to code at the base commit: the layout and
parity tests in `crates/buzz-db/src/runtime/migration.rs`,
`EXPECTED_SCOPED_TABLES` and the serving-catalog check in
`crates/buzz-db/src/store/deletion.rs`, and `BUZZ_AUTO_MIGRATE` in
`crates/buzz-relay/src/main.rs`. The new `AGENTS.md` files aren't
`.sql`, so neither the sqlx migrator nor the schema layout test picks
them up; CI's layout, migration-count, and deletion-parity tests pass.

At an earlier head, a real relay against isolated PostgreSQL 17 showed
that a new unfenced `community_id` table serves normally and makes
community deletion report `unknown=<table>`. Since then, the fence
requirement at startup was removed on main; the doc now cites
`migration_schema_fence_objects_are_optional_for_serving_and_deletion`
for that.

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
2026-10-20 15:47:05 -04:00