mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
008d72a133a83ffdbff68c8dbd42a1d8dbfde844
1005 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
008d72a133 |
test(relay): stop bridge cancel_fixture tests timing out on the first replica connect (#9691)
## Problem All seven tests that share `cancel_fixture` in `crates/buzz-relay/src/api/bridge.rs` got a replica pool with a 1 s `acquire_timeout`. Only `shed_history_read_maps_to_503_on_every_bridge_branch` needs that budget: it holds the replica full and measures how fast a read sheds. sqlx applies `acquire_timeout` to opening connections as well as to waiting for a free one, so the budget also governed the fixture's initial connect and every later acquire that had to open a connection. A transient Postgres stall on the shared CI server therefore failed tests that never hold the replica full. CI showed `connect scratch: PoolTimedOut` at `bridge.rs:10309` in `aborted_history_read_logs_events_already_queued` and `failed_history_read_closes_and_reconnect_replays_the_history` (run 44205074529 shows eight tests finishing together after a ~3 s gap, which is the stall). Pools with sqlx's 30 s default waited the stall out; the 1 s replica did not. No connection leaked and the pool was not too small. The replica's 300 ms database-level `statement_timeout` had the same flaw: migrations and seeding ran under it, so a stall during setup failed `seed community` with 57014. ## Fix (test code only) - The six non-shed tests now use default pool budgets. - Only the shed test asks for the short budget, via `budgeted_reader`. That helper pre-opens all of the reader pool's connections under the 30 s default, and does not ping on acquire, so the 1 s budget covers only the wait for a free connection. - sqlx still pings each connection on release and closes it if the ping fails, so `budgeted_reader` waits until `num_idle()` equals `max_connections` before returning. A fill-and-drain loop (acquire to `max_connections`, drop, re-check) reopens any connection a failed release ping closed, under one 30 s deadline, and panics with the `N of M idle` count if the deadline passes. - The replica's `statement_timeout` is applied after migrations and seeding, and the replica is reopened so new sessions pick it up. - The shed test asserts each shed `/query` case completes in under 10 s, so a silent fallback to the 30 s default fails instead of passing slowly. ## Verification Reproduced locally by pausing the Postgres container for 2 s at random intervals while running `api::bridge::postgres_tests` at CI's 8 threads: `connect scratch: PoolTimedOut` appeared in 1 of 4 runs before the fix and in 0 of 8 after. With the fix, the 62 bridge postgres tests passed at 8 threads against a local Postgres (`--ignored`, including the shed, statement-cancel, and both history-read tests). `cargo fmt` is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: mtoohey <mtoohey@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a406191694 |
Revert "feat(relay): support community-scoped NIP-AR artifacts" (#9689)
Reverts #9650 (squash commit `eebf62b6`), except for migration `0097` and the channel artifact sync fences it added. Community scope adds a relay access gate based on community admission rather than channel membership, a new relay-admin command kind (`9034`) and an operator-run key transition. Its design and NIP-AR text need relay maintainer review before they ship. Two integration gaps also remain: - Media download authorization looks up references only in `events`, so an attachment referenced only by a community artifact is unreadable when media-read enforcement is on. - User erasure retires a community head in the database without signaling live syncs, so members who are already syncing keep the erased copy. The feature can return as a new PR once those are resolved. ## Kept from #9650 - **Migration `0097`, byte for byte.** Published images already include it, and databases that auto-migrated have recorded it. Dropping it would stop those relays from starting. It only adds columns and indexes that the channel code ignores. The declared schema matches that expanded shape and keeps the `(community_id, artifact_id)` primary key, so the operator key transition no longer exists. - **Channel artifact sync fences.** Snapshot and live sends check for a pending resync and for connection cancellation under the queue lock. A reader who loses access, or whose content is redacted, while a frame is in flight therefore receives no further payload. Handler-backed tests cover a resync recorded while a snapshot payload waits for queue room and one recorded after a live head read. ## Compatibility This revert supports databases that applied only migration `0097`, which is all that auto-migration runs. A database that ran #9650's operator contract script, or was bootstrapped from #9650's declared schema, has no `(community_id, artifact_id)` key, so channel artifact writes fail there. Before deploying to such a database, check that `artifact_heads_pkey` is on `(community_id, artifact_id)` and that `artifact_heads` has no rows with `scope = 'community'`; if either check fails, it needs a separate recovery step. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz> |
||
|
|
db40da87b4 |
feat(relay): add conditional Solo member role updates (#9667)
**Category:** improvement **User Impact:** Solo chat owners can lower the access of any current non-owner, including people and agents. **Problem:** Using invitations to change Solo chat access can restore a removed member, reject a downgrade because of the target’s invitation policy, or show a join notice for a role change. **Solution:** Add signed role updates that require an active member at the expected role when the relay commits the change. A Solo owner can downgrade any current non-owner. Moving a viewer to Participating requires a verified agent, and granting Admin requires ownership of that agent. The relay refreshes signed group state without emitting a join notice. Companion to [block/buzz-app#3704](https://github.com/block/buzz-app/pull/3704). The [app review](https://github.com/block/buzz-app/pull/3704#pullrequestreview-5962147206) identified the need for conditional writes, verified agent identity and live relay validation. [#9592](https://github.com/block/buzz/pull/9592) introduced the atomic removal that uses the same membership lock. <details> <summary>File changes</summary> **crates/buzz-core/src/kind.rs** Register signed Solo role updates as kind 9050. **crates/buzz-db/src/store/channel_members.rs** Authorize the transition under the channel membership lock and commit the active row update and signed event together. **crates/buzz-relay/src/handlers/event.rs** Give the new command a bounded metrics label. **crates/buzz-relay/src/handlers/ingest.rs** Use the shared signed ingest path and require the channel administration scope. **crates/buzz-relay/src/handlers/mod.rs** Register the command handler and its PostgreSQL test. **crates/buzz-relay/src/handlers/solo_member_role.rs** Parse the command, route it to the conditional write, and refresh signed group state after commit. **crates/buzz-relay/src/handlers/solo_member_role_postgres_tests.rs** Exercise human and agent changes, restrictive invitation policy, promotion authorization, stale and removed membership, duplicate receipt, and signed roster updates through the relay’s production ingest path. **docs/solo-mobile-contract.md** Describe the wire format, permitted transitions, and handling when an older relay rejects the command. </details> ### Try it 1. Run the updated relay and the companion app against a disposable Solo chat with a current human and agent. Open **Chat access** as the owner. 2. Lower the human to **Viewing only**. Reopen **Chat access** and confirm the saved role. A role change should produce no join notice. 3. Downgrade an agent with a restrictive invitation policy. Confirm its role changes. Check that **Admin** can be granted only to your own verified agent. 4. Run `solo_owner_edits_active_members_and_publishes_the_new_roster` with PostgreSQL to check that a pending change for a removed member is refused and the signed roster stays clear of that member. ### Validation - The PostgreSQL regression passes at relay commit `405f7d1da`. It covers role and invite-policy enforcement, signed roster refresh, duplicate receipts, and rejection after removal. - The companion app at `a470947dc6` passes 138 administration tests. Its production command builder, validator, and signed roster reader also passed over WebSocket against a local relay backed by PostgreSQL and Redis. A human moved from Admin to Participating to Viewing only, then was removed. The app preflight and relay both refused a further role edit, and the signed roster still excluded the member. - The live check exercised the app’s relay code headlessly. The UI walkthrough is pending. --------- Signed-off-by: Taylor Ho <taylorkmho@gmail.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
eebf62b61d |
feat(relay): support community-scoped NIP-AR artifacts (#9650)
## Summary NIP-AR clients can store community-scoped artifacts and subscribe to live changes for one exact artifact type. Community and channel artifacts share revision and retry semantics and use separate identity scopes. Community owners and admins can choose whether a type accepts edits from all admitted members or only administrators. This PR combines the protocol from #9638 with the relay implementation. [Protocol]( |
||
|
|
44e97e96f4 |
fix(pubsub): round the rate-limit retry hint up from PTTL (#9552)
## Summary The Redis rate limiter built its `retry in Ns` hint from `TTL`, which truncates to whole seconds. With 400 ms left in the window, a denied request was told `retry in 0s`, and a client that sleeps for exactly the hint retried straight into another refusal. This reads `PTTL` and rounds the milliseconds up to whole seconds, so the hint is never 0 while the window is still open. The no-expiry repair path is unchanged. ## Testing - New `rate_limiter::tests::retry_hint_rounds_a_partial_second_up` (`#[ignore = "requires Redis"]`, like the other Redis tests in this crate) seeds an exhausted window with 400 ms left and asserts the denial reports 1 second. Against the old `TTL` code it fails with `left: 0, right: 1`; with this change it passes. - `cargo nextest run -p buzz-pubsub --lib`: 38 passed. Ignored Redis `rate_limiter` and `nip98_replay` tests: 5 passed against a local Redis. - `cargo nextest run -p buzz-relay --lib` with local Postgres and Redis: 1762 passed. The relay `rejection::`/`admission::` lane with `--run-ignored all`: 16 passed. - Pre-push hooks (including rust-tests) passed. CI note: the Redis-backed pubsub tests only run in CI when they are named in `.github/workflows/_ci-relay.yml`, so the new test isn't selected there yet. Adding `or test(/^rate_limiter::tests::/)` to the "Pubsub subscriber reconciliation regression" filter would cover it. I left that out here because this branch can't push workflow file changes. --------- Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz> Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz> |
||
|
|
8d613ce0e8 |
test(relay): refresh the author's membership cache after the stray-h private channel insert (#9640)
Fixes `handlers::ingest::postgres_tests::reaction_and_deletion_h_must_name_the_target_channel`, which fails on main in the PostgreSQL Tests jobs. The test creates its private channel directly in the database after the author has already published, so the per-user membership cache (`is_member_cached`) still holds the author's snapshot from before that channel existed. The author's post to the new channel is then refused with `restricted: not a channel member`. The test now drops the author's cached membership after the insert, so the channel's owner is seen as a member. The test's assertions are unchanged. Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
7cf19b713c |
perf(db): bound deep keyset history pages by the cursor timestamp (#9549)
## Problem `query_events` and `get_channel_window` page history with a composite `(until, before_id)` cursor under `ORDER BY created_at DESC, id ASC`. The cursor predicate was only: ```sql created_at < $u OR (created_at = $u AND id > $bid) ``` PostgreSQL cannot use that OR as the start of an index range, so a page deep in a channel walks the `(community_id, channel_id, created_at DESC, id)` index from the newest row and filters every newer row before it reaches the page. The cost of a page grows with its depth. ## Fix Add the redundant bound `created_at <= $u` next to the OR in both queries (`store/event.rs` and `store/thread.rs`). It does not change which rows match; it gives the planner an `Index Cond` range start at the cursor. This is the same bound the thread window query already carries (`store/thread_window.rs`). `api/bridge.rs` has the pattern only in a test fake that emulates `query_events_on`; the bridge itself routes cursors into these two store functions, so it needs no change. ## EXPLAIN before / after `EXPLAIN (ANALYZE, BUFFERS)` of the `query_events` page shape, `LIMIT 51`, kind 9, by cursor depth. Copy of a real channel (2,277 messages), custom plan, shared buffers hit: | Depth | Before | After | | ---: | ---: | ---: | | 50 | 96 | 96 | | 300 | 311 | 84 | | 1,000 | 969 | 80 | | 1,500 | 1,443 | 92 | | 2,100 | 2,006 | 89 | At depth 2,100: execution 0.709 ms to 0.058 ms, rows removed by filter 2,101 to 42. With a generic plan the after numbers are also flat (80 to 96 buffers at every depth). Synthetic table (one channel with 20,000 kind-9 rows plus 20 other channels of 2,000 each): | Query | Depth | Before | After | | --- | ---: | ---: | ---: | | `query_events`, custom plan | 10,000 | 701 | 11 | | `query_events`, generic plan | 50 | 874 (7.5 ms) | 11 (0.11 ms) | | `query_events`, generic plan | 10,000 | 444 | 11 | | `get_channel_window`, custom plan | 10,000 | 1,006 (2.35 ms) | 312 (0.49 ms) | | `get_channel_window`, custom plan | 19,940 | 1,690 (4.35 ms) | 314 (0.47 ms) | For `get_channel_window` at depth 19,940 the events index scan went from 1,385 buffers and 19,941 rows removed by filter to 9 buffers and 4 rows; the rest of its plan is the thread metadata join, which is unchanged. On the small 2,277-row channel the planner picks a sequential or bitmap scan for the window query, so its plan is unchanged there. ## Tests New Postgres test `store::event::postgres_tests::deep_keyset_pages_read_from_the_cursor`: - Inserts 1,000 kind-9 rows into one channel, two per second, so the cursor lands on same-second ties. - Turns off sequential and bitmap scans for the session, so the small fixture uses the ordered index walk a large channel uses, then reads one 50-row page at depth 900 through both `query_events_on` and `get_channel_window_on`. It asserts each page equals the expected rows and that each read touched at most 150 event rows (summed `seq_tup_read + idx_tup_fetch` over the `events` partitions). - Pages the whole channel through both paths and asserts every row comes back once, in order. Checked by reverting each half of the fix: - `event.rs` bound removed: `events page at depth 900 read 950 rows for 50` - `thread.rs` bound removed: `window page at depth 900 read 1000 rows for 50` - With the fix: passes (5 of 5 under `--stress-count 5`), reading 52 and 53 rows. Runs: - `scripts/postgres-test-run.sh -p buzz-db --lib --tests`: 763 run, 756 passed. The 7 failures were the new test before its final fixture change (it now passes) and 6 that fail the same way on unmodified `main` in my environment because they spawn a host `psql` binary that isn't installed there: `migration_schema_media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`, `script_stops_at_the_first_auth_refusal`, `script_renames_each_planned_channel_once_whatever_its_name`, `desired_event_follow_up_contract_app_only`, `desired_event_follow_up_contract_dual`, `migration_schema_event_follow_up_contract_app_only`. CI's Postgres lane is the authoritative run for those. - On the final head: the new test plus every `channel_window` Postgres test, 9 of 9 passed. - `cargo nextest run -p buzz-db --lib` (no infrastructure): 216 passed. `--test observability_source`: 28 passed. Doc tests: 5 passed. - `scripts/test-postgres-test-discovery.sh`: passed. - Pre-push `rust-tests` lane: passed. ## How to test 1. Run `scripts/postgres-test-run.sh -p buzz-db --lib -E 'test(deep_keyset_pages_read_from_the_cursor)'`. 2. Optionally, in a database with a channel of a few thousand messages, open the channel in a client and scroll back through history. Older pages should load as quickly as the first ones, and no message should be skipped or repeated across page boundaries. ## Related No duplicate PR or issue found. Related: #1787 (keyset index for thread replies) and #6004 (CLI wiring for the composite cursors). Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz> |
||
|
|
11970789eb |
feat(cli)!: consistent channels list/get/search output (type, visibility, labels, real created_at) (#9617)
Closes #6390 ## Summary `buzz channels list`, `get` and `search` each projected kind:39000 channel metadata differently. `list`/`get` dropped the classification tags, so a script couldn't tell a Solo chat from a stream or a private channel from an open one. The three commands also disagreed on field names, defaults and empty values, and `created_at` reported the last-edit time (#6390). All three now print one `ChannelSummary`, with `pubkey` added on `get`: | Field | Source | |---|---| | `channel_id`, `name` | `d`, `name` tags | | `channel_type` | first `t` tag (`stream`, `forum`, `dm`, `workflow`, `system`) | | `visibility` | `open` for `["public"]`, `private` for `["private"]` | | `labels` | the `t` tags after the first, e.g. `["buzz.solo"]` | | `archived` | `["archived","true"]` | | `description` | NIP-29 `about` tag | | `topic`, `purpose`, `ttl_seconds` | `topic`, `purpose`, `ttl` tags | | `created_at` | the channel's `created_at` tag (NIP-CL), or `null` when absent | | `updated_at` | the event's own `created_at`, which is the last metadata change | Compact `list` output (`{channel_id, name}`) is unchanged. ### Breaking output changes These are intentional, and they were discussed with a maintainer before this change: - **`search`:** `about` is renamed `description`, matching `list`/`get` and `create`/`update --description`. - **`list`/`get`/`search`:** `created_at` is now the real creation time. The old value, the last-edit time, moves to the new `updated_at`. - **`list`:** archived channels are hidden by default, as `search` already did. The new `--include-archived` flag shows them. `get --channel <id>` still returns an archived channel. `--limit` (and `--visibility`) count the channels printed: `list` reads past filtered channels, bounded by `MAX_QUERY_PAGES` on the default path and by 10,000 memberships with `--member`. - **Missing values:** they print `null` instead of `""`. This mainly affects `description`. - **`visibility`:** it prints `open`/`private`, the values `--visibility` takes, instead of the raw `public` tag. `search` printed `public` before. No in-repo consumer reads the renamed fields or the `public` value. The benchmarks read `search`'s `channel_type`, `visibility == "private"`, `archived` and `ttl_seconds`, all of which are unchanged. ### Related - Closes #6390. - Overlaps with #5664 and draft #6353, which add type and visibility to `list`/`get`. This PR covers both: it uses `open` like #6353, plus labels, archived, parity and the `created_at` fix. A maintainer may want to close them as superseded. Unlike #6353, it doesn't error on missing or contradictory visibility tags, so one malformed channel can't fail a whole `list`. ### Testing - `cargo test -p buzz-cli`: 699 passed. Clippy is clean. The tests build events from the captured `test-fixtures/solo-creation.json` identity tags and pin the full JSON shape, including the all-`null` case. They also cover the production `listed_channels` and `search_matches` filters: archived hiding, `--visibility`, and search's name and ID requirement and ordering. - An agent ran the changed commands against a live relay: - `get` and `search --exact` return identical fields for the same channel. - Over 2,000 channels, `list` hides 162 archived channels unless `--include-archived` is passed. - `--visibility open` returns only `open` channels. - 1,777 channels have `created_at < updated_at`. - No `description` is `""`. - Compact output is unchanged. - `list --limit 10` and `--member --limit 5` return exactly 10 and 5 non-archived channels, and `--limit 2000` returns 2,000 with none archived. - An independent agent review found no blockers. Its one cheap nit, `get` printing `pubkey: ""`, now prints `null`. - The pre-push workspace `rust-tests` lane was skipped for this push. When the push was made, `origin/main` didn't compile `buzz-db`'s lib tests, which is unrelated to this `crates/buzz-cli`-only diff. That breakage has since been fixed on main, so CI runs the full workspace. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Jemiah Westerman <jemiah@squareup.com> Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
493cb4cc13 |
perf(db): stop per-id planning of wide #e reads (#9591)
Thread pages fetch the reactions, edits and deletions of ~200 ids at once. Until a pooled connection has run that `#e` read about five times, Postgres plans it with the values: ~12 ms per plan (one estimate per id per partition) against ~2 ms to run it. Past 8 ids the arrays now go through a scalar subquery, so planning is one estimate (~1.5 ms) and still uses the tags GIN index; narrower reads are unchanged. On an 830-reply local thread, one viewer's full scan drops from 119 to 59 ms p50; with 50 viewers p50 holds at 242 ms, p99 drops from 664 to 413 ms, and the read's planning time falls from 13 s to 0.6 s per minute. --------- Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> |
||
|
|
25b58ab98f |
feat(push-gateway): verify Android Key Attestation (#9562)
## What and why Ticket 3 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now verifies Android Key Attestation at enrollment instead of rejecting every Android chain, and rate limits signed installation calls per attested key. Stacked on [#9560](https://github.com/block/buzz/pull/9560) (Android enrollment and FCM wakes). This PR's base is that branch; it will be retargeted once that merges. - **Chain.** It must end at a configured Google attestation root (Google's [published hardware roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate) are built in, pinned by public key), with valid signatures and issuer links, CA issuers above the attestation key certificate, and no SHA-1 signatures. The attestation key certificate itself is exempt from the CA flags, because some factory keyboxes issue it with CA:FALSE and digitalSignature only (Google's Sony Xperia 10 III sample); a Keystore leaf still cannot act as an issuer, since the extension is refused above the leaf. Validity is enforced for Remote Key Provisioning chains; Google tells verifiers to keep trusting the long-expired factory chains, which the revocation list covers instead. The attestation extension must be in the leaf and nowhere else. The leaf key must be EC P-256; it becomes the installation's signing key. - **KeyDescription.** Attestation and KeyMint security levels must be TrustedEnvironment or StrongBox. The challenge must equal SHA-256 of the enrollment transcript. Key properties (generated, EC, P-256, sign-only) and the root of trust come only from the hardware-enforced list. The bootloader must be locked, and the boot state Verified, or SelfSigned with a verified boot key on an operator-configured list. The application id (the one software-enforced value) must name exactly the configured package with a configured signing digest. - **Revocation.** A background task fetches Google's status list at startup and then on its cache lifetime (5 minutes to 1 day), with a 30 second timeout, an 8 MiB size cap, capped exponential backoff and jitter. Any REVOKED or SUSPENDED serial in the chain is rejected. With no list yet, or a list older than the grace period, enrollment fails closed. Enrollment reads an in-memory snapshot and never waits on a fetch. - **Rate limit.** Signed installation calls (delegate, revoke delegation, rotate endpoint, revoke installation, on both platforms) are limited per attested key. A call is counted only after its signature verifies, so forged requests cannot spend another installation's allowance. Counters are in memory per replica, bounded to 100,000 keys. - **Dependencies.** None added. `x509-parser` gains its `verify-aws` feature, which uses the `aws-lc-rs` the crate already depends on. ## Configuration All optional; Android stays off unless the ticket 2 settings are present. Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only, and passed through `deploy/charts/buzz-push-gateway` (disabled by default, schema-checked, covered by `tests/runtime-options.sh`). - `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS`: SHA-256 digests of verified boot keys accepted with a SelfSigned boot state. Empty by default, so a default gateway accepts stock Android only. - `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`: PEM bundle replacing the built-in roots, for a reviewed root rollout. In the chart, `android.attestationRoots.secretName` and `secretKey` mount it from a Secret; an empty name keeps the built-in roots. - `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS`: default 604800 (7 days), minimum 3600. - `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS` and `BUZZ_PUSH_SIGNED_CALL_MAX_CALLS`: defaults 60 and 30. ## Tests - `cargo test -p buzz-push-gateway` (all pass, 18 ignored), `cargo fmt --all --check`, `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings`, and the chart tests (`render.sh`, `release-contract.sh`). - Key Attestation chains are generated in the tests with a test root injected as the configured root, and run through the production verifier. One table rejects: unlocked bootloader, Unverified, Failed, SelfSigned with an unlisted key, boot key only in the software list (two variants), key properties only in the software list, extra key purposes, wrong curve, wrong package, two packages, wrong signing digest, wrong challenge, software-backed key (two variants), unknown root, forged leaf signature, expired provisioned intermediate, extension repeated above the leaf, non-P-256 leaf, a CA:FALSE certificate issuing the attestation key certificate. Another accepts Verified with any boot key, SelfSigned with a listed key, StrongBox and TrustedEnvironment, an expired factory intermediate, and a CA:FALSE, digitalSignature attestation key certificate. Revoked leaf, intermediate and root, a missing list and a stale list are rejected. The status list parser and refresh (backoff, cap, keeping the last list through failures) run against a scripted fake source; no test touches the network. - The per-key rate limit runs through the public router: forged calls do not spend the allowance, the fourth authentic call is refused whatever its kind, and another installation is unaffected. - Break check: disabling the locked-bootloader guard and the rate limit turned `rejected_attestations` and the rate limit test red; restored. ## Not here The app side (ticket 7) generates the Keystore key and sends the chain. The end to end run on a physical Android phone against a test gateway is also still to do. --------- Signed-off-by: Tom Brow <tomb@squareup.com> |
||
|
|
b769d5bee8 |
fix(relay): remove an owner's agents with the owner (#9575)
## What this changes When someone is removed from a community, their agents' live sessions already closed, but the agents kept their own membership rows and could reconnect as members. This PR removes those agents with their owner. - **Cascade.** `delete_member_with_acceptances` locks and deletes the target, then locks and deletes the `join_policy_acceptances` and `relay_members` rows of every member of the same community whose `users.agent_owner_pubkey` is the target and whose role is not `owner`. All of it runs in the same transaction, before the roster snapshot is written. Admin removal (kind 9031), self-leave and `buzz-admin remove-member` all go through it. An agent goes with its owner whatever its role, so an admin who removes a member also removes that member's admin-role agent. A direct 9031 target is still limited to `member` for admins. - **Owner recording.** The relay records a verified NIP-OA owner on every admitted sign-in, whatever the relay mode or `allow_nip_oa_auth`: on WebSocket AUTH, and for HTTP in the shared admission step after the denial checks, so `/events`, `/query`, `/count` and member POSTs all record it in one place. Before, it recorded only on open relays, so on closed relays the cascade and owner bans missed agents added directly. A request refused before recording writes nothing. Once the owner-signed tag is verified and the first admission checks pass, the relay may record the owner even if a final check, a cancellation or a token revocation then refuses the sign-in. The record still can't be changed. Over HTTP, a different stored owner refuses the request with 403 (invite creation keeps its `invite_owner_mismatch` code), and storage trouble refuses it with 503. A recorded owner can also manage the agent (channel management, channel-add policy, invites). - **CLI.** `buzz-admin remove-member` publishes clusterwide disconnects (`ConnControl::DisconnectPubkey`) for the target and its recorded agents on every run, including when the member is already gone. If publication fails or no relay server is subscribed, it exits 6 after the removal commits. Rerunning the same command retries the disconnect. - **Spec.** NIP-FI states the rule. ## Rollout limit An agent is covered only if its owner was recorded before the owner is removed. An agent whose owner was removed before the agent signed in with a NIP-OA tag after deploy, or an agent that never signs in with one, stays a member and needs a manual removal. The relay holds no proof of ownership for those agents, so there is nothing to backfill. Supersedes #6098 and #6078. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
4bf7d8a9b0 |
relay: refuse a reaction or deletion whose h names another channel (#9006)
## Summary A reaction, or a deletion that targets a message, belongs to the target message's channel. The relay works out that channel from the target and stores the event there. But every read and every live delivery matches the event's own channel (`h`) tags. So if a client puts a *different* channel in the `h` tag, the event is stored in one channel and only ever matches another: - No one ever receives it. - It still takes a slot when a client asks for "the latest N events" of the real channel. A catch-up can then return fewer events than exist while it looks complete, because the relay removes the stray event after it applies the limit. This is one of the known gaps in https://github.com/block/buzz-app/pull/2206. The relay now refuses such an event. The rule: | Event's `h` tags | Before | After | |---|---|---| | none | accepted | accepted | | include the target's channel | accepted | accepted | | only other channels | accepted, never delivered | refused | The refusal uses the same "target not found" text as the existing refusals for these kinds. So it tells the sender nothing about where the target is. No first-party client sends a mismatched `h`. buzz-app uses the target message's channel, and desktop, mobile and the SDK send no `h` on reactions. So no current client is affected. ### Details - The check covers kind:7 reactions and kind:5 deletions that name their target with an `e` tag. These are the two kinds whose channel comes from a target. A kind:5 that names an addressable event (`a` tag) is not affected. - The check runs only when the target is in a channel, so a reaction to a global event keeps any `h`. A tag must be the channel's UUID exactly as the relay writes it (lowercase, hyphenated), the same way `#h` filters match. - The check runs after the token, membership and archive checks. If it ran first, it would skip their database reads, and the response time could tell someone who cannot read a private channel whether a guessed `h` names the channel that holds a message. - Events already stored with a stray `h` are not changed. They can still take a slot under the limit. - NOSTR.md now says that an optional `#h` on these kinds must name the target's channel. It also says kind:5 takes its channel from its `#e` target (the old text said it used `#h`). ### Related issue None found. Follow-up to the known gaps listed in https://github.com/block/buzz-app/pull/2206. ### Testing - New `reaction_and_deletion_h_must_name_the_target_channel` test, as a member of the target's channel. A reaction whose `h` names only another channel is refused and not stored. A reaction with no `h`, or with both channels, is accepted, and so is a reaction with any `h` on a global event. A deletion of that reaction is refused and not stored with another channel's `h`. It is accepted with the target's `h` or with no `h`. A non-member's wrong guess still reaches the membership check. On a private channel, a right guess and a wrong guess both end at the same membership denial. - I removed the check, and the test failed. I also moved it back before the membership check, and the test failed. - On a local relay over WebSocket: the same refusals and acceptances, with the same messages, and a reaction to a global event keeps its `h`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Human test: Logan asked to take this to team review without a separate hand test (2026-11-17). buzz-review-completed Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> |
||
|
|
3876720c34 |
buzz-db: drop the five single-table guard triggers (BUZZ-318 phase 2) (#9398)
> [!NOTE] > **Rollout:** #8320 (app guards + catalog expand) is deployed, so the hold is lifted. With `autoMigrate=true`, `0096` runs at startup under a 5s lock timeout, and a failure stops startup. With `BUZZ_AUTO_MIGRATE=false`, deploy this binary first and then run `buzz-admin migrate`. Both orders are safe because the expand tolerates the objects being present or absent. ## What The required stop for `0096` is in `docs/trigger-retirement-deployment.md` (from #9622): a relay build at or after #8320 (`ec778bff`). A build older than that needs the tombstone trigger at startup and readiness. Migration `0096_drop_single_table_guards.sql` drops five triggers and their functions. #8320 moved each invariant into the application writers: | Trigger (table) | Function | |---|---| | `trg_channels_community_id_immutable` (channels) | `channels_community_id_immutable()` | | `communities_deletion_tombstone` (communities) | `enforce_community_tombstone()` | | `community_deletion_request_retargeting_guard` (community_deletion_requests) | `prevent_community_deletion_request_retargeting()` | | `community_deletion_approval_removal_guard` (community_deletion_approvals) | `prevent_community_deletion_approval_removal()` | | `community_deletion_manifest_keys_guard` (community_deletion_manifest_keys) | `protect_community_deletion_manifest_keys()` | Desired state (`schema/`) drops the five functions and four trigger files, plus the channels trigger declaration. The universal write fence on `channels` stays. Both boot paths stay catalog-equivalent: the pgschema-vs-migration parity check now also compares columns, key and FK shapes, and the remaining triggers on all five tables. Executor GUCs stay because `assert_community_write_allowed` still reads them through the universal write fence. `transition_community` and every phase-1 app guard are byte-identical to #8320. `scripts/reconcile-schema-after-pgschema.sql` has no entries for these objects. ## Tests - #8320's six `single_table_guard_*_without_trigger` PG tests no longer need to disable a trigger. They are now plain app-path tests with the same assertions. - New per-test regressions for the desired-template and migration boot paths assert that none of the ten objects exist, including disabled triggers and function overloads. - Deleted assertions that only exercised raw SQL against the triggers: retarget, rewrite and approval mutation, frozen-manifest rewrite, and tombstone DELETE. The app-path coverage for each remains. - The expand regression in #8320 migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, then validates again. - Rebased onto main `b568d9bf` after #8696 took `0095`; renumbered to `0096`. Blox gate at `7bda1f45`: fmt, clippy and buzz-db `--lib` pass; the PostgreSQL lane ran 219 tests, all pass. - Gate at `c8bc061c` (on main `051dd2d7`, then numbered `0095`, #9622 folded in): on Blox, `cargo fmt --check`, clippy and the buzz-db `--lib` tests pass. The PostgreSQL lane (migrations, single-table guards, floor retirement, fence and deletion) ran 208 tests: all pass. - Earlier gate at `0840ba49`: CI was green, and the Blox PostgreSQL lane passed 840 of 841 (the one failure, `media_reference_full_query_plans`, is a timing check that fails the same way on main on that host). - The rebase updates main's fence-retirement tests to expect the tombstone trigger gone. ## What got simpler Ten database behavior objects and nine desired-state files are gone (about 150 lines). Each rule has a single owner, the application writer. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
44cdd9feef |
push-gateway: lock expired installations before reaping (#9627)
## What The push gateway reaper deletes expired delegations and then expired installations in two statements. A delegation writer (`upsert_delegation`) that holds the installation lock can commit a new child between them. With the foreign key, the installation delete then fails, and the reap transaction rolls back. This PR locks the expired installations with `FOR UPDATE` first, as every authority mutation does. It then deletes their delegations and the installations by id. A writer that was holding the lock commits first, and the delete sees its child. A later writer finds the parent gone and is rejected. No schema change. This is the code half of #9610. The gateway image with this change must run everywhere before the delegation foreign key is dropped. ## Tests Blox at `20b66f8f`: fmt, clippy, and the push-gateway PostgreSQL tests (15/15) pass. - `reaper_deletes_delegation_committed_while_it_waits`: a writer holds the installation lock and inserts a child. The reaper starts and waits. The writer commits. The reaper deletes both rows. - `delegation_for_missing_installation_is_rejected`: `upsert_delegation` for an unknown installation returns `Rejected` and writes nothing. ## What got simpler The reaper now uses the same lock order as every other authority write. The child delete no longer needs a correlated subquery. buzz-review-completed 🤖 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> |
||
|
|
b568d9bf95 |
Retire the 0032 roster trigger in migration 0095 (#8696)
## Summary Migration 0095 drops the 0032 channel roster trigger (`trg_events_guard_channel_roster_snapshot`) and its function (`guard_channel_roster_snapshot()`). The trigger repeats a check that the relay already does in Rust. Every kind:39002 roster writer checks the roster against the channel's membership before it saves it (#8316). Since #8611, no relay requires the trigger at startup. This PR is the last step of the trigger retirement sequence in `docs/database.md`. This PR was split out of #8494 so the migration can roll out by itself. A relay from this PR does not change how it stores or publishes roles, and it has no new startup check. It serves correctly whether or not 0095 has run. #8494 stacks on this PR and must not merge until 0095 has run in every environment. ## Details - **Migration 0095.** `DROP TRIGGER` and `DROP FUNCTION`, with `lock_timeout = '1s'` and `statement_timeout = '5s'` as in 0049. `DROP TRIGGER` takes `ACCESS EXCLUSIVE` on each `events` partition in turn, so event reads and writes block while it runs. A timeout rolls it back with no change, and it can be retried. - **Desired-state schema.** `schema/functions/guard_channel_roster_snapshot.sql` is removed. This was the last trigger on `events`, so `schema/triggers/events.sql` and its include go too, as do the pre-attach trigger drops in `scripts/reconcile-schema-after-pgschema.sql`. - **Operator guide.** #8326 added `docs/trigger-retirement-deployment.md` for migrations 0089–0091. (0092 from #9365 and 0093 from #9560 drop nothing; 0094 from #9598 drops two plain SQL functions and has its own section there.) This PR adds 0095 to it: its row, the two ways an older relay fails, the migrate check, and the parent trigger a pgschema deployment must drop first. The Helm chart README names the required stop and points to that guide. - **Tests.** Tests that compared the trigger with the Rust check, or that disabled the trigger first, now test the Rust check alone. Tests that only exercised the trigger against a simulated pre-#8316 writer are removed. The 0075 invite upgrade test now migrates to 0075 exactly. ## Rollout **Required stop: the stop build in `docs/trigger-retirement-deployment.md`** (a relay build at or after `68785206`, the merge of #8325). That build contains #8316 (the app-side roster check) and #8611 (no startup trigger check), so it covers 0095 too. `relay-v0.3.0` contains #8316 and #8611 but not #8325, so it is no longer enough on its own: any build with 0095 also has 0089–0091. Without the stop, an untagged `main` build between 0032 and #8611 refuses to start once the trigger is gone, and a relay without #8316 can save stale kind:39002 snapshots (`docs/database.md` Rule 5). **Merge gate.** Every push to main publishes relay `:main` images, and the Helm chart defaults to `migrate.autoMigrate=true`. Do not merge this PR until the stop build or later runs on every serving and rollback target. That is the same gate #8326 had for 0089–0091. After that, either way works: - With `autoMigrate=true`, the first relay from this PR applies 0095 at startup. - With `autoMigrate=false`, run `buzz-admin migrate` when convenient. Relays from this PR serve with or without 0095. As with every new migration, an older binary with auto-migration on refuses a database that has 0095 (sqlx `VersionMissing`). A rollback past this release needs auto-migration off (`docs/database.md`). ## What happens next #8494 computes the `member`/`bot` label at read time. The 0032 trigger compares labels with the stored role exactly, so it would refuse those rosters. #8494 adds a startup check that refuses to serve while the trigger is installed. Merge it only after 0095 has run everywhere. ### Testing - `migration_0095_retires_the_roster_trigger`: on a database migrated through 0094, the trigger and function are installed. After the remaining migrations, both are gone, and a raw kind:39002 insert that does not match membership is accepted. It fails if 0095 does not drop them. - `embedded_migrator_contains_consolidated_initial_schema` pins 95 migrations and the 0095 statements, and checks that the desired-state schema no longer installs the function. - `migration_schema_desired_pgschema_reconcile_matches_populated_upgrade`: its fixture drops each retired parent trigger before pgschema runs (pgschema drops partition copies before the parent, which PostgreSQL refuses with 2BP01). It now drops the roster trigger too. - Locally at this head: `cargo check`, `cargo fmt --check`, and 245/245 buzz-db unit tests pass; 760/764 buzz-db Postgres tests pass. The four `event_follow_up_contract` tests fail the same way on `main` locally and pass in CI. CI runs clippy and the full PostgreSQL lane. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c01d3292a1 |
fix(db): hard-delete superseded relay-signed lists (#9586)
## Why
The relay republishes its own lists in full on every change:
- the NIP-43 membership list (kind 13534)
- the NIP-IA archived list (13535)
- NIP-29 group state (39000 metadata, 39001 admins, 39002 members)
Each write soft-deletes the previous head. No reader returns a
soft-deleted row, so each retired copy is dead weight in `events` and
its indexes. On the deployments we measured, these retired copies are
about 40–65% of monthly `events` growth. The NIP-33 path already
hard-deletes superseded NIP-RS read state and mesh status in the
replacing transaction. This PR applies the same rule to the relay-owned
lists.
## What
When a write supersedes a head of kind 13534, 13535, 39000, 39001, or
39002, it deletes the old head instead of soft-deleting it. The delete
runs in the same transaction, under the same scope and lock as before.
The change applies on the 3 paths the relay uses to write these kinds:
- `replace_addressable_event_under_lock` (13535, 39000, 39001, including
`buzz-admin` writes through `replace_addressable_event`). It gates on
the new `hard_deletes_superseded(kind)`. Other kinds on this path (0, 3,
10002, …) keep the soft delete.
- `LockedMemberSnapshot::replace_member_event` (39002).
- `write_nip43_membership_snapshot` (13534).
All 3 paths build their head read and supersede statement with one
function, `replacement_sql(in_channel, hard_delete)`, keyed by
`hard_deletes_superseded(kind)`.
Kind 13535 is now relay-only: ingest rejects a client-submitted 13535
with `restricted: relay-only kind`, as it already does for 13534. NIP-IA
defines 13535 as relay-signed, and every relay, desktop, CLI, and mobile
reader filters on the relay's pubkey. No client in this repository
publishes it.
The 39000–39002 paths already use `superseded_with_mentions_sql!`, so
the old head's mention rows are deleted with it, as before.
The gate checks the kind, not the signer, and every supersede is scoped
to the event's own pubkey. A client-signed 39000–39002 is routed to the
NIP-33 path, which keeps the soft delete. Channel deletion
(`soft_delete_discovery_events`) retires the live heads without a
replacement and still soft-deletes them.
This PR has no migration and no schema change.
## Why this is safe
- **Readers:** relay reads of these kinds filter on `deleted_at IS
NULL`, so a retired head was already invisible. One reader includes
soft-deleted rows: the admin event preview (`get_event_preview`). It
will now report a superseded roster id as absent instead of deleted. A
moderation report against an old version of a channel's metadata (for
example, a name it had before a rename) will show no target content. An
operator can no longer look up an old roster or membership list by id to
audit past membership. `docs/admin/README.md` now documents this for
`GET /api/admin/v1/events/{id}`.
- **Operator repair:** when `buzz-admin`'s group-state reconcile
overwrites a 39000–39002 head, the old row is gone, so an operator can
no longer restore it with `UPDATE … SET deleted_at = NULL`. The relay
rebuilds these lists from `channels` and `channel_members`, so no source
data is lost.
- **Replays:** while the coordinate has a live head, a replay of a
deleted head's id is still rejected, because its `created_at` does not
beat the live head's. With no live head (after channel deletion, for
example), the deleted row no longer makes the replay a duplicate. Only
the relay can submit these events: ingest requires the event's signer to
be the authenticated pubkey, 13534 is relay-only, and the relay's
writers sign a new event on every attempt. The existing tests for
soft-deleted replays seed their own rows and do not change.
- **13534 id uniqueness:** the writer still takes `max(created_at)` over
every stored list. The live head is always the newest, so the next
list's `created_at` still moves past every earlier one.
- **13535 strict stamps (NIP-IA, #9476):** each new archived list is
stamped past the live head, which the writer reads behind the
replacement lock. It never reads retired rows, so deleting them does not
change the next `created_at`.
- **Database objects:** no foreign key references `events`, and none of
these kinds is a push kind. The DELETE runs in the same admitted
community write transaction as the old UPDATE. The only trigger left on
`events` is the BEFORE INSERT kind 39002 roster guard
(`guard_channel_roster_snapshot`), and a DELETE does not fire it.
- **Rolling deploy (docs/database.md Rule 7):** old pods keep
soft-deleting and new pods delete. Both leave exactly one live head per
coordinate, under the same locks.
## Follow-up
Rows that are already soft-deleted stay. Rule 3 does not allow a
migration to delete them. A separate PR will add a
`scripts/maintenance/` repair script: bounded batches, the
community-deletion lock, and a validation query. An operator runs it
after this change is fully rolled out.
Not in this PR: the relay-signed NIP-DV DM visibility snapshot (kind
30622, `publish_dm_visibility_snapshot`) is written on the NIP-33 path
and still soft-deletes its superseded heads. We will measure its share
of `events` growth before we change it.
## QA focus
- **Each roster write keeps exactly one stored row.** Create a channel,
then add and remove members, change roles, and edit the metadata. For
each of 39000, 39001, and 39002, the channel must have exactly one
`events` row (live), not one live row plus retired ones. Do the same for
13534 (relay membership add, remove, and role change) and 13535 (`agents
archive` and unarchive).
- **Other kinds still soft-delete.** Replace a kind 0 profile or kind 3
contact list. The old row must stay, with `deleted_at` set.
- **Mention rows.** After a 39002 or 13535 replacement, `event_mentions`
has no rows for the deleted head's id.
- **Admin event preview.** Opening the id of a replaced roster now shows
the event as absent instead of deleted. Check that this is acceptable in
the admin UI, including a report filed against a channel's metadata
before a rename.
- **13535 `since` cache.** Archive and unarchive several times,
including at the same time. Each new list has a `created_at` later than
the one before. A mobile client that asks `since` its list's
`created_at` + 1 gets the newer list.
- **Client 13535 is rejected.** Publishing a kind 13535 signed by a user
key returns `restricted: relay-only kind`. Archive and unarchive (kinds
9035 and 9036) still work, and the relay still publishes its own 13535.
- **Channel deletion.** Deleting a channel still soft-deletes its live
39000–39002 heads. This path is unchanged.
- **Mixed-version rollout.** With an old and a new relay on one
database, each coordinate keeps exactly one live head. Rows that old
pods soft-deleted stay until the follow-up script runs.
- **Existing soft-deleted rows are not touched.** The disk-space gain
shows only in growth after deploy. The follow-up script cleans up the
backlog.
## Tests
- `only_relay_owned_lists_hard_delete_their_superseded_heads`: checks
the kind set, including the neighbours 13533, 13536, 38999, and 39003,
and negative kinds.
- `superseded_heads_drop_their_mention_rows` (Postgres) now expects the
old head to be gone for the 39002 member snapshot, 13535 (global), and
39000 (in a channel). A kind 3 contact list on the same addressable path
is the control: it must stay soft-deleted.
- `replacement_channel_predicate_is_an_index_condition` (Postgres) now
builds its statements with `replacement_sql`, the same function
production uses, for all 4 scope and retire-mode combinations. Before,
it checked hand-copied SQL. It checks that each `DELETE` seeks by
`channel_id` on every populated partition, as the `UPDATE` does.
- The 39002 and 13534 writers take their statements from
`replacement_sql` and `hard_deletes_superseded`, so the index-condition
test covers each statement production runs.
- `nip_ia_archived_list_is_relay_only` (buzz-core): 13535 is relay-only,
and the 9035 and 9036 requests are not.
- `test_client_submitted_nip_ia_archive_snapshots_are_rejected`
(buzz-test-client e2e, against a running relay): a client-signed 13535
is rejected with `restricted: relay-only kind` over both WebSocket and
HTTP. It shares a helper with the existing 13534 test. Against a relay
built without the 13535 gate, it fails at the WebSocket assertion. The
Relay E2E step in `.github/workflows/_ci-relay.yml` now selects it, next
to the 13534 test.
- `late_owner_link_closes_ownerless_agent_sockets_on_owner_revoke`
(buzz-relay, Postgres) copies selected tables into a private schema. The
13534 writer's supersede now also deletes the old list's
`event_mentions` rows, so the fixture copies `event_mentions` too.
- `every_membership_write_commits_its_list` (Postgres): after each
membership writer runs, the community stores exactly one kind 13534 row.
- `concurrent_archival_publishers_stamp_strictly_increasing_snapshots`
(buzz-relay, Postgres, from #9476) counted the 16 stored kind 13535
rows, superseded ones included. It now pins the head an hour ahead and
asserts that the coordinate stores exactly one row, at the pinned
`created_at` + 16 s. That holds only if each of the 16 publishers stored
exactly one snapshot, one second past the head it replaced. A
same-second replacement leaves the row short of + 16 s, and a publisher
that runs out of attempts still fails its `expect`.
- `a_publisher_that_read_before_an_edit_cannot_replace_it` (buzz-relay,
Postgres) counted retired kind 39000 rows to prove that each publisher
stores a new second. It now asserts that the coordinate stores exactly
one row, at the pinned `created_at` + 2 s. The mutation it guards
against (taking the live `created_at` before the lock) leaves the head
at + 1 s, so the test still catches it.
Commands run:
- `cargo clippy -p buzz-core -p buzz-db -p buzz-relay --all-targets --
-D warnings`
- `cargo test -p buzz-core --lib`
- `cargo nextest run -p buzz-relay --lib`
- `cargo test -p buzz-test-client --test e2e_relay -- --ignored` for the
13534 and 13535 rejection tests, against a local relay built from this
branch
- `cargo test -p buzz-db --lib`
- `cargo test -p buzz-db --test observability_source`
- `scripts/postgres-test-run.sh -p buzz-db -p buzz-relay --lib --tests`
(the CI PostgreSQL lane, run locally)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
8b6bc9beb5 |
Add community-scoped user and agent profile cleanup (#9580)
## Summary
Content, account and media cleanup leave profile records behind. Add
`buzz-admin user-deletions profile-batches` to preview or delete those
records in one community. Preview is the default; explicit `--delete`
applies bounded, retryable transactions.
Every run and retry discovers the human’s current direct agents in that
community. Ownership elsewhere cannot authorize deletion here. If Alice
owns an agent in A but Bob owns it in B, deleting Alice in B preserves
that agent. Each write batch locks and rechecks ownership. All profile
data is removed before identity rows, so an interrupted run resumes
without saved agent keys. The command no longer accepts
`--agent-pubkey`.
The handler removes profile/configuration events and projections,
rebuilds shared archive snapshots with valid signatures, and finally
removes identity rows. Repository announcements/state (30617/30618) and
name mappings remain intact without blocking identity removal; other
authored content still requires prior cleanup. Unresolved dependencies,
changed sources, untrusted signers or excessive plans stop deletion.
This includes historical `replaced-by` references in archive requests
and deltas, even after unarchive removes the current archive row. See
[operator instructions and verification steps](docs/profile-cleanup.md).
Writers must be stopped. Coordinator integration, online admission
fencing, media objects, client caches and final account-erasure
verification remain separate. The command always reports
`account_erasure_complete: false`.
### Related issue
Fixes #9576. Continues the standalone handler pattern from #9363
(content) and #9364 (account). This is an independent PR against main.
### Testing
The latest correction adds a PostgreSQL regression that runs content
cleanup followed by profile preview/delete/retry for human and agent
repository owners. It checks unchanged repository events, mentions, name
mappings and other-community data, and verifies ordinary content still
blocks profile deletion. The merge of main brings in `buzz-deletion
--lib` coverage in the CI unit lane and its fallback, covering the
preview-default parser test without duplicate runs. Account, content,
media and profile command dispatch are all preserved. The
archive-history documentation also now distinguishes planning errors
from printed blockers.
The latest main merge includes the shared dependency-policy correction
from #9609 and the content cleanup lock fix from #9615. On `54bd50299`,
PostgreSQL CI passed 1647 tests and failed 18 because content cleanup
still called the retired SQL lock-key function; this also blocked the
new content→profile regression. The merged upstream fix uses the
existing Rust-built key for both the cleanup lock and the test blocker.
Local test suites and hooks remain skipped at the owner’s request. CI
and review of the updated head are pending. The results below apply to
earlier revisions.
At `92aa9c216`, exercised the rebuilt `buzz-admin` against signed
archive/unarchive events stored in disposable PostgreSQL:
- For kinds 9035 and 8002, test a historical `replaced-by` reference to
the human and then to their owned agent after unarchive.
- Run `profile-batches --pubkey <human> --community <A> --relay-pubkey
<relay>` in preview and `--delete` modes. Both refuse the unresolved
reference; full table dumps remain unchanged.
- Keep that history only in community B. Cleanup in A succeeds,
preserves B, and selects zero work on retry.
- Delete the archive subject in B. Its history is removed while the
replacement identities remain intact.
All four scenarios passed. These are signed database fixtures exercised
through the real CLI; they do not claim live relay admission. The
correction also merges main and preserves content, media and profile
command dispatch.
The initial full database run passed 880/881 tests: the new request
fixture lost its required self-`p` tag during signing. Commit
`ff6689386` preserves that tag; all ten profile regressions now pass.
Further local checks and pre-push hooks were skipped at the owner’s
explicit request. The full corrected database suite has not been rerun;
GitHub CI will validate the new head. At `ff6689386`, the production
code matched the CLI-tested revision; the repository-retention
correction above is newer.
Previous ownership validation follows:
At `090d2a1cf`, exercised the rebuilt `buzz-admin` binary against a
disposable PostgreSQL fixture:
- Run `user-deletions profile-batches --pubkey <human> --community <A>`:
preview left table exports unchanged and selected four profile/identity
mutations.
- Repeat with `--delete --batch-size 2`: all four mutations committed;
retry selected zero work.
- Use the same human and agent keys in another community, with the agent
owned by someone else: only the human was selected, and the agent
remained intact.
This fixture uses placeholder profile signatures and validates
database/CLI behavior. It does not claim live signed-event admission.
The earlier live relay and Desktop results below cover the previous
revision.
Independent agent review covered the previous ownership correction. A
later review found the historical replacement-reference bug; the
historical-reference correction addresses that finding. Fresh review of
this revision is still required. Human command verification has not been
recorded; it is not claimed by the agent-run checks. Follow the local
verification steps in `docs/profile-cleanup.md`; preview must leave data
unchanged, deletion must preserve other-community records, and retry
must select zero work.
<details>
<summary>Historical validation at
|
||
|
|
051dd2d7aa |
fix(sdk): timestamp channel messages with millisecond offsets (#9548)
Kind-9 messages sent through the SDK or `buzz messages send` omit the `ms` tag, so clients break same-second ties by event ID. Capture one clock reading in the shared message builder and use it for both `created_at` and the canonical 0–999 millisecond offset, including direct and nested replies. Validation: both new regressions failed before the fix; the full CLI suite (691 tests) and SDK suite (335 tests) pass. The SDK test checks that the timestamp is pinned before signing; the CLI test captures and verifies signed HTTP submissions for roots and both reply depths. The built CLI also sent direct and nested replies through a managed signer to a live relay; readback confirmed one canonical `ms` tag and correct thread tags on both. Client ordering and human testing remain pending; keep this PR draft. To test manually, run `cargo build -p buzz-cli`, then send several kind-9 messages with `target/debug/buzz messages send --channel <channel> --content <text>` and direct/nested replies using `--reply-to <event-id>`. Inspect their raw events: each should carry exactly one canonical `ms` value, and a client that honors `ms` should display same-second sends in timestamp order. Related: #9541 updates mobile display ordering to consume these offsets. No duplicate producer fix found in the open PR/issue search. Repository-wide validation: `just ci` passed Rust/Tauri Clippy and formatting, then failed mobile analysis at `mobile/test/features/search/search_channels_journey_test.dart:933`: `_RenamingSession.subscribeWithStatus` omits the base method's `resumeSince` parameter. Mobile files are unchanged from the base commit. This unrelated failure remains outside this fix. The first push hook run failed the existing WebSocket throttle test `a_throttled_sign_in_reconnects_with_fresh_evidence` (connection reset during sign-in); a subsequent full CLI rerun and the complete normal push-hook retry passed without source changes. The test uses a kind-20001 event and does not call the changed builder. All required push hooks passed. Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> |
||
|
|
3bd121bc15 |
Check product_feedback's community in the writing transaction (#9608)
## Summary Third app-side step of retiring the database foreign keys (after #9399 and #9404). After this, every reference the drop migrations will remove is checked in application code. - **`product_feedback -> communities`:** `product_feedback::insert` now runs in a transaction. It locks the community row `FOR KEY SHARE` and returns `NotFound` when the row is missing. This is the same guarantee the foreign key gives. Any lifecycle state still qualifies. `docs/database.md` says provenance-only tables stay writable while their community is being deleted, and the purge clears their provenance. - **Reader tolerance:** `ProductFeedbackRecord.community_id` is now `Option<Uuid>`. The purge sets `community_id = NULL`, and `list` (used by `buzz-admin list-product-feedback`) failed to decode those rows. The JSON output shows `null` for them. - **One home for reference checks:** `require_workflow` and `require_workflow_run` move from `store/workflow.rs` into `store/reference_check.rs`. The workflow owner and channel checks now reuse `require_user` and `require_optional_channel`, so two duplicate helpers are gone. A new `require_community` joins them. - **Stale comments:** comments that justified behavior by the foreign keys now say what holds both before and after the drop. Touched: the purge order (`deletion.rs`), `command_executor.rs`'s `ensure_user`, the `set_agent_owner` doc, the NIP-43 snapshot lock note (`relay_members.rs`), `attach_scheduled_workflow_run`, and one workflow deletion test. ## Writers and readers checked (RPR #2) `product_feedback.community_id` writers: - `store/product_feedback.rs` `insert`: the only insert. It is now checked. - `store/deletion.rs` `purge_postgres`: sets the column to `NULL`. No check is needed. - `store/relay_admin_actions.rs` status update: does not touch `community_id`. Readers: - `product_feedback::list`: fixed to accept `NULL`. - `store/admin_moderation.rs` inbox queries: already `LEFT JOIN` and accept `NULL`. ## Tests All three tests drop `product_feedback -> communities` in the per-test database first, so a pass proves the application check and not the constraint. - `insert_rejects_missing_community_without_foreign_key`: a community that never existed gets `NotFound` and no row. A fenced community still accepts feedback. An active one accepts it, and a replay returns the same row. - `insert_key_share_locks_community_without_foreign_key`: an insert waits while another transaction holds the community `FOR UPDATE`, then proceeds. - `list_returns_rows_with_cleared_provenance`: a row with `community_id = NULL` is listed with `community_id: None`. ## Not in this PR - The foreign key drop migrations. They come after this PR is deployed (`docs/database.md` expand/contract). - Nothing in the database stops `DELETE FROM communities` on an active community once the community foreign keys are gone. The tombstone trigger rejects it only for inactive communities. Production never hard-deletes communities. This is decided with the drop migrations, since a trigger change conflicts with the no-new-triggers rule. ## What got simpler All in-transaction reference checks now live in one module. Two duplicate helpers were removed. `store/workflow.rs` loses about 80 lines. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
0a05330740 |
buzz-db: stop calling the dropped lock-key function in SQL (#9615)
## Summary Main's user content cleanup still calls the SQL function `community_deletion_lock_key`. Migration `0094` (#9598) drops it. On any database at `0094`, every user-deletion content batch fails with `42883 function community_deletion_lock_key(uuid) does not exist`. #9363 added this caller after #9396 moved the key to Rust. This PR binds the Rust-built key with `hashtextextended($1, 0)`, as every other caller does. - `content_batches/execute.rs`: the batch's exclusive advisory lock uses the Rust key. - `content_batches/safety_postgres_tests.rs`: the test blocker takes the same lock the same way. - `docs/trigger-retirement-deployment.md`: builds from #9363 up to this PR are not valid stops before `0094`. Rebased onto main `e894d75d`. The renumber and the `update_channel` test-call fixes this PR first carried are already on main through #9616, so they are gone from this PR. Deployed relays are unaffected: the deployed build predates #9363. ## Tests The 17 `user_deletion::content_batches` PostgreSQL tests fail on main at `0094` with the error above. This PR makes them pass. ## What got simpler One fewer SQL-side copy of the lock key. Every caller now builds the key in Rust. 🤖 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> |
||
|
|
8fb0de8d53 |
Clean up account records and refresh member lists (#9364)
## Summary Add bounded, resumable cleanup for a user’s account records and their current direct agents in each selected community. Preview prints the proposed changes without writing; deletion uses the same selectors through the command and workflow handler. Each run and retry discovers agent ownership again. An agent owned by Alice in one community and Bob in another is cleaned only in Alice’s community. Ownership changes stop the current run, and ownership rows remain available for retries and later handlers. Membership removal rebuilds and signs the current channel lists and community roster in the same transaction as each removal. A failed roster write rolls back that membership removal. The command requires the existing relay signing key when channel or community memberships are present, including users with no channel memberships. Preview does not require a key. The relay, account cleanup and admin reconciliation share the kind 39001/39002 tag builders in `buzz-db`. They preserve the existing identity tags, roster order and role positions. Regular unit-test runs now include `buzz-deletion` through both nextest and the Cargo fallback. **Channel ownership policy:** deletion may remove the last channel owner, including when the human and their agents are all owners. The channel, messages and surviving members remain. A surviving admin can manage the channel and grant ownership. If no owner or admin remains, members can continue normal use, but management recovery requires operator intervention on request. Cleanup does not require a channel ownership handoff or assign a replacement owner. The separate community-owner restriction remains. The content handler now on main advances to account cleanup before the remaining agent stage. Content and account workflow progress goes to stderr so stdout remains one JSON inspection document. The direct account command retains NDJSON stdout. Nullable attribution updates use explicit table and SET clauses so the source-policy guard can inspect them. The handler covers credentials, memberships, read progress, supported personal events and their copies, feedback, and explicit global listener/database-role cleanup. It retains shared records and historical signed lists. Scope files select the human and communities; saved agent keys do not authorize deletion. This remains an offline operator feature: stop relay and external writers before deletion. It does not revoke already-connected sessions. Coordinator integration, remaining handlers and final erasure verification are separate; results always report `account_erasure_complete: false`. The real account workflow still stops at an unimplemented successor. ### Related issue Replaces the account scope of #9354 and #9355 with one focused PR. Those earlier PRs remain intact for reference. Agent cleanup belongs within the business handlers; this change does not integrate the historical standalone agent stage in #8959. ### Testing Exercised the real preview and delete commands in an isolated local relay/database with Alice disconnected and Bob’s desktop app open. Preview left the normalized database dump unchanged. Deletion checks covered all 101 tables and all 30 affected channels; 168 newly signed list events verified. Bob refreshed the member dialog and saw Bob, B1 and Carol, then successfully sent and read a message. A1’s membership in the community where Bob owns it remained intact. The live CLI and desktop evidence above predates the latest follow-up. Independent end-to-end checks at `d45759df2` also verified unchanged preview data, signed channel/community lists after deletion, signing-key preflight, and workflow JSON stdout. The shared-builder follow-up was source-reviewed and formatted; local builds, tests and commit/push hooks were skipped at the author’s request. Validation of the new revision and a repeat of the signed-list end-to-end check are pending. Human testing remains pending. For human verification, use an isolated database and its relay signing key. Preview a community-only member, confirm no writes, then delete and verify the current kind 13534 roster omits them. Run an approved account-stage fixture with `user-deletions run <id> --delete --next-step`; the entire stdout must parse as one JSON document, with batch progress on stderr. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Signed-off-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
e894d75d26 |
buzz-db: fix main (renumber the function drop to 0094, update_channel test call) (#9616)
## Summary Main has two migrations numbered `0093`: - `0093_push_gateway_installation_platform.sql` from #9560 - `0093_drop_plain_sql_functions.sql` from #9598 The file names differ, so GitHub showed no conflict between the PRs. sqlx applies the first version-93 migration and then rejects the second as a changed migration 93. Every migrate run on main fails, including relay startup with auto-migration on. This PR moves #9598's migration to `0094`: - `git mv migrations/0093_drop_plain_sql_functions.sql migrations/0094_drop_plain_sql_functions.sql`. The SQL is unchanged. - `embedded_migrator_contains_consolidated_initial_schema` now expects 94 migrations, with the function drop at version 94. - The Postgres test is renamed to `migration_0094_drops_plain_sql_functions`. It finds the migration by description, so its logic is unchanged. - `docs/trigger-retirement-deployment.md` now names `0094`. #9560's `0093` keeps its number. It reached main first and may already be applied on deployments that auto-migrate. ## Second break on main: `update_channel` call sites Main's buzz-db lib tests also stopped compiling. #9581 added a `sender` argument to `update_channel`, and #8320's cross-community test (`deletion.rs`) landed in parallel with the old three-argument call. This PR passes the channel creator as the sender. The test only renames an open channel, so the private-to-open rule does not apply. ## Deployments No deployment has applied #9598's `0093`: no image built from main after #9598 has rolled out yet. A database that applied #9560's `0093` applies `0094` next. Do not promote any image built from `4e8f8365` (the #9598 merge) or later until this PR merges. ## What got simpler Nothing. This is a renumber and a test call fix only. 🤖 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> |
||
|
|
f158fdd9a1 |
feat(relay): name the agent whose add policy refuses a DM (#9601)
## Problem When an agent's add policy refuses a DM open or add (from #9125), the refusal says only that an agent refused. The person can't tell which agent blocked it, so they don't know whose owner to ask. ## Change The DM refusal now ends with `(agent <hex pubkey>)` for the first agent refused, in the order the request named them. For example: `forbidden: policy:owner_only — only the agent owner can add this agent (agent 3f9a…)` The prefix is unchanged, so existing clients that match on `policy:owner_only` or `policy:nobody` keep working. Desktop and mobile follow-ups will show the agent's name. ## Tests - `adding_an_agent_follows_its_add_policy` asserts the full refusal including the agent. - `opening_with_several_agents_follows_their_add_policy` adds a second refusing agent and checks the first one named is reported. - DM Postgres tests: 297/297 passed. Clippy is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4e8f836576 |
buzz-db: drop the community_deletion_lock_key and profile_name_fields functions (contract) (#9598)
## Summary Phase 2 of retiring the two remaining plain SQL functions. Phase 1 moved their work into the relay: - #9396 builds the community deletion lock key in Rust (`deletion::community_deletion_lock_key`, locked with `hashtextextended($1, 0)`). - #9397 reads profile names with inline SQL (`PROFILE_NAME_FIELDS` in `buzz-search`). No relay at or after #9397's merge (`279a31da`) calls either function. This PR drops them: - **Migration 0093** runs `DROP FUNCTION community_deletion_lock_key(UUID)` and `DROP FUNCTION profile_name_fields(TEXT)` under a 5s `lock_timeout`, with no `IF EXISTS` and no `CASCADE`. If anything still depends on a function, the migration fails instead. Migrations 0029 and 0064 stay frozen. No database function calls either one any more: 0090 dropped the fence functions, which were the only SQL callers of the lock key. - **Desired state:** removes both `schema/functions/` files and their `schema.sql` includes. Both boot paths stay catalog-equivalent (`admin_schema_parity_between_desired_state_and_migrations`). - **Tests:** - New `migration_0093_drops_plain_sql_functions`. It migrates to 0092, checks that both functions exist and that serving and deletion catalog validation pass, then runs 0093 and checks that both functions are gone and that validation still passes. This covers new code on either side of the drop. - The migration listing test pins 0093's statements and that it has no `CASCADE`. - `desired_state_catalog_has_no_universal_fence_and_still_boots` now asserts that both functions are absent. - Replaces the Rust-vs-SQL lock key parity test with `community_deletion_lock_key_bytes_are_fixed`, a unit test that maps fixed UUIDs (nil, max, and one with hex letters) to their exact keys. Older replicas and the repair-script key in `docs/database.md` build the same string, so a changed prefix or UUID format must fail a test. - Removes two relay test-schema wrappers (`bridge.rs`, `ingest.rs`) that forwarded `community_deletion_lock_key` to `public`. Writers no longer call it, and the wrapper's `CREATE FUNCTION` would fail once the function is gone. - **Docs:** `docs/trigger-retirement-deployment.md` gets a `0093` section with the required stop. ## Deploy gate **Required stop:** any relay build at or after `279a31da` (#9397's merge, which follows #9396). `relay-v0.3.0` does not contain it. A relay older than that which still serves after 0093 fails every write and deletion that takes the community deletion lock, with `42883 community_deletion_lock_key(uuid) does not exist`, and its profile name search fails with `42883 profile_name_fields(text) does not exist`. 0093 takes no table locks and needs no cleanup. Migration number: #8696 and #9398 also propose `0093`. Whichever lands second renumbers. ## Review-Proven Rules - **RPR #2 (every path):** I checked every reference on `main` and at the stop build `279a31da`. At both, only test code reads either function: no boot, readiness, catalog or runtime query depends on them. Serving and deletion catalog validation pass before and after 0093, in the new test. - **RPR #3 (falsifiable):** removing the `profile_name_fields` drop from 0093 turns `migration_0093_drops_plain_sql_functions` red. - **RPR #3 (lock key bytes):** a changed prefix, `.simple()` UUID formatting, or uppercase formatting each turns `community_deletion_lock_key_bytes_are_fixed` red. ## What got simpler Two database functions, their desired-state files, a cross-language parity test and two test-only SQL wrappers are gone. After this PR, the only functions left in `schema/functions/` are trigger functions. ## Validation Blox gate at `95ac71c8`: - `cargo fmt --all --check`, and `cargo clippy -p buzz-db -p buzz-relay --all-targets -D warnings`. - `buzz-db --lib` unit tests: 216/216, including the migration listing test. - `buzz-db` Postgres tests (`migration::`, `deletion::`, `nip_fi_binding::` postgres_tests): 130/130. These include `migration_0093_drops_plain_sql_functions`, `admin_schema_parity_between_desired_state_and_migrations` and `deletion_surface_parity_between_migration_0029_and_schema_sql`. - `buzz-search` `profile_names*` Postgres tests: 4/4, on a fully migrated database where `profile_name_fields` no longer exists. - The two relay tests whose test-schema wrapper this PR removes: 2/2. - Must-fail check: with the `profile_name_fields` drop removed from 0093, `migration_0093_drops_plain_sql_functions` fails. Second Blox gate at `e1b5513a` (the lock key vector test): - `cargo fmt --all --check`, and `cargo clippy -p buzz-db --all-targets -D warnings`. - `buzz-db --lib` unit tests: 217/217. - Must-fail checks: a changed prefix, `.simple()` and uppercase UUID formatting each fail `community_deletion_lock_key_bytes_are_fixed`. The first gate run found that `deletion_surface_parity_between_migration_0029_and_schema_sql` still expected `community_deletion_lock_key` in `schema.sql`. The second commit fixes that. 🤖 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> |
||
|
|
6b4a398829 |
feat(push-gateway): enroll Android installations and send FCM wakes (#9560)
## What and why Ticket 2 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now enrolls Android installations and wakes them through FCM, next to the existing iOS path. Builds on [#9557](https://github.com/block/buzz/pull/9557) (platform-neutral `/v1/deliveries` route), now merged. - **Platform.** The enrollment request has no platform field. The gateway derives it from which attestation is present (App Attest object or Android attestation chain) and records it in a new `push_gateway_installations.platform` column (`ios` or `android`). It lives only in gateway state; the relay never sees it. - **Android enrollment transcript.** Key Attestation fixes the challenge at key generation, so the client signs nothing at enrollment and sends no `key_id`. The attestation challenge must equal SHA-256 of a canonical JSON transcript under domain `buzz.push.enroll.android.v1` with `v`, `audience`, `challenge_id`, `challenge`, `endpoint`, `endpoint_epoch` and `expires_at`. The gateway derives the key id as SHA-256 of the attested 65-byte uncompressed P-256 key. A request whose `key_id` presence doesn't match its platform gets 400. The iOS transcript (`buzz.push.enroll.v1`) is unchanged. - **Signed calls.** iOS keeps App Attest assertions. After enrollment, an Android installation signs every call (delegate, revoke delegation, rotate endpoint, revoke installation) with its attested Keystore key: ECDSA P-256, DER, over the same transcript bytes iOS signs. High-S signatures are accepted since Keystore does not normalize. There is no counter; the single-use challenge inside the transcript is the replay protection. - **FCM sender.** HTTP v1, high priority, data-only, compiled-in payload (no relay-supplied bytes), one constant collapse key, TTL from the delivery expiry. OAuth access tokens come from the service account key (RS256 JWT bearer). Outcomes map onto the existing delivery outcome classes and metrics (`push_gateway_fcm_*`). - **Token refresh.** A cached token keeps serving until it expires. Once it is due for refresh, one background task fetches a new one, so a wake never waits on a refresh while a valid token exists. A failed fetch keeps the current token and backs off 5 s before the next attempt. Only a cold cache (no unexpired token) makes a wake wait on the token request, single-flighted. A 401 discards the cached token only if it is still the one FCM refused, so a late 401 can't drop a newer token. - **Retries.** 429 and `QUOTA_EXCEEDED` retry after at least 60 s (FCM's hint if longer). 500, 502, 503 and 504 retry. - **Attestation seam.** Android Key Attestation verification sits behind a trait. Tests use a test-only verifier compiled under `cfg(test)`, so production configuration cannot select it. The production verifier fails closed: a gateway configured for Android starts but rejects every Android enrollment until ticket 3. - **Migration.** Expand-only `ADD COLUMN platform TEXT NOT NULL DEFAULT 'ios' CHECK (...)`: the deployed gateway's inserts stay valid and existing rows become iOS. `SET LOCAL lock_timeout` (5 s) and `statement_timeout` (30 s) bound the table lock wait and the CHECK validation scan. No triggers, functions, foreign keys or backfills. Mirrored as gateway `0007` and relay `0093` plus `schema/tables/public`, per docs/database.md. ## Configuration All four are optional and must be supplied together (a partial set fails startup). Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only. - `BUZZ_PUSH_ANDROID_PACKAGE_NAME` - `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS` - `BUZZ_PUSH_FCM_PROJECT_ID` - `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` ## Tests - `cargo test -p buzz-push-gateway` (92 passed, 18 ignored; 94 passed with `personal-dev-app-attest`; iOS rows unchanged), `cargo fmt --check`, `cargo clippy -p buzz-push-gateway -p buzz-db --all-targets -- -D warnings`. - New HTTP tests with a fake FCM sender: Android enroll, delegate, deliver, rotate endpoint and revoke; signed-call rows for wrong key, altered transcript and reused challenge; platform derivation and bad attestations. - Postgres (ignored, run locally): gateway migration test (existing and old-gateway inserts become `ios`, bad value rejected); relay `admin_schema_parity_between_desired_state_and_migrations` now covers `push_gateway_installations` columns, indexes and constraints; the `runtime::migration::postgres_tests` set passes single-threaded. - Break check: making signature verification always succeed turned two tests red (the signed-call rejection rows and the signature unit test); restored. - Token cache tests against a local fake token endpoint with a controlled clock: a due refresh keeps serving the valid token even when it fails; a late 401 does not discard a refreshed token; a queued background refresh honors a foreground failure's backoff. The FCM response table covers 429 with and without an error body, and 502/504 HTML pages. - Android enrollment rows: `key_id` present on Android (400), wrong transcript binding, a 65-byte non-point key, an over-long chain, and exact replay. - Break checks for every new guard (no background refresh, blocking while due, failure dropping the token, unconditional 401 clear, no quota floor, no 502/504 retry, the queued-refresh backoff check, Android requiring `key_id`, skipping the P-256 point check): each turned at least one test red; restored. ## Not here (ticket 3) Real Key Attestation verification (Google roots, revocation list, boot state, boot-key list, app identity). Per-key rate limiting is also left for ticket 3, since it did not fall out of this change. The Helm chart does not pass the Android settings yet. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
50cfc54337 |
Apply the private-to-open rule in update_channel too (#9581)
## Summary - Follow-up to https://github.com/block/buzz/pull/9307, which made the relay refuse to open a private channel that has, or once had, any member other than the sender and the sender's own agents. That rule lived only in the channel metadata edit path (kind:9002). The store's other channel-settings function, `update_channel`, could still open such a channel. - Now both paths apply the same rule, because it runs in the one function that writes channel settings for both. `update_channel` takes the authenticated sender so it can decide the rule. Today only tests call `update_channel`, so nothing user-visible changes; the gap is closed before any real caller arrives. - The user-deletion executor doc now says what the rule needs from a purge: if a purge keeps any of a user's messages in a channel, it must also keep that user's membership row there, marked removed. The relay finds former members only through those rows, so dropping the row would let the channel be opened and its history, those messages included, be made public. ## Details - The check moved out of `apply_channel_metadata_event` into `update_channel_on`, which both paths call. It still runs under the membership lock that a visibility change takes, so members cannot be added between the check and the commit. - One ordering change: a single kind:9002 that opens a private channel with other members, archives it and sets `auto_join` to true now gets the `auto_join` refusal instead of the private-to-open one, because the `auto_join` check now runs first. Both refuse, and nothing is stored either way. - This PR also carries doc-comment wording that was reviewed on https://github.com/block/buzz/pull/9307 but not merged with it: the comments now give the reason, that opening publishes the existing history, so removed members count. - Every call site of `update_channel` is a test, and each now passes the channel owner as sender. ### Related issue Follow-up to https://github.com/block/buzz/pull/9307 (review notes on its store gap and on purge). ### Testing - New Postgres test `update_channel_refuses_opening_a_private_channel_with_other_members`: opening fails for both the owner and the other member as sender, while the other member is current and after they are removed, and the channel stays private. A channel that holds only the owner opens. - The existing kind:9002 test `private_to_open_needs_no_other_members` still passes. Both tests fail when the check is removed. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a8f55e637a |
Add real content cleanup for users and agents (#9363)
## Summary Add one shared content-cleanup handler for a user and their agents in a specified community. Preview is the default; deletion commits bounded batches and preserves other people's replies and reactions. Agent selection requires ownership by this user in the target community. Ownership elsewhere is insufficient. The start record reports missing or conflicting ownership, and every batch rechecks the selected agents before deleting anything. ### Reply preservation and live writes Keep erased placeholders for messages needed by surviving reply chains or reactions. Plain links and quotes may point to a deleted message; their signed source messages stay unchanged. Nested reply ancestry uses the existing parent/root indexes. No new permanent index or schema migration is added. Replies without thread metadata use the existing tags GIN index to search for each selected message ID in lowercase and uppercase. The shared marker parser checks which matches are actual replies. Mixed-case references without thread metadata may be missed; metadata-backed replies use binary IDs and remain covered. Planning and hard-delete rechecks each run the probes in one SQL statement with a one-second timeout and a 10,000-match limit. A reply matching several probes counts several times. Exceeding either bound aborts cleanup. This avoids the broad search through unrelated replies; production-scale performance has not been measured. Each batch revalidates its work under the community lock. Transaction-local timeouts apply before locking, including after reconnect. Planned output is written before locking and receipts after commit. A changed row, owner, or surviving reply aborts the batch; retry replans remaining work. Normal reply insertion retains the added indexed parent-existence check. This changes the live write path and prevents saving a reply whose parent disappeared while the writer waited. Erased messages appear unavailable in moderation lookups instead of carrying an empty author key. ### Included content Supported authored events and owned reaction, subscription and notification records are included. Signer-owned personas (30175), team definitions/catalogs (30176/30178), emoji sets/entries (30030/30180), and project groupings (30621) include shared publications and stored revisions. Deleting a project grouping leaves member repositories, their announcements/state and name mappings intact. ### Testing Local runtime tests and hooks are skipped at the owner's request. Source review, Rust formatting and diff checks were completed. The updated revision requires CI validation; earlier test runs and index benchmarks do not validate this replacement. Regression cases cover ownership conflicts/transfers, missing thread records, nested ancestry, plain links, late replies, lookup limits, reconnects, blocked output, and unavailable moderation targets. No new manual relay or UI test was run for this revision. Account blocking remains unfinished; these changes do not establish complete online account erasure. ### Scope and compatibility **Deferred to a separate follow-up PR to keep this PR smaller:** the following work will extend **the same content cleanup handler** (`purge_content` / `content-batches`), rather than introduce another handler: - Workflow database definitions, runs, traces, approvals, schedules and copied inputs; some source events are already covered here. - Canvas revision events and current canvas text. - Artifact events, revision records and current heads. - Channel topics and purposes. - Gift-wrapped DMs and additional huddle history that require different attribution rules. - Git issues, PRs, patches, comments/status and required repository metadata, subject to preservation rules. Repositories themselves stay. - Remaining stored workflow, delivery and projection copies outside this PR's current coverage. These categories remain unfinished. Deferring them is not a permanent retention decision or a claim of complete content erasure. The follow-up must settle shared-document and mixed-owner workflow behavior and test surviving content. Profiles and managed-agent identity definitions belong to profile cleanup. Memberships, personal preferences and access belong to account cleanup. Media cleanup was implemented separately in #9365 and is now on main. Deletion requests, approvals, progress/history and replay protection stay. The workflow orders account gating, global media cleanup, then per-community content cleanup. Real requests still stop at the unfinished account gate; demos simulate every stage without deletion. Other unfinished real workflow stages fail explicitly. Existing demo requests saved with `purge_db` must be recreated for `purge_content`. Bulk client notifications remain separate work. Open views may retain cached content and counts until refresh. The existing missing reply-count button after refresh and ordinary UI access when the root is deleted are outside this PR. Replaces the content portion of #9355 and #9332. Related prior handler: #8698. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
c0ce4982fc |
buzz-db: check membership, agent-owner and channel references in app code (#9404)
> Builds on #9399 (its two commits are included here until it merges;
review only the commits after `367d3486`).
## What
This is the second app-side step toward retiring every foreign key,
following `docs/database.md` ("Retiring a trigger, function, or foreign
key"). Each writer below now checks its parent inside the writing
transaction and locks it `FOR KEY SHARE`, the same lock an FK check
takes. The FKs stay in place, so both checks run and agree. A later
contract migration drops them.
The shared helpers are in a new `store/reference_check.rs`:
`require_channel`, `require_optional_channel`, `require_user` and
`require_relay_member`, all community-scoped. A missing parent returns
`DbError::NotFound` and nothing is written.
| FK | Writer | Change |
|---|---|---|
| `join_policy_acceptances → relay_members` | `relay_invite.rs` (both
claim paths), `relay_invite/claim_owner.rs` | One helper locks the
member row, then inserts the acceptance. The existing-member read is now
`FOR KEY SHARE`. |
| `users.agent_owner_pubkey → users` | `user.rs`
`set_agent_owner_with_operation` | Reads the agent row `FOR NO KEY
UPDATE`. A missing agent → `NotFound`; an already-owned agent →
`Ok(false)` without examining the owner; otherwise the owner is checked,
then the UPDATE runs. `NotFound` for a missing owner therefore holds
with or without the self-FK. |
| `channel_members → channels` | `channel_members.rs`
`insert_auto_membership`, `lock_channel_archived_at_in_transaction` |
The auto-add checks the channel. The archive lock now returns
`ChannelNotFound` for a missing row instead of reading as not archived.
A soft-deleted channel still reads `None`. |
| `thread_metadata → channels` | `event.rs`, `thread.rs` | Checks the
channel before writing thread metadata, in the event's own transaction.
|
| `moderation_reports/actions → channels` | `moderation.rs`,
`relay_admin_actions.rs` | Checks a non-null `channel_id` before the
write, after the existing rejection outcomes (not-found,
already-claimed, not-open, replay). |
**Real race closed.** Member removal locks the member row `FOR UPDATE`,
deletes the acceptances, then deletes the member. The acceptance insert
used to follow an unlocked member read, and a membership `INSERT … ON
CONFLICT DO NOTHING` locks nothing when the member already exists. Today
only the FK's implicit `KEY SHARE` stops an orphan acceptance; this
change makes that lock explicit.
**Caller-visible behavior.**
- The huddle join in `audio/handler.rs` maps `ChannelNotFound`, meaning
the channel was purged between the pre-join check and the lock, to
`MembershipLost` before any write.
- `set_agent_owner` has one production caller, `api::write_agent_owner`.
It runs `ensure_user_for_authorization` on both the agent and the owner
first, so its behavior is unchanged.
- `put_members` keeps its existing error.
## Tests
- `store/reference_check_postgres_tests.rs`: 9 tests, one missing-parent
test per writer plus a `KEY SHARE` lock test. Each drops the covered FK
in its per-test DB (`test_support::drop_foreign_keys_between`), so it
proves the app check. The `insert_report` upsert test pins precedence: a
missing channel beats an existing report, and the stored row is
unchanged.
- `relay_members.rs`:
- Two new race tests: a membership claim racing member removal, and an
invite claim racing member removal.
- The existing
`member_removal_waits_for_and_removes_concurrent_acceptance` now runs
against the explicit lock.
- The `wait_for_put_member_behind` query pattern in `api/invites.rs`
tests was updated to the new query text.
- `relay_members.rs`
`invite_claim_conflicting_with_a_member_added_mid_claim_waits_for_removal`:
a `#[cfg(test)]` pause before the membership INSERT
(`relay_invite::test_hook`) lets a member commit mid-claim and a removal
hold it `FOR UPDATE`. The claim must wait, then return `NotFound` with
no acceptance, no orphan, and no invite use.
- `set_agent_owner_rejects_missing_owner_with_and_without_foreign_key`:
asserts `NotFound` and an unchanged owner with the FK installed, then
with it dropped.
Falsification: removing the check at each of the 10 call sites turns its
test red. So does stripping `FOR KEY SHARE` from each helper and from
the invite member read. Swapping the conflict-branch helper for a raw
acceptance insert, or moving the owner check back after the UPDATE, also
turns its test red.
## Validation
Run on a cloud workstation at this tree (
|
||
|
|
ec778bff9a |
buzz-db: enforce five single-table guards in app writers (phase 1) (#8320)
> **Also carries the catalog expand** (`cdc88edd`) for phase 2 (#9398). `validate_serving_catalog`, used at boot and readiness, no longer requires the `communities_deletion_tombstone` trigger, only `community_deletion_lock_key(uuid)`. Without this, a pod would fail boot after `0090` drops the guards. Regression: `migration_schema_single_table_guards_are_optional_for_serving_and_deletion` migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, and validates again. No schema change. ## What This is phase 1 of 2 for retiring five single-table guard triggers (BUZZ-318). Their invariants now hold in the application writers. **All five triggers and their functions stay** for mixed-version pods. A later PR drops them. | Trigger / function | App-side enforcement | |---|---| | `trg_channels_community_id_immutable` | **By construction.** Inserts bind the tenant once. No production `UPDATE channels` assigns `community_id`, and `ChannelUpdate` has no community field. A source policy pins this. | | `communities_deletion_tombstone` / `enforce_community_tombstone()` | **One state machine.** `begin_quiescing`, `fence`, `purge_postgres` and `abort` all go through `transition_community`, using a `FOR UPDATE` row snapshot in the caller's transaction (quiesce, fence and abort also hold the community deletion advisory lock; purge does not, and its tombstone transition fails if a concurrent abort won). Allowed transitions: active→quiescing (plus a quiescing retry); quiescing→fenced, which increments the generation; fenced→tombstone at the same generation, with a one-way `deleted_at`; active/quiescing/fenced→active on abort, which also increments the generation. Every transition rejects an already-deleted row. The UPDATE is conditioned on the snapshot's state and generation. `set_community_icon` updates only an active, undeleted row and returns `AccessDenied` otherwise. Archive and unarchive lock an active row, and their UPDATEs also carry `deletion_state = 'active'`, so every non-lifecycle `communities` UPDATE or upsert carries the active predicate (policy-pinned: a non-active row is immutable outside the state machine). No production `DELETE FROM communities` exists, and the policy forbids adding one. Executor GUCs are unchanged. | | `community_deletion_request_retargeting_guard` | **Mostly by construction, plus predicates.** No production UPDATE assigns target identity or provenance (policy-pinned). Both initial inventory freezes (`freeze_inventory`, `complete_owner_preparation`) require `stage = 'submitted' AND blocked_at IS NULL AND inventory_frozen_at IS NULL` in their UPDATE. Every request UPDATE that assigns an inventory column must carry `inventory_frozen_at IS NULL`, and one that assigns `destructive_storage_*` must carry the frozen-or-equal guard (policy-pinned). The destructive-manifest freeze now also refuses a row that is marked frozen but is missing its manifest JSON. | | `community_deletion_approval_removal_guard` | **By construction.** Approvals are insert-only (`approve`, `complete_owner_preparation`). The policy forbids any production UPDATE, `ON CONFLICT … DO UPDATE` upsert or DELETE. | | `community_deletion_manifest_keys_guard` | **One shared check.** Append, pre-freeze clear and verified cleanup each lock the request row and check its stage and freeze status through `guard_manifest_chunk_write`. Chunk content is never updated: the policy rejects every chunk UPDATE or conflict upsert except `mark_manifest_chunk_deleted`, the only writer that stamps `deleted_at`. That stamp must be the function's only chunk write, a plain UPDATE of exactly `SET deleted_at = now()`, with `request_id = $1`, `chunk_no = $2` and `deleted_at IS NULL` as plain conjuncts (no `OR`, no subquery), so it stays one-way. | **The app is stricter than the triggers, not equivalent to them.** `enforce_community_tombstone()` admits any change when the executor GUC matches, before it looks at lifecycle columns, so the transition graph above lives only in `transition_community`. The chunk DELETE trigger also allows cleanup when the parent request is missing or unfrozen, while `guard_manifest_chunk_write` allows only fenced-and-unfrozen or verified cleanup. Every current caller already runs at those stages. Writer inventory: I searched every production writer of these tables and columns across all crates, excluding `#[cfg(test)]`. That covers buzz-db, buzz-deletion, buzz-relay handlers, side effects and operator/admin APIs, and buzz-audit. Relay, operator and executor entry points all call the store methods above. No other crate writes these tables directly. ## Tests The six PG tests are in `store::deletion::postgres_tests`. Each disables **only** its own trigger, then checks that the app path rejects the forbidden mutation and permits the allowed one: - `single_table_guard_channels_remain_tenant_bound_without_trigger` - `single_table_guard_community_lifecycle_rejects_deleted_row_without_trigger`: icon refused while quiescing; fence refused on a deleted row; then the full fence→tombstone sequence; abort after tombstone fails. - `single_table_guard_abort_invalidates_generation_without_trigger`: abort from quiescing and from fenced, for unarchived and pre-archived communities; asserts active state, community and request generation = previous + 1, restored `archived_at`, null `deleted_at`. - `single_table_guard_request_inventory_freeze_is_one_way_without_trigger`: re-freeze is refused on both the operator and owner-preparation paths. The owner path leaves no approval evidence behind. Owner request-ID retargeting is refused, and a frozen manifest with missing JSON can't be filled in. - `single_table_guard_approval_evidence_is_append_only_without_trigger`: asserts the exact error. - `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` The source policy lives in `crates/buzz-db/tests/observability_source.rs` (`every_production_single_table_guard_writer_preserves_its_invariants`). It scans every crate's `src` directory and reuses the file's existing cfg-test stripping, comment and literal masking, function slicing and SQL normalization. Each rule is checked per function. A minimum count of discovered writers per table makes the test fail if discovery stops matching, and exact sets of production functions hit by each rule (lifecycle exemption, stamp exemption, chunk-guard callers, active-community writers, request-freeze writers) make it fail if a parser stops matching. The parser handles `ON CONFLICT … DO UPDATE SET` (with or without a space before `(`), tuple `SET (a, b) =`, and rejects column-less community inserts. A guard counts only as a plain conjunct of the statement's own WHERE: it must follow the WHERE start or an `AND` (optionally table-qualified, never `NOT`), with no whole-word `OR` outside the frozen-or-equal groups and no subquery, and every `destructive_storage_*` assignment must preserve a frozen value with `COALESCE`. Negative and accept fixtures cover every rule. The shared source filter now also skips `test_support.rs`, which is compiled only under `cfg(test)`. Each check was confirmed to fail when its fix is removed. Seven mutants each failed on an assertion: the `inventory_frozen_at` predicate removed from each of the two freeze paths, and each of the five policy rules disabled. Review rework also falsified the injected `SET icon = NULL` writer, an unguarded inventory/destructive-storage writer, abort keeping the old generation, and the stamp without `deleted_at IS NULL`; every new fixture test fails against the previous policy. Round 1 also falsified the lifecycle `deleted_at` check, the manifest append guard, the icon predicate and the destructive-manifest predicate. ## What got simpler The four lifecycle UPDATE statements, each with its own generation arithmetic and its own GUC setup, are now one transition function with one SQL writer. Both manifest removal modes share one admission check. For inventory freeze, the check lives in the existing atomic UPDATE, with no new helper or transaction. Channel immutability and approval append-only behavior stay construction rules, not duplicated runtime checks. The source-policy scans now share one Rust crate walker, which this PR extracted into `collect_production_rs_files`. **Known policy limits:** the policy is a textual check of Rust source, not a SQL parser or a control-flow analysis. None of these gaps hides an unsafe writer today, but phase-2 reviewers should not read the policy as more than that: - Only `INSERT`, `UPDATE` and `DELETE` statements are recognized, including CTE and `ON CONFLICT` forms. `MERGE` and `TRUNCATE` are not. `UPDATE ONLY <table>` and `DELETE FROM ONLY <table>` are not recognized either, because the table name must follow the verb directly. - A guard negated *after* itself (`deletion_state = 'active' IS FALSE`, `… = false`) is not caught. - A SQL comment inside the literal (`-- AND deletion_state = 'active'`) can supply the guard text. - The frozen-or-equal `OR` text is removed before the `OR` check without checking how it is grouped. - `guard_manifest_chunk_write(` is checked for presence in the writing function only. The policy does not show the result is awaited and propagated, or that the guard runs in the same transaction as the write. With the trigger disabled, `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` shows append and pre-freeze clear refusing after freeze; verified cleanup has no trigger-disabled test. - Function discovery uses a fixed list of signature prefixes, and dynamic SQL is recognized only in known shapes such as `set_parts.push`. - The shared source filter skips files named `test_support.rs` by name. Both such files are compiled only under `cfg(test)` today. **Phase 2 (not here):** a forward migration plus a desired-state change will drop only these five triggers and functions and update `validate_serving_catalog_on` and the schema assertions. It ships after every serving and executor pod runs these writers. **Identified debt (pre-existing, outside this diff):** purge can take the request-row FK lock (checkpoint insert) before the community lock, while abort locks community then request (`deletion.rs` purge vs abort). PostgreSQL detects that as a deadlock and cancels one side, which fails closed; the order is unchanged from the base. `runtime::postgres_tests::writer_pool_rejects_non_read_committed_database_default` hangs until its 120 s bound on clean `177551dda` as well. Some test-only fallbacks still hardcode `localhost:5432`, and one relay test helper hardcodes Redis 6379. ## Verification (Blox, byte-identical tree to this commit) | Gate | Result | |---|---| | `cargo fmt --all -- --check` | pass | | `cargo clippy --workspace --all-targets -- -D warnings` | pass | | `cargo nextest run -p buzz-db --lib` | 166/166 | | `cargo nextest run -p buzz-db --test observability_source` | 30/30 | | `scripts/test-postgres-test-discovery.sh` | pass | | `scripts/postgres-test-run.sh -p` buzz-admin / audit / deletion / push-gateway / relay / search / workflow | all rc 0 (4, 7, 11, 11, 402, 20, 2) | | `scripts/postgres-test-run.sh -p buzz-db` | 515 pass, 1 fail: the pre-existing hang above | The new PG tests are selected by the `postgres-ci` filter `(test(/postgres_tests::/) or binary(/^postgres_/)) and not test(/(^|::)external_infra[^:]*::/)`. The policy tests run in `just test-unit` (`--test observability_source`). --------- 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> |
||
|
|
3d97535120 | buzz-db: check workflow references in app code before FK retirement (#9399) | ||
|
|
833c41863a |
fix(relay): enforce channel owner precedence (#9592)
**Category:** fix **User Impact:** Channel admins can manage the conversation while owners retain control of ownership and owner membership. **Problem:** Channel admins can currently grant themselves ownership, change another owner's role, or remove an owner when another owner remains. A racing promotion can stop a removal after admission while its command is still stored and reported successful. **Solution:** Reserve ownership grants, owner role changes, and owner removal for channel owners, enforced during validation and under the database membership lock. Persist each removal and its signed command together so a locked refusal rejects the receipt without storing or broadcasting the refused command; this applies equally to people and agents, with no new role, migration or protocol field. <details> <summary>File changes</summary> **crates/buzz-core/src/channel.rs** Constrain the shared role policy and member admission decision. Keep same-role additions idempotent and preserve ordinary guest-promotion rules; extend the existing role matrix and cover ownership grants through admission. **crates/buzz-db/src/store/channel_members.rs** Reject non-owner removal of an owner under the existing membership lock, including removal of an agent the actor owns. Reuse those locked checks when storing a removal command and its membership change atomically. Retain database coverage for escalation denials, ordinary owner/admin powers and concurrency; move the target-promotion race to the ingest journey below. **crates/buzz-relay/src/handlers/channel_authz.rs** Make removal authorization aware of the target's role and expose an ownership-specific role-change refusal. Extend the existing authorization tables. **crates/buzz-relay/src/handlers/side_effects.rs** Pass the removal target into admission authorization. Persist removals atomically, then run cache invalidation, eviction and best-effort notices only after commit; duplicates run no second removal or notices. **crates/buzz-relay/src/handlers/ingest.rs** Route kind 9001 through atomic persistence and return locked membership refusals as client rejection before dispatch. **crates/buzz-relay/src/handlers/remove_user_postgres_tests.rs** Exercise the real ingest race with a membership-lock barrier: target promotion causes rejection, leaves the Owner intact and stores/publishes no command. Then verify legitimate removal and duplicate replay after rejoin. This replaces the DB-only target-promotion test rather than duplicating it. **crates/buzz-relay/src/handlers/mod.rs** Register the new PostgreSQL ingest journey for automatic discovery. **NOSTR.md** Document owner precedence, including the agent-owner exception's boundary. </details> ### Try it 1. Run the updated relay and create a disposable channel with two owners, one admin, and one ordinary member. Two owners ensure the last-owner guard cannot mask the new permission check. 2. As the admin, attempt to promote yourself or another member to owner. Both requests should be refused. 3. As the admin, attempt to demote or remove either owner. Both requests should be refused and their memberships should remain unchanged. 4. Confirm the admin can still rename the channel and manage ordinary members/admins. 5. As an owner, confirm ownership delegation and co-owner demotion/removal still work. The sole remaining owner must still be unable to demote or remove themselves. 6. Run the PostgreSQL lane's membership regressions and `removal_receipt_tracks_the_locked_membership_write`. The controlled race must return rejection with the target still Owner and no stored/published removal; the same command must succeed once authorized, and its later replay must preserve a rejoined member. ### Validation and remaining checks - At `e7a8fe405`, all **2,048 infrastructure-free tests** across the complete `buzz-db`/`buzz-relay` package inventory pass with nextest process isolation, plus all **five package doctests**. The monolithic Cargo run stalled in shared-process configuration tests; the same package inventory passes with the repository's preferred isolated runner, without exclusions or assertion changes. - The new ingest journey fails on the original implementation with `accepted:true` after the locked refusal, and passes with atomic removal. Its positive controls verify actual publication for a legitimate removal and no repeated removal/publication after rejoin. The existing demoted-actor lock test retains direct-call concurrency coverage. - At the same head, all **1,425 PostgreSQL cases** across both packages pass through the per-test isolation wrapper (PostgreSQL 17.12, UTC; hosted CI uses 16). A rebuilt isolated native relay passes **24 signed WebSocket operations** plus persisted-state and subscriber checks, including the real promotion/removal race, later legitimate retry and replay after rejoin. Temporary services are stopped; Git/media behavior was not exercised. All mandatory push hooks pass, including the broad Rust suite (709.20s) and native/desktop checks (302.32s). - Test churn is **420 lines** (+399/-21); non-test churn is **196 lines** (186 source, 10 maintained docs), versus 279/69 at the preceding head. The new 207-line ingest journey and two-line registration replace the 68-line DB-only target-promotion race; no other authorization or concurrency coverage is removed. - The implementation tree passed 298 core library tests, 1,979 database/relay library tests, and 76 binary/integration-target tests: 2,353 total. Infrastructure-dependent ignored tests were excluded. These runs preceded publication; the publication commit has the identical source tree, with only its commit subject amended. - Disabling the ownership-grant guard made the admission regression fail with `Ok(Owner)`; restoring the guard returned all 298 core tests to green. - At follow-up head `6d4622d3e`, all 769 PostgreSQL tests in the `buzz-db` package profile passed using the repository's per-test database isolation wrapper (PostgreSQL 17.12, UTC; 245 cases outside the selected profile skipped). This includes both new regressions and the existing owner-management journey retained after removing two repeated positive checks. - An isolated native relay passed 18 signed WebSocket operations plus persisted-state checks: admin escalation, co-owner demotion/removal, retained admin management, owner delegation/demotion/removal, and last-owner protection. This membership workflow used local PostgreSQL and Redis; Git/media behavior was not exercised. - PostgreSQL test discovery, formatting, and hosted CI passed at `6d4622d3e`. Maintainer approval and human acceptance remain pending. This relay permission change does not require a client update. Related history: #3017 established bidirectional elevated-role checks and last-owner protection; #8143 introduced the current shared role predicate. This PR adds the Owner-over-Admin distinction to those rules. --------- Signed-off-by: Taylor Ho <taylorkmho@gmail.com> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz> |
||
|
|
97d5a46cc6 |
feat(relay): grow DMs in place, identified by their people (#9125)
## Summary
Lets a DM grow. Today adding someone to a DM always starts a new DM.
This makes the relay side of "growable DMs" work. Joining an existing
DM, and seeing its history, is always opt-in: without `["history",
"include"]` the relay never puts anyone into an existing DM, so older
clients can't add anyone to one unseen.
- **Opt-in tag on kind:41010 and kind:41011.** `["history", "include"]`,
or `["history", "ask"]` on 41011, is the only way anyone joins an
existing DM. Any other value is refused.
- **41011 with the tag:** people and agents join this DM with its
history. When people join, the DM's identity moves to the grown set of
people, so messaging only the original people afterwards starts a new
DM.
- **A DM of at most one person never gains people in place**, even with
the tag. Adding a person to you-and-your-agents starts or opens a DM of
the people, and the original keeps its members. Agents still join it in
place.
- **41011 without the tag:** finds or makes a DM of the source's people
plus whoever is added, as an untagged 41010 does, and adds no one to an
existing DM. Agents already in the source stay behind; agents named in
the add join the new DM.
- **41011 with `["history", "ask"]`:** part of the protocol, because
desktop and mobile use it to know when to ask about history. Agents
alone, and people added to a DM of at most one person, are handled as
with `include`. People who would join a DM of two or more people are
refused with exactly `needs-choice: history` and nothing changes; the
client asks, then sends the add again tagged `include` or untagged.
Agents can't send it, and it isn't accepted on 41010.
- **41010 with the tag:** finds the DM of the named people and adds any
named agents it lacks. A DM still identified by all its members (made
without the tag) moves to its people's identity when reopened this way.
- **41010 without the tag:** finds the DM of those people, which agents
may have joined, or creates a DM of exactly the named members. There is
one DM per group of people, and agents joining it don't fork it
(Morgan's product decision), so no second DM of the same people is ever
created. A DM made this way with agents named gets an all-members
fingerprint, so it never collides with the people's DM.
- **A DM of people is identified by its people.** Agents don't change
which DM it is and don't count toward the 9-person limit. There is no
agent limit, matching channels. A DM with at most one person (you and
your agents) is identified by all its members: an agent joining it moves
its identity, so reopening the original pair starts a new DM.
- **Collisions.** If people join and a DM of the grown set already
exists, the relay returns it (`response:{"channel_id","created":false}`)
and changes nothing here. Agents named with them join that DM. Agents
alone join in place; if the identity the DM would move to is already
taken (only possible for a DM of at most one person, or one still
identified by all its members), the DM gives up its identity, so
reopening its old members starts a new DM.
- **One locked step.** Every DM membership write rereads the DM's
members under its membership lock, checks the agents actually joining,
and compares the DM's identity with the fingerprint actually stored.
Starting a new DM from a DM uses the members it has at that moment.
`created` is true only when this request made the DM, even if a
concurrent open won the race.
- **Agent add policies.** Putting someone else's agent in a DM with
anyone besides you follows its `channel_add_policy`, the same rule as
channels. That covers every agent in a new DM started from another one,
and only the agents that join when a DM grows or is reopened. Messaging
an agent alone ignores it, as today.
- **Only people grow DMs.** An agent can't send the history tag on 41010
or 41011, so a DM an agent opens is identified by all its members and an
agent can't take over or join a DM of its owner's people. Growing never
reveals a DM the actor isn't in. The relay can't be added to any DM.
- **The 9-person limit counts the caller only if they're a person**, so
an agent can open a DM with nine people.
- **A new DM carries people, not agents.** Every fork (Start new DM, the
tagless 41011, a person added to an agent-only DM) holds the source's
people plus the explicit additions. Agents can be added back later, so
no agent's add policy can block Start new DM.
- **Removing an agent keeps an old DM its people's.** A DM identified by
all its members moves to its people's identity when an agent leaves or
is removed, unless they already have a DM.
- **Leaving and removing agents.** kind:9022 lets anyone leave a DM, and
kind:9001 lets you remove yourself or your own agent (as deleting an
agent does). kind:9000 and every other 9001 are refused on DMs; members
join only through 41010/41011.
- **Removals keep identity in step.** When anyone leaves or is removed,
including moderation kicks (which remove members directly in the
database), the DM keeps its identity only if its remaining members still
match it. Otherwise it gives the identity up under the same membership
lock: it keeps its history, and opening that group again starts a new
DM. Removing an agent from a group DM keeps it that group's DM.
- **The relay's moderation DM stays two-party**, on both 41010 and
41011.
- SDK `build_dm_add_member(..., include_history)`, the opt-in
`build_dm_open_with_history` (`build_dm_open` keeps the exact-members
behavior; neither caps pubkeys, since the relay enforces nine people and
agents do not count), and CLI `buzz dms add-member --include-history`.
Without the flag the CLI keeps the old behavior.
Removing other people (beyond moderation kicks) and DM naming are out of
scope.
Client follow-ups: block/buzz-app#2670 (desktop, sends the tag for
history adds, agent adds, and New message opens that show an existing
DM) and the mobile PR (sends it after its choice dialog).
**Deploy this relay change before the app PR merges:** an older relay
ignores the history tag, so the app's Include history would start a new
DM instead.
### Decisions and known gaps
- **No agent cap, on purpose.** This matches channels. The guard is the
add policy instead: every agent the caller doesn't own needs its
`channel_add_policy` to allow it when it joins a DM that holds anyone
besides the caller and that one agent. So a DM stuffed with 40 agents
whose policy is `nobody` is refused. Covered by
`adding_an_agent_follows_its_add_policy` and
`opening_with_several_agents_follows_their_add_policy`.
- **A tagless add opens the DM of the people plus the additions.** Older
clients forking a DM now leave its existing agents behind, as the new
apps do. That shares less than before, never more.
- **Where the protocol is documented.** kind:41010 and kind:41011 have
no NIP today. The history tag is documented on the SDK builders (the
add-member builder also documents `ask` and its `needs-choice: history`
refusal, which it doesn't send) and in the CLI `--include-history` help,
and the `created` field of the response is documented on the SDK
builder.
- **Known gap: lost announcements on retry.** The membership change and
the idempotency record commit separately, the same pattern main uses for
every DM command. If the membership change commits but the idempotency
commit then fails, a client retry finds the members already there and
returns success without posting the join messages, notifications or the
new-DM announcement. Membership and history are correct. This needs a
commit failure between the two writes, and fixing it means moving the DM
writes into the idempotency transaction for all DM commands, so it's out
of scope here.
### Rollout and rollback
- **No kill switch needed.** The new behavior is opt-in per event:
clients that don't send `["history", "include"]` get the old behavior.
- **If the relay rolls back,** DMs that grew are no longer found by
their people, so opening one starts a new DM. History stays in the grown
DM and no data is corrupted.
### Related issue
None found.
### Testing
- Postgres-backed handler tests (`handlers::dm_growth_postgres_tests`,
44 cases) go through `ingest_event`: growing with and without history,
the tagless 41010 and 41011 paths adding no one to an existing DM,
collisions, agents joining in place only with the tag, per-agent owner
DMs, the people-only limit, add policies (including several agents with
no other person), agent actors, not revealing a DM the actor isn't in,
the moderation DM on both kinds, a person added to an agent-only DM with
the tag starting a separate DM, unknown history values, 9000 refused,
leaving, owners removing their agents, kicks releasing or keeping
identity, legacy fingerprints reconciled on agent join and tagged reopen
(with the collision case), an agent joining a one-person DM whose grown
identity is taken, untagged adds that name a person and an agent
starting a DM of exactly those members, `ask` adding agents and refusing
people, untagged opens of a group's people finding their DM with its
agents (after an agent joined in place, and after one of two agents
left), reopening past an existing `owner_only` agent, concurrent opens
all adding their agents, new DMs carrying only people (and named
agents), live membership, the relay key refused, and an agent opening a
nine-person DM. Each new guard was mutation-checked: removing it turns a
test red.
- At
|
||
|
|
f315c7f31f |
feat(workflow): implement send_dm action (#9402)
## Summary
Workflows using `send_dm` currently fail with `NotImplemented`.
Implement the action by creating or reusing a private DM between the
workflow owner and the resolved recipient, then publishing through the
existing relay message path.
- Preserve community scoping, workflow attribution, and authored mention
provenance. Require channel owner/admin authority, as for outbound
webhooks.
- Accept only a fixed hex recipient or `{{trigger.author}}`, including
for previously stored definitions. Require an existing, unbanned
recipient in the run’s community.
- Reuse private conversations without unhiding them or repeating
member-added notices. Retain replaceable discovery events for recovery,
and validate media before creating a conversation. Propagate failures
rather than reporting success.
- Cover template resolution, signed message persistence, conversation
reuse, recipient restrictions, and both agent-mention policy modes.
- Atomically create DMs by participant hash so concurrent first sends
reuse one conversation and only the inserting caller emits membership
notices. Preserve hidden state on workflow reuse.
- Follow current main’s agent-DM policy and per-run mention-authority
gate, including withheld-mention trace output.
### Related issue
None found after searching open issues and PRs for `send_dm`, `SendDm`,
and `sendDm`.
### Testing
- `cargo test -p buzz-workflow`: 176 passed.
- `cargo test -p buzz-relay --lib workflow_sink::tests`: 23 passed.
- PostgreSQL-backed `workflow_sink` tests against an isolated PostgreSQL
17 database: 8 passed.
- `cargo clippy -p buzz-relay -p buzz-workflow --all-targets -- -D
warnings`: passed.
- Concurrent DM creation PostgreSQL regression: passed. A table-lock
barrier forces both callers to INSERT, covering interactive/interactive
and interactive/workflow races, accurate creation flags, and
hidden-state preservation.
- `cargo test -p buzz-db --lib`: 216 passed (763 PostgreSQL tests
ignored); the new PostgreSQL regression was run explicitly.
- Updated `workflow_sink` suite including PostgreSQL integration tests:
31 passed.
- `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings`:
passed.
- Rust formatting, diff whitespace checks, and PostgreSQL test
discovery: passed.
- Pre-push hooks: passed, including the broader Rust unit suites,
desktop/Tauri checks, and file-size gate.
- Previous full `just ci` attempt stopped at unrelated mobile
dependency/formatting checks. Full `just ci` was not rerun after merging
main; targeted tests, lint, and the repository pre-push hooks cover the
updated branch.
Draft pending human testing and the review checklist. Manual check: as a
channel owner/admin, configure a `message_posted` workflow with `action:
send_dm`, `to: '{{trigger.author}}'`, and `text: 'Notice:
{{trigger.text}}'`; trigger it twice as another user. Both rendered
messages should appear in the same private DM with the workflow owner,
and both runs should return a successful send with an event ID. A second
send must not add membership notices or unhide a hidden DM. Plain
members must not be able to save or run this action; arbitrary recipient
templates and unknown/banned recipients must be rejected.
---------
Signed-off-by: Yissachar Radcliffe <yissachar@squareup.com>
|
||
|
|
b303271ad3 |
[buzz] Classify HTTP event request metrics by event type (#9561)
## What Add an `event_type` label to `/events` request-count and latency metrics so operators can inspect and alert on individual operations. ## Why The existing `/events` latency alert combines message sending, profile updates, reactions, typing and identity archive/unarchive into one p95 signal. Slow archive work can trigger the same generic page as slow message sending. The page does not identify which operation is slow or show whether messaging is affected, so on-call has to inspect traces and logs before deciding what needs attention. This change supplies the event-type dimension needed to name the slow operation and choose its notification urgency. Reusing the kind registry also keeps newly registered operations visible automatically. ## How Classify events from the kind already parsed by the HTTP bridge and pass that classification to the outer request timer. Both `http_requests_total` and `http_request_latency_ms` gain a bounded label: - `message`, `profile_update`, `reaction`, `typing` - `identity_archive`, `identity_unarchive` - `kind_<number>` for other kinds registered in the existing `ALL_KINDS` registry, using `registered_kind_label` - `other` for unregistered kinds, `invalid` for malformed event JSON, and `unknown` for requests that fail before parsing New entries in the shared registry automatically receive a distinct metric label without updating a separate metrics list. Friendly names remain for the common operation groups. Latency continues to cover the full request, including admission and processing. Existing metric names and labels remain available, and other routes retain their current labels. Classification uses the existing parse path without changing admission order. No database migration is required. Closest existing PR: none found. --------- Signed-off-by: Helen Tian <htian@squareup.com> |
||
|
|
0dca767e5e |
fix(acp): saturate observer frame size estimates (#9494)
## Summary Use `saturating_add` for the three additions in the observer frame-size estimate. `serialized_len` returns `usize::MAX` on a serialization error; ordinary addition can panic in debug builds or wrap in release builds. Saturation keeps that estimate above the plaintext limit, so the next event stays queued. This is defensive hardening. The current empty envelope contains only JSON-safe fields, so a normal event cannot trigger that serialization error. ### Related issue Follow-up to #9483, addressing [this review suggestion](https://github.com/block/buzz/pull/9483#discussion_r4569450055). No duplicate issue or PR found. ### Testing Manually ran `observer::packing_tests::publish_queue_drain_probe --exact --ignored --nocapture` on the rebuilt debug test executable. All 10,000 events drained in order into 30 frames within the byte limit, with zero pending bytes. To reproduce: ```sh cargo test -p buzz-acp --lib observer::packing_tests::publish_queue_drain_probe -- --exact --ignored --nocapture ``` Generated with AI assistance Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> Co-authored-by: Codex <codex@openai.com> |
||
|
|
6f438202a0 |
Fix remote Huddle ending cleanup (#9376)
## Summary When the final Huddle audio connection was routed through another relay, owner cleanup removed the room without archiving the channel or publishing the ended event, leaving Join visible. Share committed-room finalization across local, remote, and pending-last-slot teardown. Retain the admission gate until finalization and recheck fenced owner authority under the database lock. Relay/database only; mobile history access is separate in #9375. Existing orphaned rooms are not retroactively archived. Existing clients remain responsible for disconnecting agents when the last human device leaves. ### Related issue Related: #4879 / #4918 concern discovery metadata after auto-archive. Searched open Huddle issues/PRs; no exact duplicate found. ### Testing This is the unchanged relay patch previously validated in combined commit `4ec349435151ca11ce92bd0ebe59b845b3465639`, split onto current main (whose intervening change is the relay version/changelog release). - Full PostgreSQL package lane: 1,376 initially passed; both initial failures passed after fixing local psql PATH and using actual joined/teardown completion in the test. Cleanup asserts archival and exactly one ended event. - Remote-control, pending-last-slot, and conditional archival regressions passed. - Full relay/database unit packages: 1,960 passed; five identity/archive and audit fixture failures report missing `artifact_heads` outside changed paths. - Relay/database all-target clippy and legacy desktop clippy/tests passed. Broader pre-push Rust groups passed after rerunning the load-generator group with a higher file-descriptor limit and four test threads (110 passed). - Independent relay review completed; formatting/diff/file-size guards passed. The split reused completed test evidence; no full rebuild was repeated solely for the split. Draft pending human/live-call validation. Start an agent Huddle, leave from the final human device, and verify its card stops offering Join, including connections routed through different relay servers. Not deployed. --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
65b566ca72 |
feat(deletion): clean up media for users and owned agents (#9365)
## Why
User deletion must remove uploads by the user and their owned agents
while preserving files uploaded by anyone else. Attribution can span
communities and survive only in storage, so cleanup must combine
database and storage evidence.
## What
Add one media handler used by both the direct `user-deletions
media-batches` command and the persisted user-deletion workflow. Preview
is read-only by default; deletion requires `--delete`.
The workflow now always runs `gate_user` → `purge_media` → community
stages. The gate and community handlers remain placeholders. Media
failure stays on the same stage for retry; a saved completed media stage
is not executed again on restart.
## How
- Resolve the human and directly owned agents once across communities.
Sharing within that target set does not protect a file.
- Combine candidate discovery from `media_uploaders` and upload audit
history with a sharing check for those hashes. Check outside uploaders
across all communities. Storage-only candidates receive the same
database check in batches.
- Add four nonunique indexes for uploader and hash lookups. Current
membership cannot safely filter historical discovery: departed members
may have no remaining membership row.
- Scan `_uploads/` for candidates, then candidate claims for outside
ownership. List blob and thumbnail versions by each selected `{hash}.`
prefix. A separate `_meta/` listing preserves sidecar coverage when no
matching claim or current membership remains. There is no whole-bucket
listing.
- Finish all discovery before deletion. Read historical claims using
exact `versionId` values. Delete exclusive file versions and markers,
with upload-attribution objects last. Remove target uploader rows after
storage processing succeeds. Shared storage versions and outside
uploader rows remain.
- Stream one JSON document with file identity, keep/delete status,
versions, and outcome counts. Remove per-file owner queries and owner
arrays. Workflow stdout remains inspection JSON; media reporting goes to
stderr.
Database/inventory pages hold at most 500 rows. Storage listings use at
most 1,000 entries per page and 100,000 pages per listing. A disposable
in-memory inventory has a 128 MiB accounting budget and a 250,000-entry
cap, including candidates, filenames, versions, and listing markers.
Accounting includes string bytes, inline data, and a conservative
allowance for tree/allocator overhead; it is not a process RSS limit.
This removes the SQLite dependency without a security-policy exception.
Large jobs may reach capacity sooner than with the former 1 GiB disk
inventory. Exceeding a discovery limit aborts before mutation; no
truncated inventory is used for deletion.
Migration 0092 and the desired schema add the same indexes. The
migration builds missing indexes under short lock/statement budgets and
verifies existing definitions. Large deployments can prebuild
concurrently using the procedure in [the executor
guide](docs/operator-user-deletion-executor.md). Existing relay writes
remain compatible. A stale workflow test call from the merged main
branch also receives its required run-cause argument.
## Risk
This performs real storage deletion. Writers must remain stopped; the
placeholder gate does not prevent uploads. Immutable version IDs are
required for exclusive objects. All results report
`account_erasure_complete: false`. Existing synthetic progress saved
under the older gate-to-community sequence is not migrated into the new
sequence.
Shared storage claims and audit history remain. They can continue
protecting a blob after both uploaders leave; claim retirement is
separate work. Metadata namespace scans remain proportional to their
sizes. Bare blobs with no surviving attribution cannot be assigned to a
user.
## Testing
Before committing the replacement as
`38c60be7f6c3ee3f6942ab89858ce42e2a536c5d`, exercised the actual
`buzz-admin user-deletions media-batches` command against a fresh local
PostgreSQL database and versioned MinIO bucket. Preview preserved all 23
versions and all database rows. Deletion removed 14 exclusive versions,
preserved nine shared/unrelated versions, and removed only five target
uploader rows. Retry removed no further versions; events and
publications remained unchanged.
A standalone probe of the production inventory reached the default byte
budget after 243,148 short-key versions or 90,933 versions with 1 KiB
keys. Peak process RSS was approximately 108 MiB and 124 MiB on macOS;
these measurements describe the probe, not total command memory.
Manually removed `versionId` from the production adapter's request and
ran `cargo test -p buzz-deletion --lib
historical_claim_protects_shared_file_and_bad_claim_aborts_before_deletion`.
The regression failed because the historical outside uploader no longer
protected the file. Restored the adapter before final validation.
Earlier live-lab evidence used the direct command at
`633fdb2a48dce64f904c0077689704f136c722c1`, before this query/storage
update: 38 exclusive files and 300 versions were deleted; 24 shared
files and 10 unrelated files remained. Authenticated downloads returned
404 for all deleted originals and matching hashes for all preserved
originals. That live deletion was not repeated for this update, and does
not attest concurrent-upload safety or complete account erasure.
## Bigger picture
Media tracking:
[BUZZ-415](https://linear.app/squareup/issue/BUZZ-415/delete-user-and-owned-agent-media-and-storage-objects).
Deleted-image UI is separate work:
[BUZZ-727](https://linear.app/squareup/issue/BUZZ-727/show-a-clear-unavailable-state-for-deleted-images-in-chat-and-image).
Related: #9353. This replaces the media portion of #9329 and #9355;
those branches remain intact.
Generated with Codex
---------
Signed-off-by: Ravneet Arora <rarora@squareup.com>
Signed-off-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: salad <7be12d8db721c3c6d5feccf11f8389e39c6b4b717dc6aa7ce30fc80e45e8788f@buzz.block.builderlab.xyz>
|
||
|
|
63f1d6918c |
Refuse opening a private channel that has other members (#9307)
## Summary - Turning a private channel open changes who can read and join it for everyone who joined while it was private. The relay now refuses that change when the channel has, or once had, any other member. - Removed members count too, because their posts stay in the history that opening would make public. - Opening is still allowed when every member, current or removed, is the person making the change or one of that person's agents. A Solo chat that holds only its owner and the owner's agents is the main case. - Changing an open channel to private is unchanged. - A refused change stores nothing. The sender gets: `invalid: a private channel with other members cannot be made open; create a new open channel instead`. ## Details - The check is in the channel metadata edit path (kind:9002), for every channel type. An agent counts as the sender's own only when its owner is recorded for it through an owner attestation (NIP-OA). A member who has never signed in, or an agent with no recorded owner, counts as another member. - The check runs under the membership lock that a visibility change already takes. Members cannot be added between the check and the commit. - Disclosure levels for agents do not exist yet, so all of the sender's own agents may stay when the sender opens a channel. When levels land, restricted writers will need to be excluded. - `update_channel` in the store does not apply this rule. Only tests call it. User edits go through kind:9002. Both doc comments say so. - Old desktop builds can still send an opening edit. They now get the refusal as an error. - `NOSTR.md` documents the refusal on the kind:9002 row. ### Related issue None found. The client UX is in https://github.com/block/buzz-app/pull/3145. ### Testing - New Postgres tests in `edit_metadata_postgres_tests.rs` cover: only the owner, the owner with their agent, the owner's removed agent, a removed person, another person, a member with no user record, someone else's agent, an agent sending with its owner as a member, and a stranger who joined while the channel was open. - Each refused case checks that the channel stays private and nothing is stored. The tests fail when the check is removed, when it skips removed members, or when the user join is made inner. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
df21064800 |
feat(auth): tolerate client clocks up to 120 s off (#9485)
Lets clients whose clocks are up to 120 s off sign in to NIP-FI communities and stay connected. **Relay** - NIP-42 AUTH and NIP-98 HTTP Auth accept `created_at` within ±120 s, using a shared `buzz_auth::TIMESTAMP_TOLERANCE_SECS`. This covers relay login, audio admission, bridge, admin, invites, NIP-FI policy and Git. - `DEFAULT_REPLAY_TTL_SECS` goes from 120 to 250 s: a 2 × 120 s window, plus 1 s for the inclusive whole-second bounds, plus a 9 s budget for the clock difference between relay pods. A compile-time assert checks the arithmetic. The 9 s is an operational assumption about NTP-synced pods, and the doc comment says so. No `deploy/` override exists. - Media (kind 24242): - Both modes accept `created_at` up to 120 s in the future and an `expiration` greater than `now − 120`. - Strict: the 120 s age limit and the 60 s lifetime cap. - Permissive: keeps its 3600 s age allowance and has no lifetime cap. - `buzz-auth` and `buzz-media` read the time through a `wall_now()` that tests can pin (a `#[cfg(test)]` thread-local), so boundary tests are exact. - Git transport: comments only. It still reuses one proof per session, so the reuse window now matches ±120 s. **CLI** - The desktop-provider lane asks the desktop app for the assertion every time and keeps no copy, so the desktop's cache owns each token's deadline. It looks the token up again after signing and sends that one, so a provider may hand out a new token on every call. - The direct-mint cache sets its deadline to `min(request_start + (exp − iat), receipt + (exp − local_now))`, on a monotonic clock. `request_start` is when the attempt that got the reply was sent, not the start of the retry loop. - An assertion with no local lifetime left is never returned or sent. The cache asks again, up to 3 times, then fails with an auth error that points at the computer's clock. An assertion without a readable `iat` is refused. `iat` may be fractional (a NumericDate); the lifetime is `max(0, floor(exp − iat))` whole seconds. **Cache reuse (CLI, Flutter, iOS):** each cached token records when it arrived on both the monotonic and the wall clock. It is reused only while `max(monotonic elapsed, wall elapsed)` since arrival is under its budget (`refresh point − receipt`, on the monotonic clock). A negative wall elapsed counts as 0. The monotonic clocks used here stop while the device sleeps, so the wall clock ends reuse after a sleep; setting the wall clock back can't stretch a token, because the monotonic bound still applies. **Mobile** - Flutter `HostedRelayAuth`: the same lifetime rule, on a monotonic clock, for async acquisition and for the synchronous `cachedHeaders` media path. A token with no local lifetime left is never sent: issuance is retried up to 3 times, then fails as `unavailable`. A token without a readable `iat` fails as `invalidResponse`. - Flutter refusal hint: the account client reads `Date` when a 403's headers arrive, before the body (`boundedHttpResponse` gains an `onHeaders` callback). The 403 stays `AccountFailure.denied` even if its body is then lost, late or too large. The hint is stored with the refusal it explains (`HostedRelayAuth.failureClockHint`), cleared when that community next gets a token or the account session changes, and left alone by other communities' issuance. The account client records a 403's hint only for the acquisition whose own request was refused (`BuilderlabAccountClient.observingRefusals`), so an unrelated account call, such as the organization key backup, never supplies a sign-in's hint. When the offset is over 115 s, the reconnect and organization banners add "Your device's clock looks about N minutes off, which can cause this. Check your date and time settings." - iOS `BuzzRelayAssertionIssuer`: the same lifetime rule, on `systemUptime`. An assertion without a readable `iat` is refused. - iOS push enrollment: a new grant's window starts 120 s in the past, so `not_before = now − 120` and `expires_at = now − 120 + lifetime`. A fast phone then neither signs a `not_before` the gateway hasn't reached nor goes over its 30-day maximum. A resumed journal resubmits the installation expiry it already attested, byte for byte. The delegation, which is signed fresh each time, expires at the earlier of that expiry and `not_before + lifetime`, so a journal written by an older client on a fast phone still gets a grant the gateway accepts. The saved grant records the delegation's expiry. - Flutter and iOS already sign a fresh proof with a `nonce` on every issuer attempt, so their retries needed no change. **Specs:** NIP-FA proof bounds (120 s old / 120 s future), plus NIP-FI Git (`±120s`), media freshness, the media read residual and the media trace row. `desktop/` is untouched. Not exercised live: Git clone/push, audio join and push delivery with a skewed client clock. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
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> |
||
|
|
9398918fa5 |
feat(push-gateway): accept deliveries on a platform-neutral route (#9557)
First slice of the Android push plan ([design PR](https://github.com/block/buzz/pull/9555)). The push gateway should serve every platform from one delivery route, so the relay never learns an installation's platform (see ADR 0004 in the design PR). ### What changes - The gateway accepts deliveries at `POST /v1/deliveries`. `POST /v1/deliveries/apns` keeps working unchanged as an alias until relays have moved over. - `BUZZ_PUSH_GATEWAY_DELIVERY_URL` accepts either path. The deployment guide and NIP-PL describe `/v1/deliveries` as the route to use. `.env.example` and the compose template stay on `/v1/deliveries/apns`, because released relays (`relay-v0.3.0` and older `sha-` images) refuse to start with the new path even with push disabled, and the public gateway doesn't route it yet. A later change moves them over. - Signature binding: the gateway already verified only the method and the signed URL's path (not scheme, host or port). It compared that path to a constant. It now compares it to the route the request arrived on, so a request signed for one route is rejected on the other. Each route accepts only requests signed for its own path. - The lease `transport` value, priority classes and the delivery request body are unchanged, and nothing about the device platform reaches the relay. ### Regressions None expected. iOS keeps working: the alias route behaves exactly as before, and relays configured with the old URL keep signing and sending to it. The signed path check is equivalent on that route, since it now compares against the same path the old constant held. Rollout order matters. Don't point a relay at `/v1/deliveries` until (1) its gateway runs this change and (2) for `push.buzz.xyz`, the edge path allowlist in front of the gateway admits `/v1/deliveries`. Today that edge answers `403 RBAC: access denied` there. The relay also needs a build that includes this parser. An old gateway's 404 or the edge's 403 is a permanent failure for the relay (on a retry, it counts as replay-terminal), so those notifications are dropped, not retried. ### Validation - Gateway delivery tests are table-driven across both routes: path-not-origin binding, signed URL modifiers and non-HTTP schemes, request queries, method and path routing, and new cross-route rows (signed for `/v1/deliveries`, sent to the alias, and the reverse, both rejected). - Relay config tests cover both paths over HTTP and HTTPS, plus rejected variants (trailing slash, query, fragment, credentials, other paths, HTTPS ports). - Ran the gateway crate's tests, the relay crate's unit tests (single-threaded, because the default parallel run of the whole lib hung in untouched tests waiting on shared env locks), formatting and clippy for both crates, and the repository's pre-push checks. - Relay tests that need Postgres were not run locally. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
69742376a9 |
Revert "feat(relay): agents cannot write in DMs except with their own… (#9500)
…er (#9371)"
This reverts commit
|
||
|
|
fc29f6068a |
fix(relay): stamp each NIP-IA archive list strictly after the previous one (#9476)
### Why When an admin archives or unarchives an identity, the relay publishes a new archived identities list (kind 13535). This list replaces the previous one. It contains all the identities that are archived in the community. Clients use it to hide archived agents from pickers and search. The list can be large (about 228 KB on Block's Builderlab), and it seldom changes. Thus the mobile app wants to download it only when it changed. To do this, the app keeps the last list it received, and asks the relay only for a list that is newer than that one (`since` its `created_at` plus one, in [#9445 archive list cache](https://github.com/block/buzz/pull/9445)). This works only if each new list has a `created_at` that is later than the previous list's. Today the relay does not always do this: - The relay calculates the new list's `created_at` as "the current list's `created_at` plus one second". But it reads the current list before it gets the lock that controls replacement. - Thus, when two archive requests occur at the same time, two publishers can read the same current list. Then both sign a list with the same `created_at`. The store keeps the one with the lower event id. - A client that already has the other list does not see the replacement, because it asks only for lists with a later `created_at`. It continues to hide or show the wrong agents until the next archive change or an app restart. - With many concurrent publishers it is worse: a publisher can lose that tie again and again, and then stop with `failed to publish kind:13535 after 8 concurrent replacements`. Then no list contains the latest archive change. ### What changes - New `Db::replace_addressable_event_after_head`. It gets the replacement lock first. Then it reads the current list. Then it signs and stores the new list. Thus only one publisher at a time calculates the next `created_at`, and each list is stamped strictly later than the previous one. - `publish_nipia_archival_list` uses this method. The check that publishes again when the archive state changed during a publish does not change. - NIP-IA now makes this a rule: a relay MUST publish each `kind:13535` with a `created_at` strictly greater than its previous one. Clients MAY then ask only for lists `since` their list's `created_at` plus one. ### Validation New relay test: 16 concurrent publishers all complete, and each stored list (superseded rows included) has a strictly later `created_at`. On main the same test fails, because a publisher uses all its retries. The test needs Postgres and Redis, so it is in `postgres_tests` and runs in the PostgreSQL Tests lane; a missing database or Redis makes it fail, not pass. The existing archive tests pass against a local Postgres, including the stale-publisher test. `just test` passes all 160 steps except one NIP-FI session deadline test (`deadline_refused_permit_still_queues_one_denial_when_cancel_wins`), which this change does not touch and which passes 5 of 5 reruns alone. Clippy passes. ### Regressions None expected. - A publisher now holds the replacement lock a little longer: for one read and one signature. Only archive-list writes for the same community wait on this lock, and archive changes are rare. - The new `Db` method is an addition. `replace_addressable_event` and its callers do not change. - Until this is deployed, relays keep the old behavior. [#9445 archive list cache](https://github.com/block/buzz/pull/9445) accepts that same-second case on its own. **Accepted limitation: a database restore.** The rule holds only while the relay keeps its newest list. If an operator restores the relay from a backup, the relay calculates the next `created_at` from the restored list (`max(restored + 1, now)`). If earlier fast publishes went ahead of the clock, that value can be at or below a `created_at` that a client already has. That client then stays stale until a list passes its cached `created_at`, or the app restarts. This change adds no repair for a restore. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
5780bd7d94 |
perf(acp): avoid repeated observer batch serialization (#9483)
Replaces #9413 with the packing optimization refreshed against main on a branch in this repository. ## Summary Busy agent activity streams repeatedly build and serialize a growing JSON batch just to check whether the next event fits. Reuse cached event sizes, measure the newest outer envelope, and build the batch payload once per completed frame. Preserve the wire format, greedy packing, per-channel order, channel barriers, byte budget, and one-frame-per-second relay cadence. Exact-limit coverage checks escaping, UTF-8, optional metadata, and array separators. Move the queue tests into a separate module to satisfy the file-size rule; their test names stay unchanged. ### Related issue Related to #7987. This builds on the merged fitting/locking work in #9381 and retention limits in #9436. Closest earlier batching work: #4917. No duplicate packing fix found among open PRs. ### Testing The ignored probe fills the production queue before timing, drains every event, and checks complete FIFO delivery, frame byte limits, and empty byte accounting. ```sh CARGO_INCREMENTAL=0 CARGO_PROFILE_RELEASE_LTO=thin CARGO_PROFILE_RELEASE_CODEGEN_UNITS=4 \ cargo test --release -p buzz-acp --lib observer::packing_tests::publish_queue_drain_probe -- \ --exact --ignored --nocapture BUZZ_OBSERVER_PROBE_EVENTS=100 cargo test --release -p buzz-acp --lib \ observer::packing_tests::publish_queue_drain_probe -- --exact --ignored --nocapture ``` Five alternating fresh release processes per arm and workload compared baseline `59ae028a3` with candidate `237b928b9` on macOS arm64, Rust 1.98.1. Both arms used `opt-level=3`, thin LTO and four codegen units, with incremental compilation and compiler-cache wrappers off. Each executable was rebuilt separately and its probe identity verified. Medians: | Events | Before | After | Frames in both arms | | --- | ---: | ---: | ---: | | 100 | 6.760 ms | 0.108 ms | 1 | | 10,000 | 1,597.509 ms | 7.844 ms | 30 | The one-event control measured 2.04 → 2.21 microseconds. The timed region covers packing only; ingestion, validation, encryption, publish pacing, relay delivery, and rendering are excluded. These local results do not establish an overall app latency improvement. No timing threshold was added to CI. Native and deployed-relay latency, independent review, and human verification remain pending. Keep this PR in draft. Generated with AI assistance Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> Co-authored-by: Codex <codex@openai.com> |
||
|
|
97188e90c6 |
test(cli,db): freeze the assertion test clock and give pool release tests a test-lane acquire budget (#9442)
## Summary Two Rust tests failed on loaded CI runners because their timing budget came from the wall clock or from a production timeout, not from the behavior they assert. Each fix changes only test code or `cfg(test)` code. Commits (cherry-picked unchanged from a local flake-fix series): - `test(cli): freeze the test clock in the assertion refresh tests` - `test(db): give the pool release Postgres tests a test-lane acquire budget` ### Root cause and fix per test **`federated_identity::tests::short_and_long_assertions_refresh_at_the_earlier_point`** and its twin in `desktop_provider` (`crates/buzz-cli`): failed in CI with `assertion left == right failed: lifetime 300`, left 2, right 1, at `federated_identity.rs:634`. - CI sighting, 11 November 2026, "Rust / Unit Tests", run 43122921918 attempt 1 (on #9342; the rerun passed): - https://github.com/block/buzz/actions/runs/43122921918/job/130868244938 - Root cause: under `cfg(test)`, `cached_assertion::unix_now()` was the wall clock plus a thread-local skew. The mock stamps `exp = unix_now() + lifetime`, then `CachedAssertion::get` computes `refresh_at(unix_now(), exp)` after the HTTP round trip, and the next call checks `unix_now() < refresh`. The test needed those reads to agree to the second. When the wall clock crossed a second boundary between them, the refresh point moved 1 s earlier, `advance(refresh - 1)` landed exactly on it, and the assertion was minted one step early. - Fix: a thread-local `FROZEN` base beside `SKEW`, and `test_clock::freeze(at)` to pin it. Under `cfg(test)`, `unix_now()` returns `FROZEN.unwrap_or(real_now) + SKEW`, so `advance` and its existing callers in `client.rs` behave as before. Both tests freeze the clock at the top of their loop body. The mock adapter runs on the same current-thread runtime, so `exp`, `refresh_at` and the check share one "now". Production code paths are unchanged. - Verification: each test run 1,440 times, 24 in parallel, before and after. `federated_identity`: 4 failures before, 0 after. `desktop_provider`: 1 failure before, 0 after. - Not seen in CI: the `desktop_provider` twin. It passed in the job above and is fixed here because it has the same race and failed locally. **`runtime::postgres_tests::pool_release_postgres_tests::silence_after_release_hook_does_not_strand_sqlx_ping`** (`crates/buzz-db`): panicked at `pool_release_postgres_tests.rs:204:10` with ``called `Result::unwrap()` on an `Err` value: PoolTimedOut`` after 0.85 s. - CI sighting, 10 November 2026, "PostgreSQL Domain / PostgreSQL Tests", run 42851548618 attempt 1 (on #8317; the rerun passed): - https://github.com/block/buzz/actions/runs/42851548618/job/129969964659 - Root cause: the test built its pool from the production `Db::read_pool_options`, whose 150 ms `READER_ACQUIRE_TIMEOUT` also bounded `connect_with`'s eager first dial (and `fresh_query`'s). On a busy runner the cold dial through `PausingProxy`, SCRAM and the reader `after_connect` hook overran it, so the test panicked at the initial `connect_with(...).unwrap()` before the release-hook recovery path it asserts ever ran. Production is not exposed: the relay dials the reader pool lazily, so that budget only governs request-time acquires, which fall back to the writer by design. - Fix: a 30 s `TEST_LANE_ACQUIRE_TIMEOUT` on both pool builders in this file: the reader test's `PoolOptions`, and `writer_pool`'s `DbConfig`, whose eagerly dialed 3 s default is the same exposure #9273 fixed for buzz-admin. `test_before_acquire(false)`, `after_connect` and `after_release` stay as in production, and recovery still completes at sqlx's 5 s return deadline inside the test's 10 s `await_capacity` budget. No assertions change. - Verification, against a local Postgres: 10 rounds of `pool_release_postgres_tests --ignored --test-threads=6` per binary. Before, 2 of 10 rounds failed at `:204:10` with `PoolTimedOut`, the CI signature. After, 0 of 10. Under 28 CPU busy loops, with before and after runs interleaved: 6 of 10 failed before, 0 of 10 after. - Not done here: `reader_pool_postgres_tests.rs` already carries its own 5 s test budget on `read_pool_options` for the same reason. This PR does not unify the two constants. One sighting of each failure was found in the CI runs from 7 to 12 November 2026 that were searched. ### Related issue N/A (flake fixes). No existing issue was found, and no open PR touches these tests or the four files changed here. ### Testing Human testing is still required. This PR does not carry `buzz-review-completed`; the author has not yet run these tests themselves on this branch. The repetition counts above were measured when the fixes were written, before this branch was split out. They were not repeated on this branch. #### Local checks on this branch The branch is one commit behind `main`; that commit changes only mobile and docs files, none of them touched here. Ran and passed at push time, on a checkout of this branch's head (`42b3faccc`): the organization push check, `branch-skew`, `push-head-scope`, `file-size-check` and git-lfs. Did not run: - The `rust-tests` and `desktop-tauri-checks` pre-push lanes. They were excluded from the push (`LEFTHOOK_EXCLUDE`) because the machine ran out of disk part-way through them on an earlier attempt. That attempt did not complete, so it proves nothing either way about this branch. - The desktop and mobile pre-push lanes (`desktop-check`, `desktop-typecheck`, `desktop-test`, `mobile-checks`). This diff touches no desktop or mobile file. - `cargo fmt --check`, `cargo clippy`, `just ci`, and the PostgreSQL lane. CI's Unit Tests and PostgreSQL Tests jobs are the gate for this branch. A green run does not prove the flakes are gone: both failures need a loaded runner. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: mtoohey <mtoohey@squareup.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
359839f70b |
feat(db): label advisory-lock metrics with the locked event kind (#9472)
## Why
On one deployment,
`buzz_db_advisory_lock_wait_seconds{lock_type="replacement"}` added up
to about 245,000 seconds of wait in 7 days. The metric cannot say which
coordinates wait. Replacement locks serialize writers of one `(kind,
pubkey[, d_tag | channel])` coordinate. Relay-owned lists (kinds 13535,
39000–39002) go through the same generic replacement paths as user
replaceables (kinds 0, 3, 10002, 30078, …). The 13534 membership list
takes its coordinate lock under `lock_type="membership"`. Before we
change how these lists are stored, we need to know which kinds the wait
comes from.
## What
- `buzz_db_advisory_lock_wait_seconds` and
`buzz_db_advisory_lock_acquisitions_total` get a `kind` label.
- Locks keyed by an event coordinate record that coordinate's kind,
through the new `observe_event_lock(lock_type, kind, …)`. This covers
all 4 replacement call sites (parameterized replace,
`take_replacement_lock` for addressable replace and group-state
snapshots, the kind:39002 member snapshot, and workflow deletion) and
the kind:13534 membership-list lock. The 13534 lock keeps
`lock_type="membership"`, so totals by `lock_type` do not change.
- All other locks record `kind="none"`, and their call sites do not
change. `observe_advisory_lock` has a `debug_assert` that rejects
`LockType::Replacement`, so a replacement lock cannot lose its kind by
mistake.
- `buzz_core::kind::registered_kind_label(kind)` gives the label value:
the decimal kind when it is in `ALL_KINDS`, otherwise `other`.
## Change to the #6700 label contract
#6700 says no database metric carries event kinds, and
`observability_source.rs` enforces this with a blanket ban on `"kind"
=>`. This PR makes one narrow exception: the two advisory-lock metrics.
- **Bounded:** the value set is the kind registry, not request data. Of
the 135 registered kinds, 39 are replaceable or addressable and can
reach a replacement lock. Any other kind a client sends becomes `other`.
Non-replacement locks are always `none`. New series in the worst case:
39 kinds × 4 outcomes, for the histogram and the counter.
- **Not sensitive:** no community, pubkey, coordinate, or d-tag is
attached. The kind of a replacement lock does not expose any of those.
- **The guard is narrowed, not removed:** `"kind" =>` must appear
exactly twice, inside the advisory-lock observer `observe_lock`, whose
kind must come from `registered_kind_label` inside `observe_event_lock`.
It is still forbidden everywhere else in `observability.rs` and in the
datastore tracing macro. The #7195 guard that forbids a literal
`"other"` in `observability.rs` is unchanged, because the fallback lives
in `buzz-core`.
## Dashboards and alerts
Both metrics gain a label, so existing selectors keep working:
`lock_type="replacement"` still matches every replacement series,
because Prometheus and Datadog selectors match on a subset of labels. A
consumer is affected only if it depends on the exact label set:
- Recording rules or panels that read a series without aggregating it
now get one series per kind. Aggregate with `sum by (lock_type, outcome)
(...)` to keep the old shape.
- Vector matching with `on(lock_type, outcome)` or `ignoring(...)` now
has more series on one side. Aggregate before the join.
To read the new attribution, group by `kind`, for example `sum by
(lock_type, kind) (rate(buzz_db_advisory_lock_wait_seconds_sum[5m]))`.
No consumer in this repository depends on the exact label set.
## Tests
- `buzz-core`: `registered_kind_label_bounds_unregistered_kinds` checks
that a registered kind passes through and that an unregistered or
negative kind becomes `other`.
- `buzz-db` recorder test: checks the replacement series for a
registered kind (`13534`) and an unregistered kind (`other`), and the
`kind="none"` series for a membership lock, on both metrics.
- `kindless_observer_rejects_replacement_locks`: the `debug_assert`
guard panics.
- `membership_list_lock_records_the_roster_kind` (Postgres): a 13534
list write records exactly one `membership` acquisition with
`kind="13534"`.
- `group_state_replacement_takes_its_lock_once` (Postgres): now counts
acquisitions only under the written kind. It expects `kind="39000"` for
the group-state snapshot path and `kind="0"` for
`replace_addressable_event`, so if `take_replacement_lock` drops or
swaps the kind, the count becomes 0 and the test fails.
- `observability_source.rs`: the narrowed guard described above.
Commands run:
- `cargo clippy --workspace --all-targets -- -D warnings`
- `cargo test -p buzz-core --lib`
- `cargo test -p buzz-db --lib`
- `cargo test -p buzz-db --test observability_source`
- `scripts/postgres-test-run.sh -p buzz-db --lib --tests` (the CI
PostgreSQL lane, run locally)
## Local relay check
The relay ran from this branch against an isolated database. `/metrics`
showed one series per locked kind after each write:
- `users set-profile`: `replacement`, `kind="0"`
- `users set-status`: `replacement`, `kind="30315"`
- `channels create`: `replacement`, `kind="39000"`, `"39001"`, `"39002"`
- `channels add-member`: `replacement`, `kind="39002"`
- `agents archive`: `replacement`, `kind="13535"`
- `moderation ban`: `replacement`, `kind="30622"`, plus `membership`,
`kind="none"`
- Invite mint and claim
(`e2e_relay::test_invite_mint_and_claim_admits_new_pubkey`):
`membership`, `kind="13534"`
- Background loops: `deletion` and `partition_maintenance`,
`kind="none"`
`buzz_db_advisory_lock_wait_seconds_count` matched
`buzz_db_advisory_lock_acquisitions_total` for every series. The author
also tested it against the local relay.
buzz-review-completed
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
1fb33e4545 |
fix(relay): publish a git push only when refs changed; check the protocol by refinement (#9425)
## Summary This PR is stacked on #9064. It does two things to the Git-on-object-storage code in `buzz-relay`. It replaces the TLA+ model of the push protocol with one that states what the protocol is supposed to implement and checks that it does. It also changes the rule by which the relay decides whether to publish a push, because the new model shows that the rule #9064 introduces still publishes requests in which git accepted nothing. ### Relationship to #9064 The branch is `main`, then the two commits of #9064, then four commits of this PR: the specification work, the publish-rule change, a review fix merged from #9429, and a fix to `check.sh`. A merge of `main` follows them; it was needed because `main` changed `Justfile`, which #9429 also edits, after the branch point. The first two commits are #9064's, replayed onto current `main` without conflicts and otherwise unchanged. The base of this PR stays `main` because #9064's branch is about 200 commits behind it. Once #9064 merges, this branch can be rebased and the diff shrinks to the last four commits. Until then, review the commits after the first two. This PR keeps two of #9064's three changes as they are: the `published_at` stamp that orders kind:30618 events by the manifest chain, and `protect_landed`, which lets a landed conditional write stand when the serving lease lapses after it. It replaces the third, the publish rule. ### The publish rule #9064 publishes when git exits 0 and the status report has an `ok` line or no `ng` line. That handles a push in which one ref is updated and another refused. The report, however, is not evidence of what git did. - git exits 0 for a request that carries no commands, and for a push the pre-receive hook declined. A decline is reported only to a client that negotiated `report-status`. For a request with no commands, and for a decline when the client did not negotiate a report, there is no `ng` line. The relay then writes the pointer and emits a relay-signed kind:30618 event that names the caller as pusher, although the push policy approved nothing. - The report is read from a stream whose framing the client's capabilities determine, so the decision depends on parsing a client-shaped stream. The decision is now taken from the workspace. `push_disposition` compares the refs after receive-pack with the refs the workspace was hydrated from. Unchanged refs are answered with git's own output and nothing is published. Changed refs are published if git exited normally. Changed refs after an abnormal exit fail the request. The snapshot that is compared is the one `cas_publish` publishes, so git's per-ref report is true of the published state. The status-report scanner and its tests are removed, and the ref-name conflict case they covered moves into the table-driven test described below. Three smaller changes follow. The ref-snapshot parser now fails closed: output that was not UTF-8 used to read as an empty ref set and a malformed line was skipped, and either would publish a manifest that lacks refs. `manifest_changed` in `finalize_push` could not be false and is removed. Taking the snapshot before the publish decision moved its resource-limit error (snapshot larger than 4 MiB, or more refs than a manifest may hold) onto a path that answered 500; #9429 restores the 413 the publish path gave before and adds `snapshot_resource_limit_answers_413`. ### What the specification work adds - `docs/spec/GitRefDB.tla` is the specification: a ref database in which a push takes effect in one step, is applied only if authorized and only against the old values it names, and is reported truthfully. - `docs/spec/GitOnObjectStore.tla` is the protocol: several refs, an object graph with reachability, packs, compaction, the pre-receive hook, the publish decision, the default-branch setter, repository creation, and a reader. `git receive-pack` is represented by a stated contract rather than modeled internally. - The correctness statement is `Refines`: every behavior of the protocol is a behavior of the specification. TLC checks it together with the store invariants (fence, reader completeness, closure of published manifests). - `docs/spec/check.sh` pins TLC 1.7.4 by SHA-256 and runs 28 checks. Eight instances must pass. Nineteen seeded design errors must each be detected with the violation named for them. One coverage check confirms that a behavior the properties depend on (git reporting `ok` for a command that changes nothing) is reachable. A name passed to `check.sh` that is not a check is an error, so a misspelled selection cannot report success. - Both earlier publish rules are among the seeded errors: the original rule (exit 0 and no `ng`) and #9064's status-report rule. For each, TLC reports a publication the policy did not approve (`PublishIsAuthorizedChange`) and a violation of `Refines`. - `docs/spec/GitPushPath.qnt`, the Quint model from #9064 that covers the serving lease and the event timestamps, is extended. The publish rule becomes a parameter with three values, a request may carry no commands or come from a client without a status report, and a new invariant, `publicationChangesRefs`, states that a published manifest differs in its refs from the one it replaces. The implemented rule satisfies all four invariants; the status-report rule violates the new one with a zero-command request. - `docs/spec/lean/GitPointer.lean` is a Lean 4 proof, with no dependencies, of the pointer discipline for any number of clients, refs and objects: the fence, closure, that every pointer change is a legal step from the value it replaces, that the length of the pointer's predecessor chain equals the number of pointer writes, and that a successful conditional write implies no intervening write. - `.github/workflows/spec.yml` runs TLC and Lean when a file under `docs/spec/` changes. On this PR's first run the TLC job took 10 minutes 19 seconds and the Lean job 22 seconds. Quint is not run in CI. - `docs/git-on-object-storage.md` is revised to match. The push listing follows the implemented order. The verification section separates definitions, assumptions, results checked by TLC, results proved in Lean, results checked with Quint, evidence about the implementation, and limitations. The invariant names cited by code comments and by migration 0002 are kept as aliases in the TLA+ module. ### Assumptions and limitations The TLC results hold for the bounded instances in `check.sh`, not for arbitrary sizes. The Lean proof is unbounded but covers the pointer discipline only, not the refinement. The Quint results are from random simulation (2,000,000 runs of at most 14 steps) and a bounded symbolic check (8 steps, Apalache); neither is a proof for unbounded runs. All of them rest on the assumptions named in the document: the object store's conditional-write semantics, ETag equality implying body equality, no SHA-256 collision among the values that occur, the stated contract for `git receive-pack`, and the policy endpoint deciding authorization. The correspondence between the models and the Rust code is established by reading the code and by the tests below; it is not mechanized. The document states one assumption that #9064's ordering fix depends on and that no model covers (Assumption C1). A manifest whose parent carries no `published_at` (the empty manifest written when a repository is announced, or a manifest written before the field existed) is stamped with the writing instance's current time plus one second. Its event is selected over the parent's only if that value exceeds the parent event's `created_at`, which was taken from the clock of the instance that emitted it. This holds when one instance handles both, and otherwise when the writing instance's clock is not behind the other's by more than the time elapsed between the two events. The assumption concerns one write per repository. The document lists its removal as a proposed extension, for example by having the first push after an unstamped manifest read the stored event's `created_at` and exceed it. ### Related issue Related to #2621 (CI for the formal models). This adds the TLC job for the git model and a Lean job; it does not cover the Tamarin models or the NIP-PL scripts, so it should not close that issue. ### Testing Run locally on the restacked branch: - `docs/spec/check.sh`: 28 checks, each with the expected result (8 pass, 19 seeded errors violate the named property, 1 coverage witness reached). About three minutes on 16 cores; the largest instance has 6,773,286 distinct states. - `lake build` in `docs/spec/lean` (Lean 4.33.1): succeeds. The safety theorems depend only on `propext`, `Classical.choice` and `Quot.sound`. - Quint 0.33.0, `GitPushPath.qnt`: `quint run --main fixed --invariant safety --max-steps 14 --max-samples 2000000 --seed 0x1` reports no violation; `quint verify --main fixed --invariant safety --max-steps 8` (Apalache 0.62.1) reports no violation; each single-defect module produces the counterexample the document lists. - `cargo fmt --all -- --check` and `cargo clippy -p buzz-relay --all-targets -- -D warnings`: clean. - `cargo nextest run -p buzz-relay --lib -E 'test(/^api: |
||
|
|
bd031a05af |
fix(acp): bound observer retention by bytes (#7987) (#9436)
Replaces #9366 on a branch in this repository and resolves its conflicts
with main.
## Summary
The ACP observer kept up to 1,000 raw events in both replay and live
buffers. Large valid messages could retain gigabytes before downstream
trimming ran.
Fit telemetry before either buffer retains it. Cap replay at 4 MiB of
serialized JSON and keep the existing live window. Its per-event limit
bounds live JSON below 64 MiB.
Preserve the CPU and locking improvements from #9381: prepare large
payloads and copy snapshots outside the replay lock. Finalize sequence
and timestamp with publication. Account for that final metadata,
including sequence digit-width changes, in the byte limit.
The tradeoffs are extra work per emit, shorter replay history for large
events, and elided oversized telemetry. Agent protocol messages remain
unchanged.
### Related issue
Fixes #7987. Existing publisher byte limits act downstream of these
buffers.
### Testing
The opt-in probe exercises the real in-process emit, snapshot and
stalled-subscriber paths:
```sh
CARGO_INCREMENTAL=0 CARGO_PROFILE_RELEASE_LTO=thin CARGO_PROFILE_RELEASE_CODEGEN_UNITS=4 \
cargo test --release -p buzz-acp --lib observer::tests::retention_probe -- --exact --ignored --nocapture
```
Compared baseline `a314975ce` with candidate `c2df3cb56` on macOS arm64,
Rust 1.98.1. The baseline observer, fitter, workspace manifest and
lockfile match the candidate's parent `8f3f4e266`. Both arms use
`opt-level=3`, thin LTO and four codegen units, with incremental
compilation and compiler-cache wrappers off. This profile is fixed for
the comparison; this PR does not change build settings.
Values are medians of three fresh-process runs per version and workload,
in alternating order. Peak RSS comes from `/usr/bin/time -l` around each
test executable; compilation is excluded. Each version was rebuilt
separately and its executable and workload identity verified.
| Workload | Peak RSS before → after | Emit time per event before →
after |
| --- | --- | --- |
| 10,000 × 1 KiB | 14.0 → 14.1 MiB | 0.47 → 0.89 µs |
| 1,000 × 60,000 bytes | 199.4 → 80.8 MiB | 8.54 → 22.53 µs |
| 1,000 × 1 MiB | 3,025.8 → 26.4 MiB | 123.50 → 307.89 µs |
For the 1 MiB workload, replay JSON fell from 1,000.2 MiB to 3.997 MiB.
Live JSON fell from 1,000.2 MiB to 5.91 MiB. Replay retained 676 fitted
events; the live subscriber received all 1,000.
Emit time includes payload construction. Peak RSS includes snapshot and
receive copies made by the probe. JSON budgets are not exact heap
limits. These local measurements show the memory/CPU tradeoff;
concurrent producer throughput and native app latency were not
benchmarked. See [the probe
instructions](
|
||
|
|
279a31daac |
buzz-search: read profile names without the profile_name_fields function (#9397)
## What
This is phase 1 of 2 for retiring the plpgsql function
`profile_name_fields(text)`. Its only caller, profile name search
(`search_profile_names`), now gets `name` and `display_name` from an
inline SQL expression (`PROFILE_NAME_FIELDS` in
`crates/buzz-search/src/query.rs`) instead.
The function's exception handler made unreadable kind:0 content have no
names rather than fail the search. The inline version keeps that
guarantee in two steps:
- **`pg_input_is_valid(content, 'jsonb')`** rejects the soft parse
errors: a `\^@` escape, a lone surrogate, a huge number, and malformed
JSON.
- **A bracket bound for deep nesting.** PostgreSQL's JSON parser is
recursive. Past about 10k levels at the default `max_stack_depth`, it
raises `stack depth limit exceeded`, and `pg_input_is_valid` does not
catch that. I confirmed this on PG 17: depth 10k is fine and 20k raises.
So content with more than 4096 `[` and `{` is never parsed and has no
names. The count bounds the depth. Ingest already rejects kind:0 content
nested deeper than 128 levels (serde_json), so this only matters for
content stored another way.
`OFFSET 0` keeps the parse from being copied into each reference to
`doc`, so each candidate row is parsed once, plus one validity pass. The
plpgsql function also parsed each row once.
**Behavior change (edge only):** a kind:0 with more than 4096 brackets,
even inside strings, is no longer findable by name. Real profiles don't
come close, and a `picture` data URL is base64 with no brackets.
`pg_input_is_valid` needs PostgreSQL 16 or later. CI runs 16, and the
dev compose runs 17.
**Phase 2 (not here):** a migration and desired-state change drops the
function, its `schema/functions/` file and its `schema.sql` entry once
this release has shipped.
## Tests
- `profile_names_survive_unparsable_content` already stores a `\^@`
profile, a lone-surrogate profile, a `1e1000000` profile and a 60k-deep
profile next to a plain one, and requires the search to return only the
plain one. It now also covers the bound itself: a profile with exactly
4096 brackets, all but one inside a string, is still found.
- Must-fail mutants, each run on Blox: bracket bound removed (the search
fails with a stack overflow), validity check removed, bound tightened by
one, and the string-type check loosened.
## What got simpler
Profile search no longer depends on a database function. Name extraction
lives next to the rest of the search SQL it feeds.
## Verification
Blox, at `be0db303ea90033cc2c37ac8f8f07c27f4b08e31` (clean tree):
| Gate | Result |
|---|---|
| `cargo fmt --all --check` | pass |
| `cargo clippy -p buzz-search --all-targets -- -D warnings` | pass |
| `cargo nextest run -p buzz-search --lib` | 4/4 |
| `scripts/postgres-test-run.sh -p buzz-search --tests -E
'test(/profile_names/)'` | 4/4 |
| Must-fail mutants (no bound, no validity check, bound tightened by
one, non-string names allowed) | 4/4 killed |
Probe on PostgreSQL 17.11: `pg_input_is_valid` returns false for `\^@`,
a lone surrogate, `1e1000000` and truncated JSON; nesting depth 10k is
valid; depth 20k raises `stack depth limit exceeded`. 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>
|
