mirror of
https://github.com/block/buzz.git
synced 2026-11-27 19:52:31 +00:00
6b0dfc1957fb6cb87d40b5c3bd6570aa7e8a896e
1048 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
6b0dfc1957 |
feat(search): sign OpenSearch requests with AWS SigV4 (#9947)
## Summary The relay's OpenSearch client could only use HTTP basic auth. Amazon OpenSearch Serverless accepts only requests signed with AWS SigV4, and managed Amazon OpenSearch Service domains can require them, so the relay could not index into either. This PR adds optional SigV4 signing. It is off by default; basic auth and unauthenticated clusters work as before. | Variable | Meaning | | --- | --- | | `BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE` | Turns signing on and names the signing service: `aoss` for a Serverless collection, `es` for a managed domain. Unset means no signing. | | `BUZZ_OPENSEARCH_AWS_REGION` | Region to sign for. Defaults to `AWS_REGION`, then `AWS_DEFAULT_REGION`. | The relay refuses to start when signing is set without a region, together with basic auth, without `BUZZ_OPENSEARCH_URL`, or with a service other than `es` or `aoss`. - **Credentials** come from the AWS default chain: environment variables, the shared profile, a web identity token, then the container or instance role. No keys are added to the relay's own settings. - **Refresh** (`aws_credentials.rs`): the `opensearch` crate asks its credentials provider on every request, and the AWS default chain does not cache. Used directly, every search and bulk write would call the token service or the instance metadata endpoint. The relay keeps one set of credentials and reloads it five minutes before it expires (every 15 minutes for credentials without an expiry). Each load builds the AWS provider anew, because a kept one never rereads the shared profile; a key rotated there is picked up at the next load. Concurrent requests share one load, whether it succeeds or fails: the next load starts at least 30 s after the last one ended, and requests in between use the valid set or fail at once. A first load is bounded at 30 s. A reload while the current set is still valid is bounded at 5 s, and if it fails the current set stays in use. - **Logging:** a failed credential load logs only the kind of error, because the causes can carry what a `credential_process` helper printed. The AWS SDK logs the full cause itself under `aws_config` at warn level, which the relay's default log filter leaves out; the deployment doc says how to turn it on and what it can contain. Credentials are never logged, and the config's `Debug` output shows only the service and region. - **Dependencies:** enables the `opensearch` crate's `aws-auth` feature and adds `aws-config` for the credential chain. ### Worth knowing - The region is not read from the shared AWS profile file, only from the variables above. - Right after a Serverless collection became active, the first signed request got HTTP 401 once; the same run passed 45 s later. The indexer already retries such failures. - A Serverless collection does not support `_refresh`, which only the tests' `SearchIndex::refresh` uses. ### Related issue N/A. Closest existing work: #9838 (the OpenSearch index this client writes to) and #9862. No duplicate found. ### Testing - Unit tests: startup validation of the new settings; credentials are loaded once, survive a failed reload, a failed first load is not repeated per request, requests waiting on a stalled load share its one failure, and a key rotated in a shared profile file is picked up. - Local, unauthenticated OpenSearch 2.19.3: the `postgres_opensearch_search` suite, plus index create, bulk write, search, bulk delete and index delete through `SearchIndex`. - Verified against an Amazon OpenSearch Serverless collection through `SearchIndex` with `aoss` signing and credentials from a shared profile: alias check, index create, bulk write of documents with `community:event_id` ids, search (3 hits), bulk delete of one document, search (2 hits), index delete. On the same collection an unsigned client got HTTP 403 for search and bulk write, and a client signing for `es` got HTTP 403. - The relay binary refuses to start with signing and no region, and with signing plus basic auth. - Not run: a managed domain (`es` signing), and the web identity, container and instance role credential sources. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Salman Mohammed <smohammed@squareup.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
cb4a83a406 |
feat(relay): add percentage-based NIP-FI enforcement rollout in shadow mode (#9758)
Adds `BUZZ_NIP_FI_ENFORCE_PERCENT`, a permanent operator setting for moving a relay from `shadow` to `enforce` in stages. While the relay runs in `shadow`, it enforces NIP-FI for a stable, growing share of communities (integer 0-100, default 0, read at startup). Operators raise it in steps, watch denials, then switch to `BUZZ_NIP_FI_MODE=enforce`, where the setting has no effect. Unset, behaviour is unchanged. - **Cohort:** a community is in when `rollout_bucket(id) < percent`. The bucket is SHA-256 over the UUID's 16 RFC 4122 big-endian bytes, first 8 bytes as a big-endian `u64`, mod 100. Cohorts are nested as the percentage rises and stable across renames. Golden vectors freeze the hash. - **One helper:** `NipFiRelayConfig::policy_required(id, stored)` returns `stored || in_rollout`, and only shadow mode widens it; `NipFiRelayConfig::effective_mode(id, stored)` applies it to the relay mode. They feed every field of the three `Policy` constructions (`resolve`, `bind_for_upgrade`, and live-socket revalidation), so a rollout community gets the same admission, upgrade, NIP-11 `requires_nip_fi`, binding check, `configured_mode` and deny-map guard as a stored-Required one. `Policy::stored_required` is renamed `policy_required` to match. - **Stored policy stays raw:** the host cache, `CommunityAuthPolicy`, stored-policy writes, the upgrade drain and the CAS/receipt fields don't change. Operator `effective_required` reports the derived requirement through `effective_mode`. - **Validation:** a malformed or out-of-range value refuses startup in every mode. Outside shadow the setting has no effect. - **Precedence:** a community stored Required always enforces, at any percentage, so lowering the percentage never stops it. A community stored Optional that falls inside the cohort can't opt out: a stored disable succeeds but enforcement stays on, and the only way to drop it is to lower the percentage to its bucket or below, which also drops every community in a higher bucket. - **Logging:** the `nip-fi enforce deny` and `nip-fi enforce session end` lines move to target `buzz_relay::nip_fi_enforce`, so a log filter can keep real denials while suppressing shadow would-deny volume. Startup logs one `NIP-FI config loaded` info line (target `buzz_relay`) with `mode` and `enforce_percent`, so pods running different percentages during a rollout show up in log search. - **Docs:** `docs/operator-nip-fi-bindings.md` gains a "Staged enforce" runbook step between Shadow and Enforce, with go/no-go signals, rollback (lower the percentage) and its cost: each change is a full rollout, and there is no per-community exemption. A required admission is refused when the receiving pod holds an active deny for the key; revocation closes open connections only in `enforce`, as for stored-Required communities today. Denies live only in each pod's memory and spread asynchronously, so a restarted pod, or an `enforce` pod during the switch from `shadow`, can miss one; the key can then sign in until its outstanding assertions expire (the issuer's `maximum_assertion_age_seconds` plus `skew_seconds`, if the issuer stops issuing), and finishing a rollout does not restore missed denies. The runbook describes recovery, not continuity: re-push freshly signed disconnect commands once the new pods are serving (resent old commands can fail replay and command-age checks), or wait out the bound counted from when the issuer stopped issuing. A revoked key can still be admitted before recovery, and in `shadow` a later re-push does not close a connection opened in that window. The Enforce step leaves the percentage at 100, where it has no effect. Its rollback for admission failures sets `shadow` and lowers the percentage to the last known-good value; a mode-only rollback at 100 still requires every community. Never roll back with `off`, which also turns off stored-Required enforcement. A stored disable makes reconnects optional only when the effective policy becomes optional. The upgrade runbook, community auth doc, `ARCHITECTURE.md` and the multi-tenant conformance table say cohort communities are required in `shadow` too. The NIP-FI spec drops its Buzz implementation note and describes capability advertisement in generic terms; its normative `MAY` is unchanged. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
5e11b5380f |
feat(search): index deletes and edits, backfill stored messages, run several indexer workers (#9862)
## Summary Follows #9838 (merged), which copies each new message into OpenSearch through a Postgres queue table (`search_outbox`). That PR left three gaps: the index never hears about deletes or edits, messages stored before the feature was on are never indexed, and one failed item or a busy cluster stalls the whole queue. This PR closes them. Searches still run on Postgres only. **Deletes, edits and scrubs reach the index.** A deleted message, an edit (kind 40003) and an account-deletion scrub each add a queue row in the same transaction as the change. The indexer re-reads the message and upserts or deletes its document. A source check in `crates/buzz-db/tests/observability_source.rs` fails when a new write path to `events` skips the queue. **Backfill.** A new table, `search_backfill` (migration 0107), holds one cursor per community. The lease holder walks stored messages newest first and feeds them into the same queue in bounded batches. It tops up only while the queue is short, so live messages never wait behind history. Progress shows in `buzz_search_backfill_*` and `buzz_search_indexed_documents_total`. **Failures and load.** The bulk response is now read per item. Rows that succeeded are completed; the rest stay queued. A 429 from OpenSearch backs the indexer off with jitter. A batch over 8 MiB goes out as several bulk requests, so a cluster with a 10 MiB request limit no longer refuses a full batch (HTTP 413) and pins that community's queue. The lease has jitter too, so a fleet restart does not send every relay at the lock at once. **Several workers.** `BUZZ_SEARCH_INDEXER_WORKERS` (1 to 32, default 1) runs that many workers on the lease holder. Each community's rows fall into 64 fixed partitions by the first byte of the event id. A batch takes transaction-level advisory locks on a share of partitions and claims only their rows. Two workers can never hold rows for the same message. With the default of 1 the behavior is the same as before. **Late writes cannot undo newer ones.** A bulk request can still be applied after its batch ended, when the relay crashed or the request timed out. Every item now carries an external version: the next value of a new sequence, `search_index_version` (migration 0108), read while the batch holds its partitions. OpenSearch keeps the highest version, so the late request is refused. If a live batch is refused (HTTP 409), its rows stay queued, the pass backs off, and `buzz_search_index_version_conflicts_total` counts it; that counter should stay at zero. **Fixes from review.** - Account deletion that runs outside the relay queues its scrubs once an indexing relay has ever started (`search_outbox::enable_if_indexed`). Enabling the queue takes a value from the version sequence, which keeps that fact while the queue and the backfill table are both empty. - A relay that takes the lease republishes `buzz_search_backfill_complete` for every community from stored progress. The guide now says `1` means queued, not indexed. - The guide says to set the URL on every relay in one deploy, and to delete the index if a relay ran without it; the relay then rebuilds it. Resetting the backfill alone is not enough: the backfill reads only live messages, so it leaves documents of messages deleted in the meantime. - The searchable kinds come from the edit-governed kinds instead of a second copy. - A community fenced for deletion no longer stalls the backfill of the others. - The indexer does not write to an index until 30 seconds after its creation, whichever relay holds the lease: a relay that takes over reads the index's creation time and waits out the rest. On OpenSearch Serverless, a write sent just after creating an index that replaces a recently written, deleted one can be acknowledged by the deleted index and lost. Replayed with signed requests, that happened in 92 of 220 runs when the first bulk went out at once, and in none of 220 when it waited 30 seconds. - Bulk writes get 60 seconds instead of 30; a first bulk into a new Serverless index took 20 seconds. Searches keep 30. - When a batch goes out as several bulk requests and a later one fails, the rows of the requests already applied are completed. Before, the whole batch stayed queued, so a later request that kept failing pinned the community's queue. - Account deletion checks for an indexing relay in every batch, inside the batch's transaction, instead of once per job. A relay that turned indexing on for the first time while a deletion job ran could index a message before the job scrubbed it, and nothing queued the removal. - The randomized consistency test clears the whole queue, so it now refuses to run unless the test script gave it a database of its own. - A missing index gets its history back. When the indexer finds neither the alias nor the index, it clears the backfill progress, then creates the index, so every community is backfilled again. Clearing first means a crash between the two steps leaves the index missing and the next pass repeats both. Only a 404 counts as missing; a failed or throttled lookup is an error and the pass retries. Before, a recreated index kept the old progress and stayed empty. - The guide's known gaps now describe the late case that matters: an older write that lands more than 60 seconds after a newer delete brings the document back. It also covers a version sequence left behind by a point-in-time restore or a logical-replication cut-over, and what to do when `buzz_search_index_rejected_total` rises. Worth knowing: - Documents of a purged community stay in the index for now. Search re-reads every hit from Postgres and re-checks access, so they can never be returned. For that reason the `BUZZ_OPENSEARCH_PREVIEW` opt-in from #9838 stays required, with its message reworded. - #9871 (merged) must be deployed before migrations `0107` and `0108` run. It lets community deletion accept `search_backfill` before the migration creates it. - A removed document can no longer be found, but its text stays in the index's files until OpenSearch merges them. The relay does not force that merge. - The sequence adds a `schema/sequences/` directory and widens the layout rule in `docs/database.md` to allow it. `pg_current_xact_id()` would need no schema change, but its values do not carry over to a new cluster built by logical replication. - Two rare cases can leave a stale document in the index until the message changes again or the index is rebuilt. One is an older write applied more than 60 seconds (the index's `gc_deletes` window) after a newer delete of the same message. The other is a Postgres crash or the promotion of an asynchronous replica while an older request is still pending, followed by a newer write of the same message. Search re-reads every hit from Postgres, so stale or deleted text is never shown. `docs/opensearch-search-deployment.md` describes both. - The indexer still holds one transaction open per batch, as in #9838. ### Related issue N/A. Follows #9838. ### Testing On a laptop, against a local Postgres and OpenSearch 2.19.3 with 1 million synthetic messages: - A real relay on this stack backfilled the stored messages, then indexed live messages, edits and deletes. With OpenSearch stopped, writes kept working and rows queued; they drained after it came back. - Drain rate of a full queue was about 8k, 14k, 17k and 29k documents per second at 1, 2, 4 and 8 workers. - A randomized test, `the_index_converges_on_postgres_under_interleaving`, runs concurrent sends, edits and deletes against several workers with injected timeouts, crashes and late-applied requests, then checks that the index equals Postgres. 300 seeds passed in each of three modes: plain, late requests, and the sequence set back. It found the late-write defect above before the fix (20 of 200 seeds failed), and it fails on 36 of 100 seeds when a 409 is treated as done. - `a_late_request_from_before_a_clock_step_changes_nothing` and `a_late_write_cannot_undo_a_newer_one` fail without the version and pass with it. - Send latency with the queue on was unchanged at 50 and 150 messages per second. A saturated relay lost 8 to 15% of its throughput. The queue adds about 0.5 KB of WAL per message. After the rebase onto `main`: 198 Postgres and OpenSearch tests pass locally (queue, backfill, migrations, community deletion, and every `buzz-search` test), and clippy is clean. The request splitting has a unit test only; no test sends a real batch over 8 MiB. On Amazon OpenSearch Serverless, the relay's index definition, versioned bulk writes and deletes, the 409 on a stale write and its search requests were replayed with signed `curl` requests and behave as on a self-hosted cluster. `gc_deletes` cannot be raised there, so the 60-second default applies. The relay itself has not run against Serverless: it needs request signing (#9947). The 30-second wait was measured there with replayed requests only, and whether Serverless returns an index's creation time has not been checked; without it a relay that takes over waits the full 30 seconds. Not tested: production-shaped data. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Salman Mohammed <smohammed@squareup.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
df46b827b1 |
fix(cli): attach custom emoji tags when editing a message (#9694)
**ELI5:** When you edit a message from the command line and add a custom emoji such as `👋`, it now shows up as the emoji instead of the literal text, just as it already does when you send a new message. ## Summary `buzz messages edit` published kind 40003 edits without NIP-30 `emoji` tags, so a custom-emoji shortcode introduced by an edit rendered as plain text. The desktop app already prefers emoji tags carried on an edit, and the relay already validates them on edits, so the gap was only in the CLI. - `buzz-sdk`: new `build_edit_with_tags`, which adds emoji tags alongside media tags. `build_edit_with_media` delegates to it. - `buzz-cli`: `emoji_tags_for_content` is shared by `messages send` (kind 9) and both `messages edit` paths. As on send, a palette fetch failure warns and continues without emoji tags. ### Related issue None found. ### Testing - New unit test `edit_attaches_emoji_tags` (buzz-sdk) and CLI test `command_attaches_emoji_tags_for_known_shortcodes` (kinds 9 and 7, known and unknown shortcodes). - Full pre-push suite passed (`rust-tests`, `desktop-tauri-checks`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Jeremy Mawson <jmawson@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
2870f3150c |
fix(pubsub): drop Redis pub/sub sockets that stop answering (#9918)
## Summary
The relay's Redis pub/sub subscribers (event fan-out, cache
invalidation, community connection control, NIP-FI disconnects) waited
on their message streams with no deadline. A socket the network dropped
silently looked like a quiet channel, and the pod missed every message
on it until it restarted.
A shared `keepalive` helper in `buzz-pubsub` now bounds every pub/sub
connection:
- **Setup and control requests.** Connect, handshake, and every
`SUBSCRIBE`/`PSUBSCRIBE`/`UNSUBSCRIBE` (including the fan-out
subscriber's dynamic subscribes and confirmations) must get a reply
within 5 s.
- **Heartbeat.** A single pinned future, polled next to the message
stream, sends `PING` every 15 s and fails if a reply doesn't arrive
within 5 s. Messages keep being forwarded while a `PING` is pending, and
incoming traffic can't reset its deadline.
- **Exit.** Any missed deadline returns an error from the connection
function, dropping both halves of the connection (closing the socket).
The existing reconnect loop with backoff takes over.
A dead socket is detected within about 20 s (15 s interval + 5 s
deadline) under normal scheduling. Reconnect backoff comes on top of
that. Messages that weren't read before the connection is dropped aren't
replayed by this change.
## Tests
The tests run against a scripted RESP2 server in the test module, which
can withhold `PING` or subscribe replies, push messages, and report when
a client socket closes. They need no Redis and are added to `just
test-unit` and `scripts/run-tests.sh`.
-
`conn_control::tests::keepalive::nip_fi_subscriber_forwards_while_pong_withheld_then_drops_socket`:
with a `PING` reply withheld, a NIP-FI disconnect is delivered before
the subscriber exits. With the reply never sent, the subscriber returns
a timeout and its socket closes. Fails if the loop awaits `PING` inline.
-
`subscriber::tests::keepalive::stalled_dynamic_confirm_is_not_confirmed_and_drops_socket`:
a stalled dynamic subscribe isn't confirmed, and the connection is
dropped. Fails without the subscribe deadline.
-
`conn_control::tests::keepalive::conn_control_subscriber_drops_socket_when_pong_withheld`
-
`conn_control::tests::keepalive::nip_fi_subscriber_fails_stalled_subscribe`
-
`subscriber::tests::keepalive::subscriber_drops_socket_when_pong_withheld`
-
`cache_invalidation::tests::subscriber_drops_socket_when_pong_withheld`
- `keepalive::tests::{heartbeat_fails_when_pong_withheld,
heartbeat_keeps_running_while_pongs_arrive,
bounded_fails_stalled_subscribe}`
---------
Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
|
||
|
|
c4c97119c3 |
fix(mobile): end a refused push opt-out in a visible failure with Retry (#9854)
## Summary Turning push notifications off could stay stuck forever. If the relay kept rejecting the opt-out tombstone, `setPushNotificationsEnabled(false)` swallowed the rejection, and the push bootstrap retried the tombstone on every connect, including after restarts. Settings showed the switch off the whole time, while the relay still held the lease. [docs/mobile-push-suppression.md](https://github.com/block/buzz/blob/main/docs/mobile-push-suppression.md) (rule 29) asks for the opposite: a bounded pending state, then a clear warning that notifications may continue, with no automatic retry, and the relay's actual setting on the next sync. - **Bounded pending.** An opt-out ends about 10 seconds after the tap, across every step (capability lookup, connect, authenticate, publish). While it runs, the row says "Turning off…" and the switch is held, so Off, On, Off can't race the first attempt. - **Definite vs. maybe stored.** A one-shot publish now says whether the relay could have seen the event: a refusal, or a failure before the EVENT went out, is definite; a lost acknowledgment after it went out is not. - **Refused: back to the confirmed setting.** When the relay never stored the tombstone, the saved setting goes back to On (the confirmed lease) and Settings shows "Could not confirm that notifications were turned off. Notifications may continue." with a **Retry** below it. The warning lasts for this app run; after a restart, Settings just shows On. - **Maybe stored: kept as a guard, then read back.** When the acknowledgment was lost, the saved opt-out stays as a guard (no lease or enrollment is published, and the community stays in the iOS notification snapshot), while Settings shows the confirmed On with the same warning. On the next sync, the app reads its own lease from the relay: an inactive lease or none confirms Off; an active one turns the switch back On and keeps the warning. A read that fails changes nothing and is tried again on the next connect. The read asks the relay for strong consistency, so a lagging replica can't answer with the lease the tombstone replaced. It fails if the active community changes while it waits, and it settles only the opt-out it was started for, so a Retry made during the read stays pending. - **No flash on success.** Settings reads the community from the community list, which changes in the same step as each opt-out result. The active-community projection trails it by a keychain read, which could show an accepted opt-out as failed for a frame. - **Explicit retry only.** Retry, or turning the switch off again, makes one attempt at a new generation. The bootstrap's automatic tombstone retry is removed. The warning is announced to screen readers when it appears, and Retry has its own label. This applies to every platform: the opt-out path is shared. ### Related issue None found. ### Testing - The Settings recovery journey covers a refusal restoring On with the warning, a restart that drops the warning and makes no attempt, an attempt that never answers (held switch, then the deadline, kept as a guard), a restart that keeps that warning, and a Retry that succeeds. It runs with loading, absent and failed capability, and on a small phone at text scale 2. - The toggle journey, with the real push bootstrap, covers a refusal (a reconnect neither retries nor reads), an unanswered attempt and a lease that's still active: the read on reconnect, a failed read that changes nothing, then Off or On from what the relay holds. - One-shot publish rows: a relay that stalls at authentication fails as never sent; one that stalls at OK, or closes after the EVENT, fails as maybe stored, all by the deadline. - Lease reader rows: the exact strong-read filter, an empty answer, and a community switch during the descriptor fetch or the query. A provider row holds a read while a Retry fails unanswered: the old read leaves the new opt-out pending. - A widget test with slow secure storage checks every frame of an accepted opt-out for the warning. - A relay database test reads back the author's inactive replacement lease with the filter the app uses, and the lease decryption is checked against the member's own and forged events. ### Screenshots After the relay refuses the opt-out (no relay push capability, so the toggle is reachable only because push is on). | Before | After | | --- | --- | | <img src="https://raw.githubusercontent.com/block/buzz/d2e3c753b3068a68728199096bf30e45e8948af7/pr-9854--before.png" width="300" alt="Before: switch shows off while notifications may continue"> | <img src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--after.png" width="300" alt="After: switch back on, with the warning and Retry below it"> | At text scale 2 on a small phone, Retry sits below the warning: <img src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--after-large-text.png" width="250" alt="Large text: warning readable, Retry below it"> While an opt-out attempt is in flight (new), the switch is held: <img src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--turning-off.png" width="300" alt="Notifications row with the subtitle Turning off and the switch held"> --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
309f5827b1 |
fix(push-gateway): keep Android enrollment retryable across replay races and restarts (#9893)
Follow-up to [#9811 enroll Android devices for push](https://github.com/block/buzz/pull/9811), covering the gateway side of its non-blocking review comments. Two enrollment states could make an Android phone discard a key its committed installation still holds, after which its fresh enrollment hits `409 installation_conflict` for the installation's whole lifetime (up to about 30 days of no push). Both now answer in a way the client already treats as "keep the key and retry". - **Enrollment replay racing the original request** ([review comment](https://github.com/block/buzz/pull/9811#discussion_r4648232889)). Enrollment consumed its challenge in one statement and created the installation in another. A client that timed out between them and replayed the same signed request found a spent challenge and no installation, and got `404 not_authorized`. Consuming the challenge and creating the installation are now one transaction. A concurrent replay locks the challenge row before judging its expiry, so it waits even when the challenge expires meanwhile, then returns the installation the first request committed, or enrolls itself if that request rolled back or was cancelled. A request that finds its challenge expired deletes it before answering `404`, so a slower request that read its clock earlier cannot spend it afterwards. A refused creation (`409`) also leaves the challenge unspent. - **Enrollment before the attestation status list loads.** A restarted gateway has no status list until its first refresh (and a list past its grace period is equally unusable), so every Android chain was refused with `401 invalid_attestation`, which the client treats as final. The verifier now reports a missing or stale list as unavailable, and enrollment answers `503 temporarily_unavailable` before spending anything. A listed certificate is still refused. - **NIP-PL** now specifies Android enrollment: the `android_attestation` chain and FCM token request, the `buzz.push.enroll.android.v1` transcript whose SHA-256 is the Keystore attestation challenge, what the gateway checks in the chain, and the SHA256withECDSA signature Android installation calls carry in `assertion`. It also records the two behaviors above, corrects the enrollment body ceiling for the Android chain allowance, names the transcript separator as one LF byte, and says a client stores its installation handle before delegating (replay recovery ends once a delegation extends the installation's expiry). ### Validation Added tests: - [`enrollment_replay_waits_for_an_uncommitted_enrollment`]( |
||
|
|
e8a8e4cb6a |
feat(nip-fi): scope disconnects to tokens issued through revoke_through, stored durably (#9917)
## Summary Builds on #9860 (merged as `c0932db19c`). A NIP-FI disconnect command can now carry `revoke_through` (C), an integral NumericDate. With C, the relay refuses and closes only assertions whose verified signed `iat` is at or before C, until `until`. Tokens issued after C are admitted straight away. Without C, the deny covers the whole key, as before. - **Spec:** `docs/nips/NIP-FI.md` adds the `revoke_through` claim and a Deny scope section (admission, close scope, merging, records, the issuer's duty) with a behavioral oracle. The existing deny, command-algorithm, oracle and security text now carry scope. The deny set's storage text is #9860's (shared storage, restored before admission); this PR adds no wire claim or storage schema to the spec. - **Parsing:** a `revoke_through` that is `null`, nonnumeric, fractional or unrepresentable is rejected as `evidence_rejected` before any state changes. - **Verified `iat`:** `VerifiedAssertion::issued_at()` comes from the time-checked `iat`, not from profile evidence. `NipFiSession` records it at registration. - **One predicate:** `DenyScope::covers` compares the full verified instant (fractional `iat` included) against C. It decides admission (WebSocket and HTTP, with asserted key and owner checked separately) and every close scan (root and audio registries, the command route, cross-pod delivery, shadow accounting). - **Merge:** `DenyEntry::merge` takes the later `until`. Whole-key beats a cutoff, two cutoffs merge to the larger C, and expired entries contribute nothing. Activity is read from a clock sampled inside the issuer shard lock, so an entry that expires while a merge waits contributes nothing. A past-`until` command still does its scoped close without changing an active entry. The close scope widens to any stronger active entry, and a poisoned shard closes the whole key. - **Bus:** `NipFiDisconnect.revoke_through` is optional. A message without it means whole-key. - **Durable cutoff (Redis):** the cutoff lives in its own per-issuer hash, `<deny prefix>-revoke-through:<sha256(iss)>`, field `pubkey_hex`, value C. The exact-`until` hash keeps only `secs:nanos`. One accept script merges `until` and scope by the same rule as `DenyEntry::merge` and gives all three keys one expiry. It judges whether the command and the stored entry are still active by Redis `TIME` as it runs, not by the authentication clock. Before any write it checks the target's stored cutoff by restore's rule: a disconnect over an unreadable one returns `unreadable`, `try_claim` fails (`503`), the claim stays unused and nothing is recorded. Restore judges expiry when it merges. Restore reads both hashes in one script and joins them before merging, looking deny keys up in a set (linear at capacity), so a missing cutoff field is a whole-key deny. A cutoff that isn't an integer, or names no deny, is `reason="unreadable"`. As in #9860, one bad record does not hide the others: restore still applies every readable deny (a deny under a malformed cutoff as the whole key; an orphan cutoff adds nothing) and then fails, so admission stays closed. `LoadDenies` and `LoadDeniesError::Unreadable { readable }` now carry `DenyEntry`, and a restore counts a same-`until` scope widening as changed, so it closes the sessions it newly covers. - **Runbook:** `docs/operator-nip-fi-bindings.md` names the cutoff hash and how to clear a bad cutoff. It warns that deleting an orphaned cutoff leaves no deny at all, and that a disconnect over a bad stored cutoff fails until it is cleared. ## Deploy and rollback Deploy this to every relay pod before any issuer sends `revoke_through`. Until then, a pod still on the old build ignores the claim and blocks the whole key, so the agent stays locked out until its old token expires. Rolling a relay back to #9860 is safe. That build reads only the exact-`until` hash, which this PR writes in the same format, so it restores every cutoff as a whole-key deny and never fails its restore on this data. It ignores `revoke_through` in commands and bus messages, and every accept it makes clears the target's stored cutoff, so its whole-key revokes are never narrowed by a cutoff this build stored. All of this only over-blocks: agents wait for their old tokens to expire instead of getting back in at once. ## Testing Behavior tests cover old and fresh tokens at admission and in close scans, redelivery leaving fresh root and audio sessions open, cross-pod delivery, an owner whole-key deny blocking a fresh agent token, same-deadline scope changes in both orders, an expired whole-key entry followed by a cutoff, past-`until` commands, invalid `revoke_through` values, legacy bus messages, fractional `iat` at C and C + 0.5 through real verification, replay-claim waits that cross an entry's expiry, and root/audio handler straddle cases where the signed `iat` differs from registration time. Each of these was checked to fail when the code it guards is broken: - the route's published bus message keeps the cutoff on another pod (fails if `nip_fi_disconnect_message` drops `revoke_through`); - a cutoff command over an active whole-key entry closes a fresh session (fails if the route skips close-scope widening); - a poisoned shard's close scope is whole-key; - shadow `would_close` ends only sessions issued at or before C; - a cutoff in Redis restores as a cutoff (fails if the accept script stops writing the cutoff hash), and #9860's reader, taken from its final head `02627cce`, decodes the same record as a whole-key deny; - #9860's writer, copied verbatim from `02627cce`, writing over a stored cutoff with an equal or shorter `until`, then a fresh restore by this build, gives a whole-key deny; - a full revoke that expires between authentication and its Redis write neither widens a cutoff nor, once stored and expired, overrides one (fails with the authentication clock); - a whole key that is live when restore reads and expired when it merges gives way to the stored cutoff (the load is gated, not slept; fails if restore merges at the pre-read time); - the Redis merge matches `DenyEntry::merge` for whole-over-cutoff, cutoff-over-whole, two cutoffs under a shorter or longer `until`, and an expired whole key (fails if a whole-key write stops clearing the cutoff); - pruning clears an expired entry's cutoff, from a fixture seeded already expired in one atomic step; - a same-`until` scope widening is `Merged`, not `Unchanged` (fails if the change test compares `until` only); - a cutoff that isn't an integer, is out of range or has no deny fails the restore as `unreadable`; - a malformed cutoff leaves its deny restorable as the whole key, an orphan cutoff adds nothing, and a good cutoff still scopes its key, while the load still fails as `unreadable`; - a disconnect over a complete active deny whose stored cutoff is fractional or out of range fails with the claim unused and the index (with scores), exact and cutoff hashes unchanged (fails with the accept script's check removed); the script's bounds are pinned to chrono's range. - through the real Redis load and restore, a readable deny next to a bad record keeps its cutoff: a session issued at C is closed, one issued after C stays open, and admission stays fenced (fails if the partial payload drops scope). --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
c0932db19c |
fix(relay): persist NIP-FI revocations across restarts and bridge shadow to enforce (#9860)
## Summary Stack: this PR → #9917 NIP-FI revocations (deny entries from `POST /api/nip-fi/disconnect`) now survive relay restarts and lost pub/sub subscriptions, and an enforce relay can optionally carry over revocations accepted during the `shadow` period. ## Changes - **Durable deny store (Redis).** Per mode and issuer hash, a sorted set (score = `until` in ms, rounded up) plus a hash holding the exact signed `until`, merged by maximum. One Lua script runs all checks before any write: replay → expiry/capacity → write. Outcomes: claimed, replay (403), full (503, nothing written). Every write and prune also clears the target's field in the issuer's revoke-through cutoff hash, so a full revoke is never narrowed by a cutoff a newer relay version stored. A Redis error is an unknown outcome (503); the issuer sends a fresh command. - **Shared capacity.** `deny_set_capacity` is enforced in Redis, across pods. - **Fail-closed restore.** A pod starts closed to protected admission, refusing as authorization unavailable (HTTP 503 and the matching Nostr denial on root and audio AUTH; `shadow` records it as unavailable). Active deny entries still refuse with 403. Each key's verdict (allowed, denied, unavailable) comes from one read of the deny map, so a restore that starts mid-check is never reported as a revocation. A single consumer task restores by generation: wait for a confirmed subscription, load the stores, apply buffered messages, then reopen. A reconnect, a lag, or a received deny that does not fit the local capacity starts a new generation, so admission reopens only once the active union fits. A restore merges every stored entry first, then closes sessions only for targets it added or extended (also when it fails part-way; a capacity miss or a store error for one issuer or source doesn't end the pass, so every reachable target is still merged or closed and the first failure keeps admission closed), so restoring after a Redis blip doesn't walk every connection once per entry. While a restore keeps failing, the consumer still applies disconnects that arrive, so revoked sessions close while admission stays closed; the retry runs on a fixed one-second deadline that traffic can't push back. A stored deny record that doesn't parse fails the restore rather than being skipped; the issuer's other records are still applied and their sessions closed. Restore failures are counted in `buzz_nip_fi_deny_restore_failures_total{reason}`; a stored record that doesn't decode is counted as `reason="unreadable"`, apart from `store` (Redis unavailable). - **Bridge setting.** `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` (default false, enforce only) makes an enforce pod also subscribe to the shadow channel and restore the shadow store. - **NIP-FI spec.** Restart behaviour now allows shared storage that is restored before protected connections or HTTP requests are admitted. Disconnects document the unknown-outcome reply: when a relay can't tell whether its shared-storage write applied, it returns `503` `authorization unavailable` and closes no sessions, and the caller retries with a freshly signed command (new `jti`). Added to the step 7 pseudocode, the disconnect response table and the `authorization_unavailable` rejection row. - **Runbook.** New "Revocation during a deploy" section in `docs/operator-nip-fi-bindings.md`: coverage (restarts, not lost Redis data), non-evicting Redis, disconnect responses, capacity, boot behaviour when Redis is unreachable, recovering from an unreadable deny record (`HDEL`), and the shadow → enforce rollout steps. ## Tests - Restart restores denies from the shared store; unavailable store keeps admission closed; consumer reopens only for a live, restored subscription. - Store error returns 503 and the command retries; lost reply returns 503 and needs a fresh command. - Capacity enforced across pods; over-capacity restore stays closed; a capacity miss during the restore handoff or after a successful restore keeps or closes admission. - A restoring deny map refuses as unavailable (503 / bare close), not revoked, at each admission point: WebSocket upgrade, protected HTTP, root AUTH and audio, and when the restore starts during the check. - Restore closes only added or extended targets, still closes them when it fails part-way (a capacity miss, a failing source before a healthy one, and the first-visited issuer failing before a healthy one, and an unreadable record reported as `unreadable`, not `store`), and live delivery of an unchanged entry still closes sessions. A broadcast lag after a restore restores again. During repeated restore failures, delivered disconnects still close their sessions, admission stays closed, and steady traffic doesn't delay the next attempt (run on a paused Tokio clock). - The buzz-pubsub deny-store key and rounding unit tests now run in `just test-unit` and `run-tests.sh`. - Subscribe channels and restore sources follow mode and bridge; config rejects the bridge outside enforce. - Redis-backed (ignored, run in CI's NIP-FI Redis step; each case uses its own store namespace): script checks before writing and keeps exact `until`; expired entries free their slot and a shorter command never lowers a score (`ZADD GT`); bridge restores shadow-period denies on enforce pods; a record with an unreadable key or `until` fails the load while every readable active record after it still loads, and expired entries are still filtered; restore applies a good record past a bad one for the same issuer, closing its sessions and leaving others open, fails as `unreadable` with admission unavailable, and reopens on retry once the record is removed (fixture hashes expire after 60s); an accept with an equal or shorter `until`, and a prune, clear the target's stored cutoff. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: wpfleger <wpfleger@users.noreply.github.com> |
||
|
|
166245b4f9 |
chore(db): accept the activity cache tables before their migration (#9815)
## Summary **What it does.** It tells community deletion that two tables, `channel_heads` and `thread_heads`, may exist. It lists them in `PENDING_SCOPED_TABLES` and `APPROVAL_FORWARD_TABLES`. This release creates no table and changes no schema. With it deployed, deletion accepts both tables whether or not they exist yet. When they exist, it purges their rows and verifies them. It also still executes a deletion that was approved before they appeared. **Why.** #9756 adds these two tables as caches for the `/buzz/v1` activity list. Deletion's catalog check is an exact set. A relay without this change would see them as unknown tables after #9756's migration runs, and community deletion would fail for every community: during the rollout, and again after any rollback. `docs/database.md` ("Adding a tenant-owned `community_id` table", and the table in *What breaks the old relay*) asks for this precursor release. **Order of rollout.** 1. Merge and deploy this PR to every relay, deletion executor and operator CLI. 2. Then merge #9756, which creates the tables (migration 0105) and moves them to `EXPECTED_SCOPED_TABLES`. This PR's release becomes the rollback floor once that migration runs. **This must ship and deploy before #9756.** **What users will notice.** Nothing. **Out of scope.** The tables themselves and everything that uses them are in #9756. ## Testing - `cargo test -p buzz-db -p buzz-deletion` (unit tests, including the list invariants) passes. - Against a local Postgres: `pending_scoped_tables_are_optional_purged_and_verified` passes with both tables on the list. - `approval_before_an_expand_migration_completes` needs S3 and Redis and is outside the Postgres lane, so it runs only where that infrastructure exists. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Jude Edwards <judeedwards@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
e68cd09794 |
feat(search): keep an OpenSearch message index in sync through a Postgres outbox (#9838)
## Summary
This PR keeps a second copy of the message index in OpenSearch. Searches
still run on Postgres. Each searchable message writes a small "index me"
row to a new Postgres table, `search_outbox`, in the same transaction
that stores it. One relay drains that queue into OpenSearch. Writes
never wait on OpenSearch, and if it is down, rows wait in the queue.
```mermaid
sequenceDiagram
participant Client
participant Relay as Relay (admission tx)
participant PG as Postgres
participant Idx as Indexer (1 leader)
participant OS as OpenSearch
Client->>Relay: kind 9 "flamingo"
Relay->>PG: INSERT events + INSERT search_outbox (same tx)
loop every 5s, backing off up to 60s on failure
Idx->>PG: claim ≤500 rows of one community (SKIP LOCKED)
Idx->>PG: re-read those events (+ channel, thread, mentions)
Idx->>OS: one bulk request: upsert docs, delete missing ones
Idx->>PG: DELETE the claimed rows, COMMIT
end
```
- **Turn it on** with `BUZZ_OPENSEARCH_URL` plus
`BUZZ_OPENSEARCH_PREVIEW=true` (optional basic auth: set both or
neither). Without the opt-in, a relay with the URL refuses to start. The
relay refuses to start if migration `0106` has not run. Without the
setting, each insert pays one flag check.
- **Queue** (`migrations/0106`, `search_outbox.rs`): one row per stored
message of kind 9, 40002, 40008, 45001 or 45003. A rolled-back write
takes its row with it. The indexer re-reads each event, so duplicate
rows are harmless.
- **Indexer** (`indexer.rs`): one leader, chosen with a Postgres session
advisory lock. A batch holds its community's write transaction until the
bulk request ends, so deletion can't fence the community mid-batch. HTTP
400/413 skips that community for the pass. Any other failure ends the
pass and backs off. Batches have no byte cap yet, so a cluster with a 10
MiB request limit can reject a full batch; #9862 caps requests at 8 MiB.
- **Index** (`opensearch.rs`): alias `buzz-messages` →
`buzz-messages-v1`, strict mapping, message text indexed but not stored.
Writes require the alias, so they never create an index. Searches filter
on community first and fail rather than return partial hits.
- **Deletion:** community deletion fences and purges the community's
queued `search_outbox` rows with its other rows. It doesn't touch
documents already in the index.
- **Infra:** an opt-in `opensearch` service in docker-compose
(`--profile search`). The CI Postgres job starts OpenSearch 2.19.3. The
−1,895 lines move the Postgres search tests into `tests/search_suite/`,
which now runs against both backends.
### Worth knowing
- **A rejected batch blocks its community.** Rows are claimed oldest
first, so the same batch comes back every pass. Other communities still
drain, but each rejection counts as a failure, so passes slow to 60 s
apart.
- **Text isn't stored in the index,** so a new mapping version needs a
full backfill from Postgres. No backfill exists yet, so messages stored
before the setting aren't indexed.
- **Not for relays with real data yet.** Deletes, edits and account
scrubs don't reach the index until #9862, and nothing purges a deleted
community's documents. Searches never return them, since every hit is
re-read from Postgres, but their words stay in the index. So the relay
requires the `BUZZ_OPENSEARCH_PREVIEW` opt-in, which #9862 removes.
- **Coverage gaps:** each relay queues only what it stores, so set the
URL on every relay.
- **Delay:** up to ~5 s of polling plus a 30 s refresh before a message
is searchable.
### Testing
CI's Postgres job now runs the shared search suite and the outbox sync
tests against a real OpenSearch. For a local run, see
`docs/opensearch-search-deployment.md`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Salman Mohammed <smohammed@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
54e2d25f69 |
chore(deletion): accept the search outbox and backfill tables before they exist (#9871)
## Summary Community deletion checks the database's community-scoped tables against an exact list and fails closed when it finds a table it does not know. The OpenSearch indexing stack that starts at #9838 adds two such tables, `search_outbox` (migration 0106) and `search_backfill` (migration 0107). A relay from before that stack, running after those migrations, would refuse every community deletion with "community deletion catalog drift (missing=, unknown=search_backfill,search_outbox)". That happens in a mixed fleet during the rollout and after a rollback. This PR lists both tables in `PENDING_SCOPED_TABLES` and `APPROVAL_FORWARD_TABLES` in `crates/buzz-db/src/store/deletion.rs`, so a release without the tables already accepts them. Neither table has a foreign key, so purge order does not matter. Nothing else changes: the tables do not exist yet and nothing writes to them. This release must reach every relay, deletion executor and operator CLI before the migrations run. The stack's own copies of this change get dropped when it is rebased onto this. ### Related issue N/A. Prerequisite for #9838 and #9862. ### Testing The existing table-driven tests for pending tables and approval forwarding cover both new entries. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Salman Mohammed <smohammed@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
5884965a47 |
perf(relay): bound channel- and thread-window aux hops to a day before the oldest target (#9874)
## Summary
Both window aux closures, the channel window and the thread window, now
read their `#e` hops from one day before the window's oldest aux target.
That lets Postgres prune older `events` partitions instead of probing
the community's whole history.
### Channel window
`handle_channel_window_filter` runs two `#e` aux hops for a channel
window: hop 1 fetches the reactions, edits and deletions of the window
rows, and hop 2 fetches the deletions of those aux events. Neither hop
had a lower time bound, so each `#e` GIN probe ran against every
`events` partition in the community's history.
Both hops now read from `since = oldest retained window row's created_at
− 1 day` (`WINDOW_AUX_SINCE_MARGIN_SECS`), which lets Postgres prune the
older partitions. A hop-2 deletion postdates the aux event it deletes,
so one bound covers both hops. An empty window has no bound, and no hops
run for it.
**Why it's safe**
- Ingest rejects events more than ±15 min from the relay clock
(`MAX_TIMESTAMP_DRIFT_SECS`), so an aux event can predate its target by
at most about 30 min. The day of margin covers that, plus data that
reached the store some other way.
- In a sample of about 86.6k aux events across every partition, none was
dated more than 1 day before its target.
**Measured**
- Channel 029f8049: both lookups went from 927 to 230 ms.
- Channel a9cb3f0a: 256 to 46 ms.
- Prod `pg_stat_statements`: hop 2 averages 147 ms over 2.9M calls and
returns 0 rows on average, so most of that time is spent scanning
partitions it can now skip.
**Known risk:** a tighter bound can flip the planner to a worse plan on
busy channels. A 1-hour margin did this in testing. The 1-day margin is
the one that measured well.
### Thread window
`thread_window::query` → `buzz_db` `thread_window_aux` runs the same two
hops. `AuxQuery` gains an optional `since`, which `select_aux` adds as
`created_at >= since`. In a thread window, `rows` holds only replies,
but the root is always a hop-1 target, so the bound is `min(root
created_at, oldest reply) − 1 day`. `select_window` now reads the root's
`MIN(created_at)` in the query that already checked the root exists in
the channel (it used to be `EXISTS`), and returns it as
`ThreadWindow::root_created_at`. Both paths share `window_aux_since`.
**Measured** on the prod reader with `EXPLAIN (ANALYZE, BUFFERS)`, warm,
with the exact `select_aux` SQL: 50-reply windows (51 targets), and an
accessible set of 974 channels (a real user's). Times are execution +
planning ms; rows were identical with and without the bound in every
case:
| Thread | Hop | Unbounded | Bounded |
|---|---|---|---|
| 244d0894: 1570 replies, root Nov 16 | hop 1 | 352 (45.0k buf) | 108
(13.4k buf) |
| 0fdaa9bb: busy channel 638c53ca | hop 1 | 357 (45.0k buf) | 111 (12.5k
buf) |
| 346a47e6: busy channel 029f8049 | hop 1 / hop 2 | 100 / 53 | 45 / 14 |
| f7c2c2f9: root Sep 22, still active | hop 1 / hop 2 | 330 / 53 | 259 /
37 |
With only the thread's own channel accessible, the same cases went 216 →
15, 218 → 21, 76 → 31 (hop 2 35 → 5), and 214 → 151. None of the bounded
plans was worse: they use the Nov partition's `kind_created_at` btree
plus its tags GIN. An old root gains less, because the bound still has
to reach back to the root's month.
Prod `pg_stat_statements` (reader, since Nov 2): the thread aux shape
ran 1.03M calls, averaging 50 ms, 8.5k buffers and 3.9 rows per call,
14.4 h in total. Cost grows by about 4.5 ms and 800 buffers per target:
11 targets averaged 52 ms over 268k calls, and 51 targets averaged 250
ms over 43k calls.
Caveat: I measured with literals, which gives custom plans. If sqlx's
prepared statements switch to a generic plan, partitions are still
pruned, but at execution time rather than at planning time.
### Related issue
N/A. This comes from the structural first-paint investigation of prod
head-read latency. No existing issue or PR found.
### Testing
- New thread test
`thread_window_aux_hops_read_from_a_day_before_the_root`: its only reply
is 2 days newer than the root, so a bound anchored on the replies alone
would fail it. A reaction and a delete-of-reaction dated inside the
bound come back, and ones dated more than a day before the root do not.
Two mutation checks fail as expected: dropping the SQL clause fails on
"hop 1 past the bound", and leaving the root out of the bound fails on
"hop 1 inside the bound".
- New channel test
`channel_window_aux_hops_read_from_a_day_before_the_oldest_row`: a
reaction and a delete-of-reaction dated inside the bound come back, and
ones dated more than a day before the oldest row do not. As a mutation
check, removing `aux_query.since` makes it fail on "hop 1 past the
bound".
- `scripts/postgres-test-run.sh`: `buzz-relay` `api::bridge::` 135/135
pass and `buzz-db` `thread_window|thread::` 28/28 pass. The
workflow-webhook test needs `REDIS_URL` set.
- The Security check fails on a new advisory, RUSTSEC-2026-0592 (`url`
2.5.8, in `Cargo.lock`). This PR doesn't touch dependencies, and main's
run of that workflow at
|
||
|
|
2e3bebe9b6 |
feat(mobile): enroll Android devices for push (#9811)
## Summary Ticket 7 of the [Android push plan](https://github.com/block/buzz/blob/main/PLANS/ANDROID_PUSH.md). Android phones can now enroll with the push gateway and publish a relay lease, through the same shared push layer iOS uses. The wake handling side is ticket 6, [#9804 Android push wake handling](https://github.com/block/buzz/pull/9804). - The phone gets an FCM token, then generates a sign-only P-256 Keystore key whose attestation challenge is the SHA-256 of the enrollment transcript. The chain goes to the gateway at enrollment. Every later installation call (delegate, rotate endpoint, revoke delegation, revoke installation) is signed with that key over the transcript bytes the gateway builds. - A rotated FCM token rotates the endpoint. Signing out revokes the delegation and the installation. The first enrollment waits a short random time. - Android 13+ asks for the notification permission at the same point iOS does. Declining keeps the app working. - A phone that cannot attest (no hardware attestation, unlocked bootloader, unlisted boot key) keeps working, and Settings says push is unavailable on this phone. - The relay lease keeps the fixed `transport` value iOS sends. - Firebase config is the same build-time setting [#9804 Android push wake handling](https://github.com/block/buzz/pull/9804) adds: four `BUZZ_FIREBASE_*` environment variables become the string resources Firebase reads. Nothing is committed, and builds without them still work (push reports unavailable). The Gradle hunks (permission, config block, `firebase-messaging` dependency) are copied from that PR verbatim so the two merge cleanly, including its `lifecycle-process` line, which this PR does not use. - The token and permission calls use their own `buzz/push_registration` channel, because Android's notification-open handler from that PR already owns `buzz/push` and a channel has one native handler. - The gateway gets an `enroll_android` transcript vector so Dart and Rust agree on the exact bytes. Enrollment state is journaled before each network attempt, so a lost response resumes with byte-identical requests instead of leaving an orphaned installation. ### Related issue None found. Builds on [#9560 enroll Android installations](https://github.com/block/buzz/pull/9560) and [#9562 verify Key Attestation](https://github.com/block/buzz/pull/9562). ### Validation Journey tests cover first enrollment, a second relay, reuse and renewal, lost responses, token rotation, an installation the gateway dropped, a lost Keystore key, a phone that cannot attest, and sign-out revocation, against a fake gateway that keeps the real gateway's semantics. Transcripts replay the shared vectors byte for byte. A settings journey checks the Notifications row and the unavailable row on Android, and a resume table checks the FCM token refresh: it runs while the relay reconnects, but not when push is off or the relay doesn't offer push. On a physical Pixel 9a (debug build, a local test gateway on a local Postgres, reached over `adb reverse`), the real Keystore key and hardware attestation chain enrolled and delegated, and the gateway accepted the attestation. The same session then ran: a signed delivery authorized against the delegation, endpoint rotation and re-delegation at the next epoch, rotating back, delegation revocation, installation revocation, and re-enrolling the same FCM token afterwards. The notification prompt appears when registration starts, before the token is fetched: <img src="https://github.com/user-attachments/assets/2aed92fe-20c1-4658-b990-51c3f3c96120" width="270" alt="Android notification permission prompt"> Not validated on the device: the FCM wake itself (the local gateway has no credentials to call FCM, so the delivery was authorized and then failed at the FCM hop), lease publication to a relay, and the in-app unavailable row, which only the widget tests exercise. A relay-backed run needs a signed-in test community on the phone. ### Settings while turning off Turning notifications off sends a relay tombstone. Until the relay accepts it, the row now says so, on both platforms. An Android build without a gateway also keeps a saved opt-in visible so it can still be turned off; once off, the row goes away. These are rendered from the Settings journey test. | | Before | After | |---|---|---| | Android build without a gateway, saved opt-in | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--01-before-config-less.png" width="270" alt="Before: no Notifications row"> | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--02-after-config-less.png" width="270" alt="After: Notifications row with the switch on"> | | After turning off, relay has not accepted yet | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--03-before-turning-off.png" width="270" alt="Before: plain off switch"> | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--04-after-turning-off.png" width="270" alt="After: Turning off. Notifications may continue until this finishes."> | ### Regressions - iOS enrollment is unchanged: the shared bridge only branches to the Dart authority on Android. iOS gains the pending opt-out subtitle, and its opt-out now also tombstones after a gateway change using the saved lease id. - The Android app gains the `firebase-messaging` dependency and a `POST_NOTIFICATIONS` permission. Backups exclude the push preferences file. ### Known limits - An FCM token rotation while the app is running is picked up on the next resume or launch, because the wake service owns the single messaging service. It could call into the registration plugin once both Android push PRs merge. - After an endpoint rotation, only the active community's lease is republished. Other enabled communities' grants are void until each is opened, the same way their leases lapse at grant expiry today. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
80131055dc |
Revert "perf(db): stop per-id planning of wide #e reads (#9591)" (#9848)
Reverts #9591 (`perf(db): stop per-id planning of wide #e reads`). Hiding the `#e` id arrays from the planner made reads in large communities much slower in prod. This is a straight revert. ## Evidence - **8 → 9 row cliff on the channel head read with `include_aux`:** 125ms at 8 rows, 1.4s at 9 rows, about 2.3s at 20 rows. - **Replica `EXPLAIN ANALYZE`, 20-id aux query:** 130ms with the ids visible to the planner, 2240ms with them hidden. The hidden plan reads and discards about 625k rows in `events_p2026_07_08_legacy`. - **200-id thread page (1,593-reply thread):** | ids | plan | exec | |---|---|---| | visible (this PR) | 78ms | 1,387ms | | hidden (#9591) | 10ms | 18,146ms | #9591 saves planning time but makes execution about 13x slower. - **Prod:** #9591 reached bb-block prod with `main-20261120032502-8d4b301` (2026-11-20 14:48Z). ## Notes - #9674 used the same trick for thread-window aux reads and had the same risk. It's now closed. - Any future change like this should be checked with `EXPLAIN ANALYZE` on the replica first. A test that runs EXPLAIN against a large community is a follow-up, not part of this PR. ## Testing - `cargo test -p buzz-db --lib e_tag` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Bradley Axen <baxen@squareup.com> Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
58695fe376 |
acceptance: read the probe key from a file; dial a connect address (#9773)
## Summary Follows https://github.com/block/buzz/pull/9771 (merged), which added the acceptance CronJob. Some NIP-FI issuers bind each key to one identity. A deployment that mints a new identity for each run then needs a new key for each run, written next to the assertion before the probe starts. The probe could only take its key from an argument or the environment, which a Kubernetes init container can't set. - **Probe:** `--private-key-file` (`BUZZ_PRIVATE_KEY_FILE`) reads the key (hex or nsec) from a file. It conflicts with `--private-key`. - **Shared read:** the key file and the assertion file use one bounded reader, `acceptance::read_secret_file`. It needs a regular, non-empty file under a size cap. - **Report:** the JSON report now includes `pubkey`, the hex key the probe ran as. An operator can match a run to the identity that was minted for it. - **Chart:** `acceptance.privateKeyFile` is passed as `--private-key-file`, not as an env var, so a probe that predates the flag fails instead of running with a new key. Exactly one of it and `acceptance.privateKeySecret.name` must be set; rendering fails with neither or both. - **A new key per run needs an agent assertion** (`nip-fi-agent+jwt` whose `nostr_owner_pubkey` is a relay member). A members-only relay refuses a new person key, and an open relay joins it to every auto-join channel. The README and `values.yaml` say so. - **Connect address:** `--connect-addr` (`BUZZ_ACCEPTANCE_CONNECT_ADDR`) dials a plaintext `host:port` for every WebSocket connection and for the NIP-11 fetch, for a probe that can't reach the relay's public host. The relay URL still sets the `Host` header, the NIP-42 relay tag and the NIP-11 `Host`, so the relay serves the same community. On that path, NIP-11 uses no proxy, follows no redirect and requires a 2xx answer. The chart passes `acceptance.connectAddr` as `--connect-addr`, not as an env var, so a probe that predates the flag fails the run instead of checking the public URL. The default is empty. `NostrWsConnection::connect_to_addr` now takes upgrade headers, so the NIP-FI assertion goes on this path too; loadgen passes none. (Folded in from #9830.) - **Chart version 0.1.13** with an `artifacthub.io/changes` entry. It publishes the acceptance CronJob from #9771, the key file and the connect address. - **Follow-up test from the #9767 review:** the fake relay gets an `accept_mismatched` setting, and `access_control_fails_when_the_relay_accepts_another_keys_write` expects `access_control` to fail at `pubkey_mismatch_rejected`. A `pubkey_mismatch_rejected` stage that always returns Ok now fails a test. ## What got simpler The assertion reader's inline bounded read is now the shared `read_secret_file`, so both secret files follow one rule instead of two copies of it. The probe's four connection call sites now share one `open` helper, and `connect_to_addr` reuses the same `upgrade_request` path as `connect_with_headers`. ## Testing - `e2e_acceptance`: `the_binary_authenticates_with_the_key_from_its_key_file` passes against a live relay with the key path in `BUZZ_PRIVATE_KEY_FILE` (the same clap argument as `--private-key-file`). It checks that the report's `pubkey` is the file's key, so a probe that ignored the file and made a new key fails. - `e2e_acceptance`: `the_binary_exits_2_when_it_cannot_run` covers a bad key, a bad key file, a missing key file, and both key flags at once. Each exits 2 with no report and no metrics. - Existing unit tests cover the shared reader through the assertion file (missing, empty, oversized, directory, FIFO). - `connect_addr_dials_the_address_and_keeps_the_relay_url`: the probe runs at an unresolvable `wss://relay.invalid` with the fake relay's address. Every upgrade has `Host: relay.invalid` and the assertion's bearer header, and every AUTH relay tag is `wss://relay.invalid`. - `nip11_goes_to_the_connect_addr_with_the_relay_host` (`GET /relay?route=probe`, `Host: relay.invalid:8443`) and `nip11_at_the_connect_addr_does_not_follow_a_redirect` (a 301 fails `nip11` with no version). - `caller_user_agent_replaces_default` now covers `connect_to_addr` too. - `tests/acceptance_test.yaml`: `acceptance.connectAddr` renders `--connect-addr <addr>` in the args, and the default args do not have it. The key file renders as `--private-key-file <path>` in the args, with neither `BUZZ_PRIVATE_KEY_FILE` nor `BUZZ_PRIVATE_KEY`, a Secret plus a file fails, and no key source fails. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed --------- 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> |
||
|
|
af8287d961 |
Fail CI on new triggers, functions, rules and foreign keys (#9812)
## Summary Migrations up to `0104` dropped every trigger, function and foreign key. `docs/database.md` Rules 1 and 2 forbid adding them back, but nothing enforced that. This PR adds the guard. - **Migration lint.** `migrations_after_retirement_add_no_triggers_functions_or_foreign_keys` scans each migration numbered after `0104`. It fails on `CREATE [OR REPLACE] FUNCTION | PROCEDURE | TRIGGER | RULE`, `CREATE CONSTRAINT TRIGGER`, `CREATE EVENT TRIGGER`, `REFERENCES` and `FOREIGN KEY`, outside `--` comments. The error names the file and line, for example `migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION`. Nested `/* */` comments are skipped. Quoted identifiers and string values are data, except a string passed to `EXECUTE` or `format(`. Each dollar-quoted body is scanned as SQL up to its closing delimiter, so DDL run through `EXECUTE` in a `DO` block is caught, and an apostrophe inside `$$...$$` cannot hide the rest of the file. It runs in the infra-free `buzz-db --lib` unit lane. - **Schema file check.** `desired_state_schema_layout_is_complete_and_schemabot_shaped` allows `schema/` files only under `tables/public/`, `types/`, `partitions/` and `seeds/`, and runs the same scan on every file. A `functions/` or `triggers/` file, or an inline `REFERENCES` in a table file, fails it. - **Catalog check.** `admin_schema_parity_between_desired_state_and_migrations` now asserts that both bootstrap paths (pgschema + reconcile, and all migrations) have zero non-internal triggers, event triggers, `public` functions and procedures, rules and foreign keys. Extension members (pgcrypto) are excluded. No allowlist is needed: main with all 104 migrations applied has none of these objects. Main now has `0105`, which passes the lint. Open PRs that add a migration only need to renumber to `0106` or later. The two open ones (https://github.com/block/buzz/pull/9621 and https://github.com/block/buzz/pull/9690) add no forbidden object. ### What got simpler - The parity test's per-table trigger comparisons (`events`, `event_mentions`, and the five tables `0096` unguarded) and its separate foreign-key check are replaced by one zero-object assertion. - The scoped-key lint no longer parses foreign keys. None may exist, so checking that they lead with `community_id` is dead logic. - `schema/schema.sql` drops its empty `-- functions` and `-- triggers` sections. Its header and `docs/database.md` stop describing `functions/` and `triggers/` directories that no longer exist, and the doc's "remaining triggers stay as a backstop" text now says they are gone. ### Checklist (`docs/database.md`) - [x] Phase: none. Test and docs change only. No migration and no runtime code. - [x] No trigger, function, procedure, rule or foreign key is added. - [x] No migration mutates rows. - [x] Rule 4 locations: no schema change. `schema/schema.sql` changes only comments. ### Related issue None found. ### Testing Run on a Linux workstation with PostgreSQL 17 at `b7254f90`, before the review fixes. CI passed with the first review fixes at `0fed6b1b`. `9749e618` adds dollar-quote, nested `EXECUTE $tag$` and `$1` cases to `schema_object_lint_reports_each_construct_with_its_line`, and CI checks it. - `cargo fmt --check` and `cargo clippy -p buzz-db --all-targets -D warnings`: pass. - `cargo test -p buzz-db --lib` and `cargo nextest run -p buzz-db --lib`: 223 passed. - `scripts/postgres-test-run.sh` for `admin_schema_parity_between_desired_state_and_migrations`, `migrated_catalog_retires_universal_fences_but_keeps_deletion_guards` and `pgschema_reapply_keeps_runtime_partitions`: 3 passed. - Proof the lint can fail: a temporary `migrations/0105_probe.sql` with a function and a `REFERENCES` column fails the lint with `migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION` and `migrations/0105_probe.sql:3: REFERENCES`. - Proof the catalog check can fail: a temporary `0105` that creates `probe()` fails the parity test with `the migrations leave a trigger, function, rule or foreign key`, `left: ["function probe()"]`. - The catalog on main at `9c0bcd62`, with all 104 migrations applied through psql, has no triggers, functions, foreign keys, rules or event triggers. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
792a9ce563 |
feat(relay): list and revoke invite links (#9680)
Stack: this PR → #9690 ## What this does Adds listing and revocation for v2 invite links, and makes every reader of an invite's expiry accept a missing value. - **`GET /api/invites?limit=&before=`** lists the community's v2 invites, newest first: id, creator, created/expiry/revoked times, uses and a computed `status` (`active`, `revoked`, `expired`, `exhausted`). Owner/admin only. The NIP-98 signature covers the full URL including the query. `limit` defaults to 50 (max 200). `next_before` is an opaque cursor holding the last row's `created_at` (microseconds) and id, so paging doesn't depend on that row still existing. - **`POST /api/invites/revoke`** takes exactly one of `{"id": "<uuid>"}` or `{"code": "v2...."}`. The code is hashed and looked up only inside the request's community. v1 and malformed codes get `400 invite_not_revocable`; an invite not in the community gets 404. Revoking twice returns the first `revoked_at`. Members who already joined stay. - **Authorization.** Mint, list and revoke share one HTTP admission helper (tenant bind → NIP-98 via NIP-FI → replay → membership/ban → NIP-OA owner link → role gate). Revoke's final decision is made in the write transaction, in the same order as mint: admission lock → actor's role row `FOR SHARE` → restriction check → invite row `FOR UPDATE`. Owners and admins can revoke any invite; any other member only one they created. A removed or restricted actor is refused. Mint now uses the same role-lock helper. - **Mint response** now includes `invite_id`. - **Nullable expiry readers.** Claim, list, the mint response and operator mint treat a missing `expires_at` as "never expires". The column is still `NOT NULL` here. - **Secrets.** No list/revoke response or access-log line contains a code or its hash; request errors are fixed strings that never echo input. Revoke logs only `invite_id`. A revoke the database refuses is logged as denied with its reason. ## Deploy order A follow-up PR adds links that never expire (`expires_at` nullable). **It depends on this PR being deployed everywhere first**, so every serving relay can read a missing expiry before one is written. ## Tests - DB (`relay_invite/manage_postgres_tests.rs`): revoke by code targets exactly one of two near-identical invites, idempotent revoke, community scoping, creator demoted to member can revoke theirs, a member who didn't create it is refused, a removed creator is refused, a restricted admin is refused, a demotion holding the role row or a restriction holding the admission lock makes revoke wait and then refuse with the row unchanged, a paused claim and a revoke serialize with the member kept, revoke is refused while the community is quiescing, paging survives deleting the cursor row, and a row with no expiry is listed, claimed, kept by the reaper and revocable (on a scratch database with `NOT NULL` dropped). - Relay (`invites/postgres_tests/manage_tests.rs`): list/revoke by id and code end to end, no code or hash in responses, member/non-member refusals, bad selectors, other-community lookups, query-string signature binding, malformed requests not echoing a code in responses or access logs, refused revokes logged as denied, and replayed list/revoke requests refused. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
81b4054e5d |
fix(push-gateway): answer 429, not 404, when the delivery quota is exhausted (#9803)
When an endpoint's delivery quota is exhausted, both authority stores
returned `AuthorityError::Rejected`, so `/v1/deliveries` answered `404
invalid_grant`. NIP-PL already specifies `429 {"error":"rate_limited"}`
for this case.
The 404 matters because the relay treats a 404 on a retry attempt as a
terminal replay and completes the wake, so a throttled wake was silently
dropped. On a first attempt it failed the wake. A 429 takes the relay's
existing retry-with-backoff path instead.
### Change
- Memory and Postgres stores return `RateLimited` on quota exhaustion.
`http.rs` already maps that to `429 rate_limited`.
- The rate-limited attempt still charges no quota and consumes no
auth-event or request-id fence, so the relay's retry with the same
request id is admitted once the window reopens.
- No doc change: NIP-PL and the deployment doc already describe 429.
### Validation
- Memory store: an exhausted quota returns `RateLimited`, leaves replay
rows and the quota counter unchanged, and the same auth event and
request id are admitted after the window.
- Postgres (ignored test, run locally against a temporary database): the
quota-ceiling race test now also asserts the loser is `RateLimited`.
- HTTP: the eleventh delivery under a quota of ten answers `429
{"error":"rate_limited"}` and reaches no transport.
- With the two store lines reverted, all three tests fail.
### Regressions
None expected. Only the quota-exhaustion result changes; grant,
authority and replay failures still collapse to `404 invalid_grant`.
---------
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
|
||
|
|
e21606bf96 |
feat(cli): leave archived identities out of users get --name (#9752)
`buzz users get --name` now leaves out identities on the relay's NIP-IA archive list. `--include-archived` brings them back, each marked `"archived": true`. `--pubkey` lookups always return the profile and mark it when archived. - The list is read by `fetch_archived_snapshot`, the same reader as `buzz agents archived`, so only a kind:13535 event signed by the relay's NIP-11 `self` key (with the NIP-70 tag) counts. A profile that sets its own `archived: true` is not marked unless the signed list names it. - Fail open: if the list can't be read, can't be verified, or takes longer than 5s, results come back unfiltered with a JSON warning on stderr. The search never fails because of it. - Name searches and `--pubkey` lookups read the profiles and the archive list in parallel. A profile error returns at once as the usual single JSON error, without waiting for the archive read or printing its warning. `--owner` with no matching agents returns `[]` straight away. - Documented in the CLI README. Out of scope: the relay and `send`/`dm`. Related: [buzz-app#4021](https://github.com/block/buzz-app/pull/4021) --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> |
||
|
|
eae69483fd |
fix(push-gateway): retry, don't drop, a delivery replayed while its first attempt is in flight (#9802)
The relay gives up on a push gateway delivery call after 2 seconds and
retries the same `request_id` with a fresh NIP-98 event. A gateway send
can take much longer than that: an FCM token mint has a 15 second
deadline, and the APNs and FCM sends each have a 15 second timeout. A
retry that arrived while the first attempt was still sending hit the
request replay fence and got `404 invalid_grant`. The relay reads a 404
on a retry as "the earlier attempt already finished" and completes the
wake. If the first attempt then failed retryably, nothing ever sent the
wake, and the notification was silently lost.
This change makes the gateway tell an in-flight request apart from a
finished one:
- Admission records the request id as in flight. A terminal outcome
marks it finished, and a retryable outcome releases it, as before.
- A replay of an in-flight id now gets `503
{"status":"retry","retry_after_seconds":5}`. Nothing is sent and no
quota is charged, so the relay's existing 503 path retries with backoff.
- A replay of a finished id still gets 404, so the relay's existing
handling of a finished attempt is unchanged.
Postgres gets a `finished` column on
`push_gateway_delivery_request_replays` (gateway migration 0009,
mirrored in relay migration 0105). It defaults to `true`, and the
gateway writes `false` explicitly on admission. Rows written before this
migration, or by an older gateway during a rollout or rollback,
therefore keep today's behavior. The constant default adds the column
without rewriting the table.
### Validation
-
[`replay_while_first_attempt_is_in_flight_is_retried_not_dropped`](
|
||
|
|
9f49216f8b |
feat(test-client): add buzz-acceptance relay probe (#9767)
## Summary
Adds `buzz-acceptance`, a third binary in `buzz-test-client` (next to
`buzz-loadgen`). One run checks the relay's core jobs once against one
relay and exits. It is meant to run on a schedule (for example a
Kubernetes CronJob) or as a deployment step (for example an Argo
Rollouts `job` analysis against the canary Service).
Checks, in order:
| Check | Stages |
|---|---|
| `relay_info` | `nip11` (the response must be a NIP-11 document) |
| `connect_auth` | `ws_connect`, `nip42_auth` |
| `channel_create` | `create` (a private, per-run channel with a 1 h
TTL) |
| `publish` | `ok` |
| `fanout` | `connect_second`, `subscribe`, `publish`, `receive` |
| `history` | `req_eose` (the published event is in a fresh REQ, intact)
|
| `access_control` | `unauthenticated_rejected`,
`pubkey_mismatch_rejected` |
| `cleanup` | `connect`, `delete_channel` (on a fresh connection) |
`access_control` passes only on the relay's own denial reasons:
`auth-required:` for a write on a socket that sent the NIP-FI assertion
but skipped NIP-42 AUTH, and `invalid: event pubkey does not match
authenticated identity` for a write signed by another key. A closed
socket or any other reason fails the stage.
`fanout` reads the listener while the publish waits for its OK, so
`receive` measures delivery (publish → arrival on the second socket),
not the publisher's acknowledgement.
`fanout` and `history` verify the event they get back (`Event::verify`:
id and signature against its content). An event the relay corrupted
under its original id fails the stage.
A channel is never stranded on purpose. If the create times out or the
socket drops, the probe keeps the channel id and `cleanup` deletes it
over a fresh connection. A failed cleanup names the channel. The TTL
archives any channel a killed run leaves behind.
Output:
- A JSON report on stdout: each check's result, the stage that failed,
and each completed stage's duration.
- Optional DogStatsD metrics (`--statsd-addr`): `<prefix>.runs`,
`<prefix>.run.seconds`, `<prefix>.check.runs{check,result,stage}`,
`<prefix>.check.seconds{check,result}`,
`<prefix>.stage.seconds{check,stage}`. Every series also carries
`relay_version` (from NIP-11) and any `--tag k:v`.
- Exit code 0 when every check passed, 1 when a check failed, 2 when the
probe could not run or send its metrics.
A check whose prerequisite failed is reported as `skipped`, so each
failure is counted once, at its cause, and every run reports the same
set of checks.
### NIP-FI
On a relay that enforces NIP-FI, pass `--assertion-file` (a regular
file, at most 16 KiB; a FIFO or larger file fails the connection at
once). The probe reads the file before every connection and sends it as
`Nostr-Federated-Identity: Bearer …`. Another process (for example a
sidecar) keeps it fresh. How the assertion is minted is deployment
configuration and stays out of this repo.
## What got simpler
Nothing got simpler. This adds one binary. It reuses `buzz-ws-client`
and the crate's existing dependencies, and adds no new crate and no new
dependency (`clap` gains its `env` feature).
## Testing
- Unit tests drive the probe against a scripted relay: a publisher OK
that arrives 600 ms after delivery (`receive` stays under 300 ms), a
refusal with the wrong reason and a closed socket (both fail
`access_control`), an unanswered create and a socket lost after create
(both still delete that exact channel), and a failed cleanup (the error
names the channel). Also: metric lines and tags, one datagram per line,
stage timeout, assertion file limits, and an unreachable relay.
- `tests/e2e_acceptance.rs` runs in CI's Relay E2E lane against a live
relay. It runs the shared runner and the binary itself: exit 0 with JSON
and datagrams on a pass, exit 1 when a check fails, exit 2 when the
probe cannot run.
## Follow-ups (not in this PR)
- Image and CronJob / Rollouts wiring.
- Before the probe can gate a canary: a dial override that keeps the
canonical Host and signed relay URL (like `buzz-loadgen`'s
`connect_addr`).
- Before it can gate a promotion: a build identifier from the relay.
`relay_version` is the Cargo package version, which several image builds
can share.
- Confirm the delete took effect: read the channel back after
`delete_channel` returns `OK true`. This needs a stable relay read
contract for deleted channels. Until then the 1 h TTL bounds any channel
a silent delete failure leaves behind. The scheduled deployment can also
sweep stale probe channels at start.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
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>
|
||
|
|
e95d7a9509 |
feat(relay): add pinned messages (nip-pm) (#9729)
## Summary Implements NIP-PM on the relay. A member signs one command to pin or unpin a message, and the relay publishes the channel's pins as one relay-signed list. The NIP is `docs/nips/NIP-PM.md`, added in #9712. - **Kinds.** `40010` pin and `40011` unpin commands (one `h`, one `e`, empty content) and the relay-signed `30623` pin list, one addressable event per channel, newest pin first. The list carries the channel in `d` and in `h`. - **Ordering.** Every writer of a channel's list takes that list's replacement lock, so pins, unpins and deletes of pinned messages apply one at a time. A command, the new list and the notice are stored in one transaction. - **Idempotency.** A command sent again answers `duplicate:` and is not applied again. Pinning a pinned message or unpinning an unpinned one is accepted and changes nothing. - **Validation.** The author must be able to post in the channel, and the channel must not be archived. A pin target must be a live message of that channel. A channel holds at most 250 pins. - **Deletes.** A delete by the author, the owner of the agent that wrote the message, a channel admin or a relay admin removes the message from the list in the deleting transaction and publishes the new list. A delete removes its messages first and then takes the list locks in channel order, rewriting each list once. Each list write records its timestamp, and a delete reads that first: a delete of a message that is not pinned locks only its own month of `events`, plus the list month when the channel has a list (#9743). The pin list itself cannot be deleted. - **Notice.** A pin that changes the list posts a `message_pinned` system message naming the member, the message and the command. - **Reads.** The list is readable by those who can read the channel. Clients read it with `#h`, which names the channel under NIP-CL, and each new list is delivered to `#h` subscribers. - **Configuration.** None. A relay running this build accepts the commands; it does not advertise pins in NIP-11. - **Threads.** A pin or unpin command cannot be the parent of a reply or the target of an edit or a vote. - **Account erasure.** Content cleanup removes a member's pin and unpin commands. One under an hour old keeps its ID, timestamp, kind and channel so that a resend stays a duplicate. The leader's periodic maintenance tick removes those records once the command is an hour old. `docs/operator-user-account-retention.md` describes this. ### Related issue N/A. #8809 is an earlier draft of message pins with a different event model. ### Testing - Postgres-backed store tests for the list writes: ordering, concurrent pins, resends, the limit, deletes, the lock order of a delete of several messages, the partitions a delete locks, the refusal to delete the list, erasure records and their expiry across communities. - Postgres-backed handler tests through ingest and REQ: the pin and unpin journey with notices and live delivery, who can read the list (private channel, DM and an unlisted channel read by a non-member), every refusal, a reply to a command, and deletes that rewrite the list. - `e2e_channel_pins` runs over WebSocket against a relay and is added to the relay integration job. - Run against a local relay started with no pins configuration: the end-to-end test. On an earlier revision, the periodic tick removed expired erasure records from an archived channel while leaving younger records, live commands and other kinds. - `cargo fmt --check`, clippy with warnings denied on the touched crates, and the file-size check. - `just test-unit`, which includes the buzz-db source-policy tests. --------- Signed-off-by: Kalvin Chau <kalvin@block.xyz> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
5268caa866 |
feat(push-gateway): mint FCM tokens through AWS workload identity federation (#9692)
## Summary Block's GCP projects forbid service account keys, so the push gateway can now get its FCM access token by federating its AWS identity (Google workload identity federation), with no key file. - `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` is renamed `BUZZ_PUSH_FCM_CREDENTIALS_PATH` (no deployment sets it yet). The file is dispatched on its JSON `type`: `service_account` keeps today's JWT flow; `external_account` is Google's standard AWS credential configuration, the file Block's `identity-federation-aws` Terraform module generates. - Only the minting step changed. `TokenSource` caching, refresh, backoff and the Rejected/Unavailable split are as they were. - A federated mint: AWS credentials (EKS Pod Identity, IRSA or static env keys; no EC2 metadata), a SigV4-signed STS `GetCallerIdentity` subject token, Google STS, then `generateAccessToken` for the FCM scope. One 15 s deadline covers the whole chain. - Faults: network errors, 5xx and 429 on any hop are Unavailable; other 4xx are Rejected. - Startup checks the file's shape and the AWS environment but calls neither AWS nor Google, so an outage can't stop the gateway from serving iOS. The first mint's result is logged once. - Helm: `android.fcmServiceAccount` is renamed `android.fcmCredentials`, mounted as `credentials.json`. ## Validation - New tests drive `TokenSource` against fake AWS, Google STS and impersonation servers: the full chain, each hop's failure classification, a failed refresh keeping a valid cached token, the overall deadline, and config rejection cases. - SigV4 known-answer tests use AWS's documented example credentials, checked against an independent implementation. Checked live against the dev Firebase project from a local AWS identity: the federated mint succeeds and FCM accepts the resulting token. Not yet run from a gateway pod. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
47c9a672d7 |
perf(push-gateway): evict the oldest signed-call window without scanning (#9799)
The push gateway's signed-call limiter keeps one counter per attested key, capped at 100,000 keys. Once the map was full, every call from a key not already in it scanned the whole map (once to drop expired windows, again to find the oldest), all while holding the limiter's lock. Under heavy load from many new keys, that serialized each signed call behind a 100,000-entry scan. The limiter now keeps a queue of window starts, oldest first, and evicts from its front. A key whose window restarts leaves a stale entry behind, which eviction skips; the queue is compacted once stale entries make up half of it, so a call stays O(1) amortized. Rate-limit behavior is unchanged, except that a full map now drops one oldest window per new key instead of every expired window at once. The map and the queue share one copy of each key; the queue can reach about twice the map's entries before compaction, so memory stays bounded. Follow-up from #9562. ### Validation | 1,000 new keys on a full map (release build) | Time | | --- | --- | | Before | 277 ms (about 0.28 ms per call, under the lock) | | After | 0.11 ms | - [`a_full_map_drops_the_key_with_the_oldest_window`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs) checks that eviction picks the oldest window. - [`eviction_skips_a_restarted_window`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs) checks that eviction skips a stale entry and keeps a key whose window just restarted. - [`restarted_windows_do_not_grow_the_queue`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs) checks that compaction bounds the queue when one key keeps restarting its window. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
786726907c |
test(relay): cover member-cache invalidation routes and refill orders (#9748)
## Summary Add 54 cases that verify a relay cache refill cannot restore stale channel membership after invalidation. The cases cover stale grants and denials, reader and community isolation, and three orders in which reads can finish. The publish-wrapper cases exercise the local cache drop. The receiving handlers are tested separately. Both unit-test runners select the new cases. ### Related issue Test coverage for #9735 and #9742. ### Testing The read-cache lane passed all 26 tests on the reviewed tree. Both runners selected all three new tests. The draft will remain open while repository CI and human confirmation are pending. For manual verification, run `cargo test -p buzz-relay --lib state::tests::member_channel_invalidation_tests:: -- --nocapture` and expect three passes. Generated with Codex Signed-off-by: Brad Seiler <seiler@squareup.com> |
||
|
|
8d4b30176b | feat(cli): add many channel members per kind:9000 event (#9738) | ||
|
|
7e94503fe9 |
Stop using the unused delivery_log and subscriptions tables (#9746)
## Summary `delivery_log` and `subscriptions` came with the initial schema for a delivery feature that was never built. No code has ever written to them. This PR removes every reader, writer, partition-manager entry and deletion selection, so a follow-up contract migration can drop both tables (`docs/database.md` Rule 5: drop only after the release that stops using a table is fully deployed). - **Partition manager:** manages `events` only. It no longer creates or audits `delivery_log` partitions. - **User deletion:** the content, account and profile handlers no longer select, delete or recheck rows in either table. - **Community deletion:** both tables move from `EXPECTED_SCOPED_TABLES`/`PURGE_SCOPED_TABLES` to a new `RETIRING_SCOPED_TABLES` list. The catalog accepts each one present or absent. The purge deletes its rows only while it exists. `validate_approved_schema` accepts a frozen retiring table that has since been dropped, and no other missing table. Without this, every community deletion would fail its exact catalog check once the tables are gone. - **Docs:** a short "Retiring a tenant-owned table" section in `docs/database.md`, plus partition-monitoring and cleanup docs. The tables, their schema files, `.pgschemaignore` entries and the partition primary-key lint exception stay until the drop migration. ### Rollout 1. Deploy this release to every relay, deletion executor and operator CLI. Older binaries fail community deletion's exact catalog check after the drop. 2. Then ship the drop migration and remove the schema entries. Operators with external tooling that expects `delivery_log` to exist must update it first. The partition audit stops emitting `buzz_partition_audit_*` series with `table="delivery_log"`. Alerts keyed on that label will go quiet. ### What got simpler Two tables' worth of code paths are gone: partition management, the audit, and five deletion handlers stop special-casing them. The follow-up removes the tables and the `RETIRING_SCOPED_TABLES` entries. ### Testing On a remote workstation at `3675ff17`: `cargo fmt --check`, `clippy -D warnings` for buzz-db, buzz-deletion and buzz-relay (all targets), unit tests for buzz-db (lib and tests), buzz-deletion and buzz-relay bins, and `scripts/postgres-test-run.sh` for buzz-db partition/deletion/migration tests (294 passed) and all buzz-deletion Postgres tests (44 passed). The new tests cover: retiring tables purged and verified while present; a request inventoried before a real `DROP TABLE` still purges and verifies; `validate_approved_schema` tolerates only retiring tables vanishing. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
69ea27343c |
Fix media deletion’s community ownership and share agent discovery (#9670)
## Summary Deleting a human must preserve an agent's uploads in communities where someone else owns that agent or its profile is missing. Media cleanup now carries community/key pairs through database and storage discovery, shared-file decisions, and uploader-row deletion. Media, content, account and profile cleanup share one direct-agent discovery utility. Each caller retains its previous limits and transaction behavior. Media discovers ownership once per invocation, including retries, and uses a hash set for storage matching. The report shape stays unchanged. The operator guide explains that community/agent pairs have no separate cap and sit outside the inventory budget. The discovery helper documents that global, identity-grouped discovery requires `lock: false` because PostgreSQL cannot combine `GROUP BY` with `FOR SHARE`. Run a read-only preview first, then keep writers stopped throughout deletion. Reverting the binary restores the old cross-community selection bug; it cannot restore deleted objects. ### Related issue Follow-up to the merged media handler in #9365 and the content/account/profile handlers in #9363, #9364 and #9580. No duplicate of this ownership correction was identified. ### Testing Exercised the rebuilt `buzz-admin user-deletions media-batches --pubkey <fixture-human> --read-only`, then `--delete`, against isolated PostgreSQL and versioned MinIO. Preview changed neither rows nor storage. Exclusive versions and in-scope uploader rows were deleted; shared originals, thumbnails and historical versions survived. All four handler commands agreed before and after a between-invocation ownership change. Failure followed by retry used fresh ownership, and repeat deletion removed zero versions. Compared the production candidate SQL with the pre-PR query on about 50,000 local upload/audit rows. With 9,999 agents, execution took 120–185 ms per 500-row page versus 38–83 ms before community matching. Three runs per query; this excludes planning, Rust preparation and storage operations. The added per-version ownership queries are removed entirely. Full database/deletion/admin package runs passed (339 tests). The PostgreSQL database/deletion run passed 904 tests; after strengthening the retry fixture, the full deletion PostgreSQL package passed all 45 tests. The retry case retains ownership in another community, and media tests assert exactly one ownership lookup per invocation. Local `just test` completed with one failure in the unchanged relay logging test `composition_log_does_not_leak_issuer_url` (expected warning not captured); all other test groups passed. Two pre-push attempts failed in unchanged ACP tests: first a launch timeout, then credential tests using Git 2.40 where 2.46+ is required. All four credential integration tests passed with Git 2.54; the full pre-push retry was stopped at the author’s request to skip local checks and push. Local `just ci` was also stopped before completion. Neither interrupted run is a full pass; local hooks were skipped for publication. The follow-up for the optional review comments changes documentation only. Its statements were checked against the query and all five production callers; `git diff --check` passed. Runtime suites were not repeated for this follow-up. Human local acceptance remains pending. 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> |
||
|
|
729cb10b78 | buzz-db: drop the remaining relay foreign keys (#9740) | ||
|
|
890824f072 |
feat(read-state): sync mark read, channel mark unread and thread follows (#9501)
Reading, mark read, whole-channel mark unread and thread follow choices now sync across a person's installations. This PR specifies the rules in NIP-RS and implements them in the mobile app. ## Spec (`docs/nips/NIP-RS.md`) - Defines *catch-up* and *displayed*. - A catch-up advances the channel's own frontier (top-level messages) or `thread:<root>`. `activity:` and `thread-activity:` become read-only legacy keys. - Explicit mark read is synchronized state. A first explicit read of a message with no override group writes only its `msg:` frontier. Display, dwell, scroll, catch-up and mention visibility create no `msg:` entries. - Only whole-channel override groups are published, merged and cleared with the counter. Readers ignore peer `msg:` and `thread:` groups. - Single-message and thread mark unread stay on the device. They end once the merged frontier covering them passes their baseline, from any installation, or on display, catch-up or explicit read. The section also states clearing scope, the accepted concurrency limitation and capacity. - When the merged override union no longer fits the primary, the client rewrites the primary compactly from the groups its last published primary carried, each canonical against current frontiers. It never omits merged groups or tombstone floors that primary carried, and override actions fail visibly. - Adds Buzz Thread Follow Choices: `thread-follows:<32hex>` coordinates, validation, three-state verdict, last-writer merge with ties going to unfollow, publication and recovery, legacy import at `at = 0`, and capacity. ## Mobile - Catch-up writes the main frontier. A flat timeline reads up to the newest top-level message it reached. - Explicit mark read publishes. Passive `msg:` marks stay on the device. - Whole-channel mark unread publishes an override group and merges peer groups. An explicit read or catch-up clears it, even when no frontier moves. The action fails visibly at the uint32 limit or when the primary is full. A synced clear the primary can't carry is rolled back, and the channel view reports it once while the failure stands. - Device-local message and Inbox unread overrides record a baseline and clear when a covering frontier passes it, including one merged from a peer. - Thread follows move from local storage to the synced `thread-follows:` slots. They share the read-state `client_id`, journal, `created_at` sequence, snapshot and live subscription, and spill across up to 16 slots with stable placement. An unreadable coordinate marks follow state incomplete and blocks this installation's follow publication. - Follow and unfollow are refused on every cold start of the writer until its first complete recovery of its own state succeeds and every owned follow head is readable. Cached follows show at once. A refused tap changes nothing and shows "Follow choices are not ready. Connect and try again." Reads, catch-up and both kinds of mark unread are not gated. - A follow tap is accepted only once journaled. The accepted own head, pending edits and the exact in-flight packet are kept apart, so a retry or restore never drops or re-attributes an edit. - Pre-sync local follows are imported at `at = 0` after a complete merge, once their channel is known from a relay event. An imported key is settled, and its legacy copy retired, only when the journal write the import awaited covered it and that entry is still current. - An explicit unfollow suppresses ordinary replies at live and catch-up admission. A change in follow choices drops the unread replies already counted for an unfollowed thread. A newly followed thread re-runs catch-up only for its own channel. - A reading clear refused because the view hasn't completely loaded is retried after the next complete snapshot, including when publishing was shut off at the time. The view also counts as not completely loaded while the live subscription is reconnecting, so a read made while the phone is offline can't erase a newer unread mark set on another device. Offline, whole-channel mark unread is still refused, with a message. - Read-state events, including live ones, are verified with native libsecp256k1 before they are used. - A pending unread packet is counted as published only when no newer own head outranks it. When a newer head supersedes it, a successor is built above that head from the saved intent, and a late echo of a replaced packet doesn't overwrite what was published. - When the merged unread state overfills the primary and the compact fallback can't carry a pending mark, the packet stays pending and the "read state full" error shows. Other queued reads and follows in the same flush still publish. - When this installation's own unread record can't be decoded, only the unread step is held: that record isn't overwritten, its pending marks stay queued and the sync error shows. Other queued reads and follows in the same flush still publish. - The sync notice stays up after an unsupported refusal until a new session. Offline, it can't be tapped and says it will retry when back online. - Two-device fixtures against an in-memory relay cover channel round-trips and clears, stray message groups, the first explicit message read, the primary cap, follow propagation, same-second and backward-clock follow publication, legacy import, retry after a failed publish, unreadable coordinates and slot packing. Recovery fixtures cover the startup gate, journal failures during flush, interleaved legacy imports, and restore of an older journal. ## Relay - Conforming `thread-follows:<32 hex>` records get the NIP-RS treatment: a replaced record is purged, and a stale resend of an older one is refused. Records with a mismatched `t` tag keep ordinary replaceable-event behavior. ## Known gap - An unread packet held for capacity can age past the relay's timestamp window. The relay then refuses it, and the refusal path retires it without the capacity check, so the error clears and other installations don't get that mark. The mark stays on the device. Related: [block/buzz-app#3552](https://github.com/block/buzz-app/pull/3552) --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Will Pfleger <wpfleger@squareup.com> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
cda68a9333 |
Fix shared stars and mutes in mobile and CLI (#9684)
## Summary Mobile, CLI, and legacy desktop write millisecond timestamps for new star and mute edits. They compare legacy seconds in the same unit and retain the original timestamps of untouched entries during rollout. Mobile and CLI cap saved records at 500 entries and repair oversized records on a write. CLI no-op adds and removes leave oversized records alone. They keep the current edits and evict by age, preferring clears when timestamps tie. The CLI accepts a full flag record within the short-form NIP-44 envelope. Mobile builds each write from the writer's retained snapshot plus a durable journal of local edits. The journal drains in batches of at most 500 edits. It retries transient failures and older writer snapshots with bounded backoff and retires a pending edit after verifying that the writer already holds it or holds a strictly newer one. Retried writes preserve the original entry timestamps. An exact timestamp tie with a conflicting writer value advances by one millisecond so older clients accept the edit. An unreadable record pauses writes until a valid snapshot or app resume. On mobile upgrade, a verified writer snapshot lets the app recover newer local star and mute edits from the old cache. The legacy cache has no edit journal. Below 500 writer entries, the app also recovers absent active flags. At 500 or above it only recovers absent active flags dated after the snapshot's creation second. Absent legacy clears and clears newer than the writer's recorded clear are kept locally. They enter the publish queue when an older or equal enable appears. If the enable disappears before preflight, the clear returns to the local cache. A newer enable, an equal or newer clear, or a fresh tap retires the saved clear. A cached enable is queued when it is newer than the writer entry or ties a writer clear. A strictly newer cached enable advances the timestamp even when both copies are enabled. Recovered enables and promoted clears keep their original stamps in the journal. When the relay entry is absent or uses seconds, the write keeps a recovered seconds stamp so a later edit from an older phone can win. An existing millisecond entry uses millisecond comparison and serialization for the recovered edit. ## Validation - Mobile regressions exercise a later seconds-stamped edit, two-device eviction, a pending clear at the cap across manager replacement, transient read recovery, a losing duplicate acknowledgement, and a second toggle during confirmation, including at the cap. - CLI regressions cover seconds-stamped entries, the 500-entry limit, recovery from oversized records, and clear retention, including a repeated remove that leaves active flags intact. - Runtime validation uses scripted relays. - All 702 CLI tests passed. - Pre-push gates passed, including the full Flutter suite and analysis, repository Rust tests, and desktop Tauri checks. - Legacy desktop tests cover mixed-unit merges and back-to-back toggles. Mobile upgrade regressions cover newer offline entries, eviction, reconnect, and malformed-head recovery. --------- Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz> |
||
|
|
e581555bf8 |
perf(relay): serve named-only channel access from the access caches (#9735)
## What
REQ, COUNT, `POST /query` and `POST /count` now take a reader's
named-only channel access (system channels, and any type added later)
from the two access caches they already read. Before, any filter that
opted in to system channels, or named a channel outside the implicit
set, ran `get_readable_named_only_channels` on the writer, uncached, on
every request.
## Why
Clients send such a filter on every connect. buzz-app's system channel
discovery reads `{kinds:[39002], "#p":[me], "#t":["system"]}`. So a
fleet reconnect (rollout, relay restart, network blip) paid one extra
uncached writer read per client, on top of the cached access set. This
read showed up near the top of writer SQL during reconnect herds.
## How
- `get_member_channels_read_at` and `get_listed_open_channels_read_at`
(buzz-db) return every channel type, with their connection checkout
time, and split rows into the implicit set (legacy types) and the
named-only set, with the type. They are the same two queries as before,
without the type filter. `get_member_channel_ids` and
`get_listed_open_channel_ids` keep their results.
- With no names, the two named-only halves together are exactly what
`get_readable_named_only_channels` returns. A new Postgres test pins
that equality for a member and a non-member.
- `AppState::get_channel_access_cached` returns a `ChannelAccess` from
the member cache (per pubkey, 10 s, dropped on every membership write)
and the open cache (1 s, shared reads). It yields the named-only
channels on demand, so a request that uses only the implicit set does no
extra work. `get_accessible_channel_ids_cached` is now a wrapper around
it.
- Both caches' refills are fenced against invalidation by a small shared
`LoadFence` (new `load_fence.rs`), as `MembershipCache` does.
Overlapping misses for a key share one load token, so the first read to
finish publishes. Invalidation drops the token, and a read publishes
only while its token is current. Before, a read that began before a
removal (or an open-to-private change) could finish after it and cache
the old set. That race also affected private stream/forum channels.
- The member snapshot is dated from its read's connection checkout, like
the open set, and a hit older than `MEMBER_CHANNELS_MAX_AGE` (10 s)
reads again. Before, its 10 s started at insert, so a slow read
stretched the bound.
- `readable_named_only_channels_for_filters` uses the cached set when
every channel the request names outside the implicit set is in it. The
system opt-in needs exactly that set. When a request names any other
channel (an unlisted open channel, or one it can't read), it keeps the
uncached read, unchanged.
- A `"consistency": "strong"` `POST /query` takes its named-only access
from the database, so a client that just created a system channel finds
it even on a pod that has not yet seen the invalidation. REQ, COUNT and
`POST /count` keep the cache.
- The thread-window and workflow checks keep the uncached read.
## Staleness
Same as the implicit set's today. Every membership write
(`invalidate_membership`) drops the per-pubkey entry, whatever the
channel type, and the drop is sent to every pod. On the pod that ran the
removal, the next request sees it (the refill fence closes the race). A
missed cross-pod drop keeps a removed member's system channel for up to
10 s after the read began on that pod, as for a private channel. The
open half is used for 1 s.
## What got simpler
No new access cache and no new invalidation trigger. The named-only
access now comes from the same snapshot as the implicit set, so REQ no
longer mixes a cached implicit set with an uncached named-only set.
`get_member_channel_ids` and `get_listed_open_channel_ids` no longer
have their own SQL, and their unused `Db` wrappers are gone. The two
replacement reads keep the old span names (`get_member_channel_ids`,
`get_listed_open_channel_ids`).
## Tests
-
`handlers::system_channels::tests::cached_access_answers_named_only_needs_without_a_database_read`
(unit, unreachable DB): discovery and a cached `#h` name are answered
with no read, the token scope still narrows the result, and a name
outside the cached sets reads the database.
-
`store::unlisted_channels_postgres_tests::cached_channel_sets_match_the_uncached_named_only_read`
(Postgres): the cached halves equal the uncached read and the accessible
set.
-
`state::tests::a_member_read_that_straddles_an_invalidation_is_not_cached`
(unit): a read held open through a per-user or a community-wide
invalidation answers its own request but is not cached.
-
`state::tests::an_open_read_that_straddles_an_invalidation_is_not_cached`
(unit): an open-set read held open through the community's invalidation
answers its own request, and the next request reads again.
- `state::tests::a_member_snapshot_ages_from_its_read_not_its_insert`
(unit): a member snapshot already 10 s old when published is not served.
- `state::tests::overlapping_member_reads_cache_the_first_to_finish`
(unit): a second miss that starts while the first read is in flight does
not stop the first from being cached.
-
`handlers::system_channel_postgres_tests::a_strong_query_sees_a_just_created_system_channel_past_a_stale_cache`
(Postgres): a strong `/query` finds a just-created system channel past a
stale member entry.
-
`handlers::system_channel_postgres_tests::a_token_scope_narrows_system_channels_on_both_access_paths`
(Postgres): token-scoped WS REQ and COUNT, through the cache path and
the database path.
- Must-fail mutants: always take the database branch; keep only legacy
types in the member query; drop the token scope at the REQ call site;
publish without the fence check; drop the open-set token on
invalidation; ignore the member snapshot's checkout age.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
|
||
|
|
d9c3f4e99e |
Remove personal workflow data and missed event copies (#9675)
## Summary User content cleanup left private hide-list snapshots, saved workflow inputs and notes, unused automation, and some delivery copies behind. This extends the existing per-community content handler to remove them with the same preview, ownership and retry checks. - Delete trusted-relay hidden-DM snapshots and author-signed historical file-metadata events (kind 1063). - Clear recorded event-trigger text/emoji, authenticated manual inputs, and the recorded approver's note while preserving the rest of each run or approval. - Delete unused workflow database definitions and their schedule claims together. Any run, approval or linked claim protects the definition. The entire group must fit the requested batch size, capped at 100 rows, or planning refuses before mutation. - Delete delivery logs under surviving subscriptions before erasing their source events; reject newly arrived dependent rows before committing. Check the whole event batch with hashed membership to avoid repeated work across unrelated delivery history. Run deletion offline with the relay, workflow engine and external writers stopped. Shared history, canvases, artifacts, Git data and device registrations remain outside these additions. Retained runs can subsequently read the cleared inputs; this does not cancel them or claim complete account erasure. Existing signed kind 30620 event cleanup is unchanged. This is an application-only change against existing tables. It adds no migrations, indexes, triggers, functions or foreign keys. Existing per-statement timeouts and community write admission remain in use. ### Related issue Related: #9353. Extends the content handler in #9363. Shared workflow ownership policy remains separate from these personal-field deletions. ### Testing Ran the rebuilt `buzz-admin user-deletions content-batches --community <fixture-community> --pubkey <fixture-user> --batch-size 100` against disposable PostgreSQL 17 fixtures with 100 events, 500,000 unrelated delivery logs, and 9,999 small communities. `--read-only` selected 100; `--delete` removed 100 in 0.39 seconds locally; a second `--delete` selected zero. All 500,000 unrelated same-community delivery rows survived. EXPLAIN used hashed membership under both custom and generic plans. Independent review also exercised stale statistics. Removing the planner safeguard made the regression fail at the executor's actual 3-second timeout. The late-copy test still refuses deletion and preserves the source until retry can include the new copy. Independent agent review completed with no remaining blockers. Earlier command validation on the original patch exercised all agreed additions: preview nine operations, delete nine, retry zero, with whole-row preservation checks for the other community, shared canvas, surviving subscriptions, workflow output/provenance, and other approvers' notes. The repository-wide `just ci` run passed static checks, then stopped on two timeouts in unchanged `buzz-agent` OAuth tests. Both cases passed a serial recheck. The subsequent normal push hooks passed, including the complete Rust unit lane and Tauri checks. Later app build/test recipes were not reached; the full local CI command is not claimed green. Human command verification is pending, so this PR remains draft. On disposable fixtures, run the same preview/delete/retry sequence and verify that only the planned rows/fields change. Generated with Codex --------- Signed-off-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
946d9c3467 |
fix(relay): rename target log field to target_pubkey (#9739)
Rename the relay's custom structured log field from `target` to `target_pubkey` at the affected call sites. `tracing` also writes its own `target` field (the module path) after callsite fields, and Datadog keeps the last value. That overwrites the pubkey; using `target_pubkey` preserves it without changing tracing's built-in `target` metadata used by `RUST_LOG` and Vector routing. Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Alia <d32955ad69077062930cc46cfe2df30ca9aaf6f8e76422681265e9e9af704d78@buzz.block.builderlab.xyz> |
||
|
|
379b501124 |
feat(push-gateway): declarative desired-state schema, one file per table (#8328)
## Summary Gives the push gateway a declarative desired-state schema in the same layout the relay uses since #8131: a `\i` manifest plus one file per table, the shape SchemaBot reads. - `crates/buzz-push-gateway/schema/schema.sql`: an ordered `\i` manifest and nothing else. - `crates/buzz-push-gateway/schema/tables/public/<table>.sql`: the end state of migrations `0001`–`0008` for all six gateway tables. That includes `0007`'s `installations.platform` column and `0008`'s dropped delegation → installation foreign key (#9610), so the delegation table declares no `REFERENCES`. Each file holds only its `CREATE TABLE` and plain `CREATE [UNIQUE] INDEX` statements. - `src/postgres.rs`: the six table names are now one `GATEWAY_TABLES` constant shared by readiness and the runtime-role GRANT, instead of two hand-copied lists. - `src/postgres/desired_schema_postgres_tests.rs` adds two tests: - `desired_state_schema_layout_is_complete_and_schemabot_shaped` (no infra needed). It checks that the manifest includes every file exactly once and holds only `\i` lines, that each table file creates exactly one table, and that indexes use a plain `CREATE INDEX` on that table. - `desired_state_schema_matches_migrations` (PostgreSQL lane). It builds one probe database from `schema.sql` through the real `bin/pgschema apply` and another through `GATEWAY_MIGRATOR`. It then requires the two `public` catalogs to match: table set, columns from `pg_attribute` (full type with typmod via `format_type`, default, nullability, identity, generation, collation), table options (persistence, RLS flags, `reloptions`), constraints (`pg_get_constraintdef`) and index shapes (`pg_get_indexdef` + `indoption`). Neither probe may hold functions, non-internal triggers, policies, views, sequences or user types, and the declared table set must equal `GATEWAY_TABLES`. It compares the whole `public` catalog, not a list of tables, so a future migration that changes `public` tables, columns, table options, constraints or indexes without a matching `schema/` change fails CI. It doesn't cover data-only migrations or objects outside `public` (other schemas, roles, database settings). Probe databases are created from `template0` and dropped even when an assertion, `pgschema` or setup fails; the original failure is re-raised unchanged. Connection details, including the password, come from the resolved `PgConnectOptions`, so percent-encoded credentials, `?password=` and Unix-socket URLs reach `pgschema` the way SQLx sees them. `pgschema` 1.7.4 builds an unquoted keyword DSN, so a password or socket path with whitespace, a quote, `=` or a backslash isn't supported (noted in the test). ## Not changed The gateway still migrates itself at startup: bootstrap guard, then SQLx migrations, then runtime-role grants. The guard and grants are operational steps, not desired-state DDL, so they stay in code. No `schemabot.yaml` is added: SchemaBot isn't configured for the relay or the gateway yet, so the yaml for both waits until that server-side setup exists. The manifest header notes that the relay's post-pgschema reconcile step (root `AGENTS.md` gotcha #7) doesn't apply, because the gateway schema has no seed DML or storage parameters. SchemaBot compatibility is not proven here. The parity test shows the files are equivalent under `pgschema`. Since #9610 the gateway schema has no foreign keys, so the earlier inline-FK caveat is gone. `docs/database.md` Rule 4 now lists the gateway `schema/` directory as a schema location. ## What got simpler To read the gateway's schema today you have to replay eight migrations: two CHECK rewrites, two dropped UNIQUE constraints, a dropped column, an added column and a dropped foreign key. After this PR it's one declarative file per table, in the same convention as the relay. There is no new runtime path and no new abstraction, and the duplicated table list in `postgres.rs` collapses to one constant. ## Testing At `c4336392` (rebased on main after #9610; mirrors gateway `0007`/`0008`; reads the `pgschema` password from a copy with a URL-safe host and username, so a `PGHOST` or default-search socket no longer panics and a `/role` username no longer drops the password): - `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings`: pass. - `cargo test -p buzz-push-gateway --lib desired_schema`: pass, including `resolved_password_reads_through_a_socket_host_and_slash_username`. Removing the username normalization makes that test fail. - `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 17/17 passed, including `desired_state_schema_matches_migrations`. At `df3ff104` (password from resolved connect options), same workstation: - fmt, clippy (`-D warnings`, with and without `personal-dev-app-attest`): pass. `cargo nextest run -p buzz-push-gateway`: 80/80, and 82/82 with the feature. `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 13/13. - `?password=`: with `PGPASSWORD` unset, `postgres://<role>:wrong@localhost/postgres?password=<encoded p@ss:w/rd#x>` passes the parity test, so `pgschema` gets the query-parameter password that SQLx uses. A wrong `?password=` is rejected (`28P01`). - The CHECK-bound falsification still fails with `constraint parity mismatch`. Every run leaves 0 probe databases. At `f937924a` (probe cleanup and connection-URL follow-up), on a Linux workstation against PostgreSQL 16 with the repo's pinned `bin/pgschema`: - `cargo fmt --all -- --check`, plus `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings` with and without `--features personal-dev-app-attest`: pass. - `cargo nextest run -p buzz-push-gateway`: 60/60 passed, and 62/62 with `personal-dev-app-attest`. `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 12/12 passed. - Probe cleanup: with a CHECK bound changed (2048→4096), the previous test code fails and leaves both `push_gateway_{desired,migrated}_*` databases behind. The new code fails with the same `constraint parity mismatch` panic and leaves none. A table file that makes `pgschema apply` fail (`no_such_column`) also reports `pgschema apply failed: ... column "no_such_column" does not exist` and leaves none. - Connection URLs: the parity test passes as a role whose password is `p@ss:w/rd#%x`, given percent-encoded in the URL with `PGPASSWORD` unset. It also passes over `postgres://<user>@%2Fvar%2Frun%2Fpostgresql:5432/postgres` (Unix socket, peer auth). Earlier, at `ee2745cb78`: - `scripts/postgres-test-packages.sh` discovers `buzz-push-gateway`. The parity test lives under a `*_postgres_tests` module so the `postgres-ci` nextest filter selects it. - `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings` both pass. - `cargo nextest run -p buzz-push-gateway`: 60/60 passed, including the layout test. - `scripts/postgres-test-run.sh -p buzz-push-gateway`: 12/12 passed, including `desired_state_schema_matches_migrations`. - Falsification checks: - Dropping the partial predicate from `push_gateway_installations_active_token` makes the parity test fail with an index-shape mismatch. - Adding an unmirrored `0007` migration (`ADD COLUMN probe TEXT`) makes the parity test fail with a column mismatch. Mirroring the column in the table file makes it pass again. - Putting `CREATE TABLE` DDL in `schema.sql` makes the layout test fail. - A `0007` adding `probe VARCHAR(64)` mirrored as `VARCHAR(128)` fails with a column mismatch (typmod); mirroring it exactly passes. - An unmirrored `0007` `ALTER COLUMN expires_at TYPE TIMESTAMP` fails with a column mismatch. - An unmirrored `0007` `ENABLE ROW LEVEL SECURITY` fails with a table-option mismatch. - A `0007` creating a function and trigger fails the "only tables and indexes" check. Known gap: `sqlx::migrate!` doesn't notice a *new* migration file on an incremental build. The crate has no `build.rs` `rerun-if-changed`, and neither does any other crate in the workspace. For the `0007` check above I touched `src/postgres.rs` to force the macro to re-expand. Clean CI builds aren't affected. buzz-review-completed --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7e7ec731cd |
test(cli): keep the raw refusal exit test independent of BUZZ_* env (#9733)
## Summary
Follow-up to #9653. Its new test
`cli_exits_nonzero_when_the_relay_refuses_a_raw_publish` went through
`run_from_args`, which resolves credentials from the caller's
environment. With `BUZZ_AUTH_TAG` set (as it is for agents run by the
ACP harness), the test client's key doesn't match the auth tag and the
test exits 3 instead of 2.
The check moves to an integration test,
[`tests/raw_publish_exit.rs`](
|
||
|
|
bc3023a050 |
push-gateway: drop the delegation → installation foreign key (#9610)
## Summary Retire the last foreign key in the push gateway schema: `push_gateway_delegations.installation_id → push_gateway_installations(id)`. This follows `docs/database.md` Rule 2 and the relay FK retirement work (#9399, #9404). - **Gateway migration 0008** drops the constraint. - **Relay migration 0101** drops the relay's legacy copy (Rule 4: gateway schema changes go in both). `schema/tables/public/push_gateway_delegations.sql` loses the inline `REFERENCES`. ## Required stop Every gateway and rollback target must run #9627 (`44cdd9fe`) or later before this merges and deploys. #9627 makes the reaper lock expired installations before it deletes their delegations. Without the FK, an older reaper can leave an orphaned delegation. This is step 2 of the Rule 5 retirement sequence; #9627 is step 1. ## Why the app already enforces the reference | Path | Check | |---|---| | `upsert_delegation` (only delegation insert) | Locks the installation `FOR UPDATE` in the same transaction; rejects a missing or revoked one. | | `create_installation` (replaces expired installations) | Locks the matching installations `FOR UPDATE`, deletes their delegations, then the installations. | | `reap_expired` | Locks expired installations `FOR UPDATE`, deletes their delegations, then the installations (#9627). | | `authorize_delivery` | Reads the installation through the delegation; a missing installation is `Rejected`. | | `revoke_delegation` | Updates the delegation only; an orphan has no effect. | | `revoke_installation`, `rotate_endpoint`, `advance_assertion_counter` | Update the installation; they never delete it. | The relay never reads or writes the `push_gateway_*` tables (the gateway requires its own database), so dropping the relay copy changes no relay behavior. ## Tests The gateway tests run against the migrated schema, which no longer has the FK, so they prove the app check. - `migrated_schema_has_no_foreign_keys` (new): the gateway schema has no foreign keys after migrations. It fails if gateway migration 0008 is removed. - `delegation_for_missing_installation_is_rejected` and `reaper_deletes_delegation_committed_while_it_waits` (from #9627) now run without the FK. - `reaper_retains_revocation_tombstones_until_authority_expiry`: its hand-built schema drops the FK too. - Relay: `push_gateway_delegations` joins the constraint parity check in `admin_schema_parity_between_desired_state_and_migrations`, and the migration count test covers 0101. ## Validation Blox at `33f7df90` (before the rename to 0101; CI covers the rebased head): - `cargo fmt --check`, clippy (`buzz-push-gateway`, `buzz-db`, all targets), gateway unit tests, `buzz-db` migration unit tests: pass. - `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 16/16 pass. - `buzz-db` Postgres tests for migrations, parity, push, floor retirement and retained guards: 56/56 pass, including `admin_schema_parity_between_desired_state_and_migrations`. - Must-fail check: with gateway migration 0008 removed, `migrated_schema_has_no_foreign_keys` fails (1 foreign key vs 0). ## Coordination - On main after #8696, #9398 and #9710 (relay 0095–0100). #9627 shipped this PR's reaper fix and tests separately, so this PR is the schema drop only. - Renumbered to relay 0101 after #9710 took 0098–0100 (rename only; file contents unchanged). #9690 and #9621 also add a relay 0098; whichever merges second renumbers. - #8328 adds the gateway's declarative schema with the inline FK. Whichever PR merges second removes it there. ## What got simpler One fewer database object. Every gateway reference check now lives in one place: the gateway's own transactions. 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> |
||
|
|
5ccbb61190 |
feat(cli): add raw query and publish escape-hatch commands (#9653)
## Summary Agents using the CLI had no way to answer questions like "which channels is key X a member of" (kind 39002 with `#p`) without scanning channels one at a time, which runs into identity-adapter rate limits. This adds a small escape hatch that reuses the CLI's existing credentials (signing key, auth tag, federated identity assertion): - `buzz raw query <filter>`: send one filter object or an array of filters (or `-` for stdin) to the relay's `/query` endpoint and print the relay's JSON as-is (an event array, or an object for filters such as read-state snapshots). - `buzz raw publish`: build, sign and send an arbitrary event, either from `--kind`, repeatable `--tag` (JSON arrays, as in `social set-list`) and `--content`, or from a full `--event-json` template. Signing goes through `sign_event`, so the auth tag is attached as for every other command; a caller-supplied `auth` tag is refused. Ephemeral kinds (20000 to 29999) use the ephemeral publish path, except the NIP-43 leave request (28936), which goes over HTTP because the relay revokes the submitting socket on success. Gift wraps (1059) are refused, since they need NIP-59 signing with a throwaway key. Malformed input (bad JSON, a filter that isn't an object, a bad tag) exits 1 with the usual `user_error` JSON; the relay validates filter fields itself, and its rejection exits 2 as a relay error. A publish the relay refuses (`accepted:false`, over HTTP or the WebSocket) exits 2 with the event id and message. README and TESTING.md list the new commands and their limits (replaceable and addressable kinds replace the whole event; kind-scoped credentials can fail artifact revisions). ## Regressions None expected: this adds a new command group and does not change existing commands. `submit_event` now also gives the relay-admin kinds (9030 to 9033), identity archive and unarchive requests (9035, 9036) and the leave request (28936) the moderation retry policy (no blind resend after an ambiguous outcome). `agents archive` and `agents unarchive` send 9035 and 9036, so after a lost response they now report an unknown outcome instead of resending, which could re-archive over a later unarchive. ### Validation Tried against a live relay as a signed-in user: a kind 39002 `#p` query listed one key's channels, a two-filter array and an `ids` lookup returned the expected events, and `raw publish` sent a typing indicator, a reaction and a deletion of that reaction, all accepted. New tests in [`raw.rs`]( |
||
|
|
98e2b7cbbc |
feat(relay): push mentions to people outside a listed channel (#9623)
## Summary A message that `p`-tags someone in a listed channel they haven't joined now sends them a push. Before this, push woke only channel members. This is the relay part of "Let them know", a choice for mentioning people outside a public channel. The client changes are https://github.com/block/buzz-app/pull/3769, https://github.com/block/buzz-app/pull/3771 and https://github.com/block/buzz/pull/9629. - The matcher wakes a non-member only when a `p` tag names them and the channel is open, not unlisted, and a stream or forum. It reuses the channel directory's `LISTED_CHANNEL_SQL`. - Delivery checks again before sending. The channel must still be listed, the event must still mention them, and they must still be able to connect. A ban on them or their agent's owner blocks the push, and so does a missing membership or allowlist entry when the relay requires one. - Members, private and unlisted channels, DMs and system channels are unchanged. **Needs security review.** This decides who gets push wakes. A wake goes only to someone who could already read the event with `REQ`, and it carries no message content. Follow-up: a banned or removed channel member still gets wakes until their lease expires. That predates this PR, and the fix belongs in the ban and removal code. ### Related issue None found. ### Testing - Postgres tests run ingest through delivery against a fake gateway. They cover private, unlisted and system channels, a switch to private before delivery, bans, removal, a missing allowlist entry, and an agent relying on its owner's membership. I made 20 small changes that each broke one of these checks, and each one made a test fail. - On a local relay with a stand-in gateway, an outsider's mention push arrived, and nothing went out after a ban, a removal or a switch to private. With the new delivery check turned off, the banned and removed people got pushes. - Not tested: a real gateway and a phone. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Soheyl Vakili <soheyl@squareup.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
9ea57cba2a |
fix(db): undo migration 0097 (#9710)
## What Migrations `0098`–`0100` undo migration `0097` (community artifact expand). The declared schema goes back to its shape before #9650. #9650 added `0097`. The revert, #9689, removed the feature but kept `0097` byte for byte, because databases that auto-migrated recorded its checksum. No code on `main` reads or writes what `0097` added. This PR removes it with forward migrations, as `docs/database.md` requires ("Never edit a merged migration. Fix forward."). `artifact_heads.channel_id` gets `NOT NULL` back in the three steps from *Adding `NOT NULL` to a populated table*: - `0098` checks that the artifact head key is `(community_id, artifact_id)`, then adds `CHECK (channel_id IS NOT NULL) NOT VALID`. - `0099` validates the check under `SHARE UPDATE EXCLUSIVE`, so channel artifact reads and writes continue. - `0100` sets `NOT NULL` from the validated check (no scan), drops the check, drops `artifact_heads_live_type`, `artifact_heads_scoped_identity` and `artifact_revisions_scoped_identity`, and drops `artifact_heads.scope`, `artifact_revisions.scope`, `artifact_revisions.community_event`, `artifact_revisions.redacted` and `communities.artifact_type_policies`. The primary keys don't change. `0097` never changed them. ## Review checklist (docs/database.md) - **Phase:** contract. It follows the expand in #9650 (`0097`) and the code revert in #9689. - **Required stop:** every relay pod, job and rollback target must run #9689 (`sha-a406191`) or later before `0100` runs. The chart's upgrade notes (`deploy/charts/buzz/README.md`) say this, along with how to roll back with auto-migration off. No tagged relay release contains #9650. Only rolling images from `eebf62b6` up to, but not including, `a4061916` are affected. Relays built from #9650 itself read `artifact_heads.scope` and write with `ON CONFLICT` on `artifact_heads_scoped_identity`. Releases before #9650 never read these objects. - **Fails closed:** `0098` refuses a database whose artifact head key is the scoped key from #9650's removed operator contract script or declared schema. That database needs the recovery in #9689's Compatibility section. `0099` fails if any head has a null `channel_id`. Both stop before any cleanup. - No trigger, function, procedure, rule or foreign key is added. No migration changes existing rows. - Every schema location in Rule 4 is updated: `migrations/` and `schema/tables/public/` (`artifact_heads.sql`, `artifact_revisions.sql`, `communities.sql`). No reconcile-script or gateway change applies. - **Currently deployed relay:** a relay from #9689 or later doesn't use these objects, and neither does a relay from before #9650. The populated-table test runs every migration over channel artifact data. - **Locks:** each migration sets `lock_timeout = '5s'` and `statement_timeout = '30s'`. No index is built. ## Tests - `admin_schema_parity_between_desired_state_and_migrations` compares `artifact_heads`, `artifact_revisions` and `communities` across the desired-state and migrated paths. It fails without `0100`. - `populated_artifact_tables_auto_migrate_through_every_migration` checks that a channel head and revision written before `0097` survive with the same channel and event. - `artifact_unexpand_validates_while_channel_heads_are_written`: `0099` completes while a channel head write is still open. It fails if `0099` sets `NOT NULL` directly. - `artifact_unexpand_refuses_scoped_head_key`: `0098` stops on the scoped key and leaves `0097`'s columns in place. ## What got simpler The schema loses 5 unused columns and 3 unused indexes. `artifact_heads.channel_id` is required again, as the channel code assumes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4704fbafb6 |
fix(relay): resurface a hidden DM when someone else messages it (#9678)
## Summary A DM hidden with **Hide conversation** (kind 41012) stayed out of the sidebar for good, even after new messages arrived. The only way back was New message → same people → Send. This makes the relay clear the hide when *another* member posts a message (kinds 9 / 40002 / 40008) in the DM, like Slack does. The author's own hide is kept, so replying from another device doesn't resurface it. - `buzz-db` `dm.rs`: `unhide_dm_for_recipients` clears `hidden_at` for every other active member. `lock_dm_visibility` takes the same advisory lock that replacing the viewer's kind 30622 snapshot uses, then reads that viewer's hidden DMs and latest snapshot time. - `side_effects.rs`: `persist_dm_message` stores the message, clears the hides and replaces each affected viewer's snapshot in **one transaction**, then fans out after commit. A snapshot that doesn't land rejects the message, so the client's resend tries again. When someone hid the DM, the message takes the DM's membership lock before its insert, as a removal does, so it can't deadlock against a removal or reopen. The hide/open path (`publish_dm_visibility_snapshot`) shares the same lock → read → write seam. - Used by both message paths: client ingest (`ingest.rs`) and relay-signed workflow messages (`workflow_sink.rs`, author resolved via `effective_message_author`). - `NIP-DV.md`: documents the rule. **Deploy order:** relay first. The client companion is block/buzz-app#3889, which rereads visibility from the writer when a message lands in a hidden DM. Against an older client the row returns on the next roster refresh. ### Related issue N/A. None found. ### Testing - New Postgres test `dm_message_from_someone_else_unhides_it` (`membership_notice_postgres_tests.rs`): hide → the viewer's own message keeps it hidden → a peer's message whose snapshot is blocked by a trigger is rejected, not stored and not delivered → its resend, parked at fan-out, already shows the DM visible and is delivered once. It is `#[ignore]` (needs Postgres) and runs in Backend Integration CI. It was not run locally. - Pre-push `rust-tests` lane (`just test-unit`) and local clippy pass; `observability_source` source-policy test updated for the new transaction seam. - Reviewed by the Royal Court agents. Their findings (atomicity, lock-before-read, workflow path) are fixed in follow-up commits. - Human test pending. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Wes <wesbillman@users.noreply.github.com> Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b68c4edda5 |
feat(cli): show and search verified identity in users get (#9647)
## Summary `buzz users get` reads only kind:0 profiles, so the CLI can't find or confirm a person by their verified username. This adds relay-verified profiles (kind:30382) to `users get`. - `--pubkey` adds a `verified` object (`username`, `display_name`, `full_name`, `issuer_label`, `verified_at`) for subjects that have one. A requested person with a verified profile but no kind:0 is still returned. - `--name` uses the relay's `POST /profiles/search` when the community advertises verified profiles with `searchable: true`, so it matches verified names (word prefix). Otherwise, or for queries over the endpoint's 100-character limit, it runs the existing NIP-50 substring search and attaches verified profiles where the community advertises them. Verified profiles are read only when NIP-11 advertises `federated_identity.public_profile`. A projection is trusted only if it is kind 30382, signed by the relay's `self` key with a valid signature, and follows the NIP-FI projection rules the mobile client applies: empty content, exactly the projection tags (each once with one value), `p` equal to `d`, `active` set to `true`, a valid username, names of 1–64 characters with no surrounding whitespace or control characters (looser than mobile, which also requires NFC and rejects more Unicode categories), and a decimal `verified_at` no later than `created_at`. The newest projection per subject wins (the lower id breaks a same-second tie), so a retraction clears the verified name. Any `verified` key in user-authored kind:0 content is dropped on every path, so only a relay-signed projection can set it. `users get` now makes one NIP-11 request. If that request fails, the advertisement is malformed, or the kind:30382 lookup fails, it still prints the kind:0 results and writes a `verified_profiles_unavailable` warning to stderr. This applies to `--pubkey`, no args, and `--name`. ### Related issue Related: #8745 (verified profile spec), #9624 (verified-name mentions in workflows). ### Testing - `cargo test -p buzz-cli` passes, with tests for trust checks, retraction, both lookup paths, search without the advertisement, and a forged `verified` object in kind:0 (no advertisement, impostor-only projection, and a valid projection replacing it). - `cargo fmt` and `cargo clippy -p buzz-cli -D warnings` are clean. - An earlier revision of the built CLI was run against a live community with verified profiles: `--name <verified username>` found a user whose kind:0 name differs, and `--pubkey` returned the expected `verified` objects. --------- Signed-off-by: damienrj <damien@squareup.com> |
||
|
|
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> |