mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
286095c9374e5acbaab0f9cc102fb85ad93d393b
6 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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`](
|
||
|
|
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> |