mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
493cb4cc1369ff9fdb44ae6c50f18c66d1fb6474
3552 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
493cb4cc13 |
perf(db): stop per-id planning of wide #e reads (#9591)
Thread pages fetch the reactions, edits and deletions of ~200 ids at once. Until a pooled connection has run that `#e` read about five times, Postgres plans it with the values: ~12 ms per plan (one estimate per id per partition) against ~2 ms to run it. Past 8 ids the arrays now go through a scalar subquery, so planning is one estimate (~1.5 ms) and still uses the tags GIN index; narrower reads are unchanged. On an 830-reply local thread, one viewer's full scan drops from 119 to 59 ms p50; with 50 viewers p50 holds at 242 ms, p99 drops from 664 to 413 ms, and the read's planning time falls from 13 s to 0.6 s per minute. --------- Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> |
||
|
|
bc3afbb293 |
[buzz] fix(ci): link relay image indexes to their source (#9637)
The relay image index includes the qualified Git revision. Add the source repository URL beside it so OCI registry clients and deployment tools can link the image to the exact source commit. The manifest assembly step derives the URL from GitHub Actions' server and repository variables. The release workflow contract checks that the index includes both the source and revision annotations. Signed-off-by: Helen Tian <htian@squareup.com> |
||
|
|
25b58ab98f |
feat(push-gateway): verify Android Key Attestation (#9562)
## What and why Ticket 3 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now verifies Android Key Attestation at enrollment instead of rejecting every Android chain, and rate limits signed installation calls per attested key. Stacked on [#9560](https://github.com/block/buzz/pull/9560) (Android enrollment and FCM wakes). This PR's base is that branch; it will be retargeted once that merges. - **Chain.** It must end at a configured Google attestation root (Google's [published hardware roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate) are built in, pinned by public key), with valid signatures and issuer links, CA issuers above the attestation key certificate, and no SHA-1 signatures. The attestation key certificate itself is exempt from the CA flags, because some factory keyboxes issue it with CA:FALSE and digitalSignature only (Google's Sony Xperia 10 III sample); a Keystore leaf still cannot act as an issuer, since the extension is refused above the leaf. Validity is enforced for Remote Key Provisioning chains; Google tells verifiers to keep trusting the long-expired factory chains, which the revocation list covers instead. The attestation extension must be in the leaf and nowhere else. The leaf key must be EC P-256; it becomes the installation's signing key. - **KeyDescription.** Attestation and KeyMint security levels must be TrustedEnvironment or StrongBox. The challenge must equal SHA-256 of the enrollment transcript. Key properties (generated, EC, P-256, sign-only) and the root of trust come only from the hardware-enforced list. The bootloader must be locked, and the boot state Verified, or SelfSigned with a verified boot key on an operator-configured list. The application id (the one software-enforced value) must name exactly the configured package with a configured signing digest. - **Revocation.** A background task fetches Google's status list at startup and then on its cache lifetime (5 minutes to 1 day), with a 30 second timeout, an 8 MiB size cap, capped exponential backoff and jitter. Any REVOKED or SUSPENDED serial in the chain is rejected. With no list yet, or a list older than the grace period, enrollment fails closed. Enrollment reads an in-memory snapshot and never waits on a fetch. - **Rate limit.** Signed installation calls (delegate, revoke delegation, rotate endpoint, revoke installation, on both platforms) are limited per attested key. A call is counted only after its signature verifies, so forged requests cannot spend another installation's allowance. Counters are in memory per replica, bounded to 100,000 keys. - **Dependencies.** None added. `x509-parser` gains its `verify-aws` feature, which uses the `aws-lc-rs` the crate already depends on. ## Configuration All optional; Android stays off unless the ticket 2 settings are present. Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only, and passed through `deploy/charts/buzz-push-gateway` (disabled by default, schema-checked, covered by `tests/runtime-options.sh`). - `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS`: SHA-256 digests of verified boot keys accepted with a SelfSigned boot state. Empty by default, so a default gateway accepts stock Android only. - `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`: PEM bundle replacing the built-in roots, for a reviewed root rollout. In the chart, `android.attestationRoots.secretName` and `secretKey` mount it from a Secret; an empty name keeps the built-in roots. - `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS`: default 604800 (7 days), minimum 3600. - `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS` and `BUZZ_PUSH_SIGNED_CALL_MAX_CALLS`: defaults 60 and 30. ## Tests - `cargo test -p buzz-push-gateway` (all pass, 18 ignored), `cargo fmt --all --check`, `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings`, and the chart tests (`render.sh`, `release-contract.sh`). - Key Attestation chains are generated in the tests with a test root injected as the configured root, and run through the production verifier. One table rejects: unlocked bootloader, Unverified, Failed, SelfSigned with an unlisted key, boot key only in the software list (two variants), key properties only in the software list, extra key purposes, wrong curve, wrong package, two packages, wrong signing digest, wrong challenge, software-backed key (two variants), unknown root, forged leaf signature, expired provisioned intermediate, extension repeated above the leaf, non-P-256 leaf, a CA:FALSE certificate issuing the attestation key certificate. Another accepts Verified with any boot key, SelfSigned with a listed key, StrongBox and TrustedEnvironment, an expired factory intermediate, and a CA:FALSE, digitalSignature attestation key certificate. Revoked leaf, intermediate and root, a missing list and a stale list are rejected. The status list parser and refresh (backoff, cap, keeping the last list through failures) run against a scripted fake source; no test touches the network. - The per-key rate limit runs through the public router: forged calls do not spend the allowance, the fourth authentic call is refused whatever its kind, and another installation is unaffected. - Break check: disabling the locked-bootloader guard and the rate limit turned `rejected_attestations` and the rate limit test red; restored. ## Not here The app side (ticket 7) generates the Keystore key and sends the chain. The end to end run on a physical Android phone against a test gateway is also still to do. --------- Signed-off-by: Tom Brow <tomb@squareup.com> |
||
|
|
b769d5bee8 |
fix(relay): remove an owner's agents with the owner (#9575)
## What this changes When someone is removed from a community, their agents' live sessions already closed, but the agents kept their own membership rows and could reconnect as members. This PR removes those agents with their owner. - **Cascade.** `delete_member_with_acceptances` locks and deletes the target, then locks and deletes the `join_policy_acceptances` and `relay_members` rows of every member of the same community whose `users.agent_owner_pubkey` is the target and whose role is not `owner`. All of it runs in the same transaction, before the roster snapshot is written. Admin removal (kind 9031), self-leave and `buzz-admin remove-member` all go through it. An agent goes with its owner whatever its role, so an admin who removes a member also removes that member's admin-role agent. A direct 9031 target is still limited to `member` for admins. - **Owner recording.** The relay records a verified NIP-OA owner on every admitted sign-in, whatever the relay mode or `allow_nip_oa_auth`: on WebSocket AUTH, and for HTTP in the shared admission step after the denial checks, so `/events`, `/query`, `/count` and member POSTs all record it in one place. Before, it recorded only on open relays, so on closed relays the cascade and owner bans missed agents added directly. A request refused before recording writes nothing. Once the owner-signed tag is verified and the first admission checks pass, the relay may record the owner even if a final check, a cancellation or a token revocation then refuses the sign-in. The record still can't be changed. Over HTTP, a different stored owner refuses the request with 403 (invite creation keeps its `invite_owner_mismatch` code), and storage trouble refuses it with 503. A recorded owner can also manage the agent (channel management, channel-add policy, invites). - **CLI.** `buzz-admin remove-member` publishes clusterwide disconnects (`ConnControl::DisconnectPubkey`) for the target and its recorded agents on every run, including when the member is already gone. If publication fails or no relay server is subscribed, it exits 6 after the removal commits. Rerunning the same command retries the disconnect. - **Spec.** NIP-FI states the rule. ## Rollout limit An agent is covered only if its owner was recorded before the owner is removed. An agent whose owner was removed before the agent signed in with a NIP-OA tag after deploy, or an agent that never signs in with one, stays a member and needs a manual removal. The relay holds no proof of ownership for those agents, so there is nothing to backfill. Supersedes #6098 and #6078. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
4bf7d8a9b0 |
relay: refuse a reaction or deletion whose h names another channel (#9006)
## Summary A reaction, or a deletion that targets a message, belongs to the target message's channel. The relay works out that channel from the target and stores the event there. But every read and every live delivery matches the event's own channel (`h`) tags. So if a client puts a *different* channel in the `h` tag, the event is stored in one channel and only ever matches another: - No one ever receives it. - It still takes a slot when a client asks for "the latest N events" of the real channel. A catch-up can then return fewer events than exist while it looks complete, because the relay removes the stray event after it applies the limit. This is one of the known gaps in https://github.com/block/buzz-app/pull/2206. The relay now refuses such an event. The rule: | Event's `h` tags | Before | After | |---|---|---| | none | accepted | accepted | | include the target's channel | accepted | accepted | | only other channels | accepted, never delivered | refused | The refusal uses the same "target not found" text as the existing refusals for these kinds. So it tells the sender nothing about where the target is. No first-party client sends a mismatched `h`. buzz-app uses the target message's channel, and desktop, mobile and the SDK send no `h` on reactions. So no current client is affected. ### Details - The check covers kind:7 reactions and kind:5 deletions that name their target with an `e` tag. These are the two kinds whose channel comes from a target. A kind:5 that names an addressable event (`a` tag) is not affected. - The check runs only when the target is in a channel, so a reaction to a global event keeps any `h`. A tag must be the channel's UUID exactly as the relay writes it (lowercase, hyphenated), the same way `#h` filters match. - The check runs after the token, membership and archive checks. If it ran first, it would skip their database reads, and the response time could tell someone who cannot read a private channel whether a guessed `h` names the channel that holds a message. - Events already stored with a stray `h` are not changed. They can still take a slot under the limit. - NOSTR.md now says that an optional `#h` on these kinds must name the target's channel. It also says kind:5 takes its channel from its `#e` target (the old text said it used `#h`). ### Related issue None found. Follow-up to the known gaps listed in https://github.com/block/buzz-app/pull/2206. ### Testing - New `reaction_and_deletion_h_must_name_the_target_channel` test, as a member of the target's channel. A reaction whose `h` names only another channel is refused and not stored. A reaction with no `h`, or with both channels, is accepted, and so is a reaction with any `h` on a global event. A deletion of that reaction is refused and not stored with another channel's `h`. It is accepted with the target's `h` or with no `h`. A non-member's wrong guess still reaches the membership check. On a private channel, a right guess and a wrong guess both end at the same membership denial. - I removed the check, and the test failed. I also moved it back before the membership check, and the test failed. - On a local relay over WebSocket: the same refusals and acceptances, with the same messages, and a reaction to a global event keeps its `h`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Human test: Logan asked to take this to team review without a separate hand test (2026-11-17). buzz-review-completed Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> |
||
|
|
3876720c34 |
buzz-db: drop the five single-table guard triggers (BUZZ-318 phase 2) (#9398)
> [!NOTE] > **Rollout:** #8320 (app guards + catalog expand) is deployed, so the hold is lifted. With `autoMigrate=true`, `0096` runs at startup under a 5s lock timeout, and a failure stops startup. With `BUZZ_AUTO_MIGRATE=false`, deploy this binary first and then run `buzz-admin migrate`. Both orders are safe because the expand tolerates the objects being present or absent. ## What The required stop for `0096` is in `docs/trigger-retirement-deployment.md` (from #9622): a relay build at or after #8320 (`ec778bff`). A build older than that needs the tombstone trigger at startup and readiness. Migration `0096_drop_single_table_guards.sql` drops five triggers and their functions. #8320 moved each invariant into the application writers: | Trigger (table) | Function | |---|---| | `trg_channels_community_id_immutable` (channels) | `channels_community_id_immutable()` | | `communities_deletion_tombstone` (communities) | `enforce_community_tombstone()` | | `community_deletion_request_retargeting_guard` (community_deletion_requests) | `prevent_community_deletion_request_retargeting()` | | `community_deletion_approval_removal_guard` (community_deletion_approvals) | `prevent_community_deletion_approval_removal()` | | `community_deletion_manifest_keys_guard` (community_deletion_manifest_keys) | `protect_community_deletion_manifest_keys()` | Desired state (`schema/`) drops the five functions and four trigger files, plus the channels trigger declaration. The universal write fence on `channels` stays. Both boot paths stay catalog-equivalent: the pgschema-vs-migration parity check now also compares columns, key and FK shapes, and the remaining triggers on all five tables. Executor GUCs stay because `assert_community_write_allowed` still reads them through the universal write fence. `transition_community` and every phase-1 app guard are byte-identical to #8320. `scripts/reconcile-schema-after-pgschema.sql` has no entries for these objects. ## Tests - #8320's six `single_table_guard_*_without_trigger` PG tests no longer need to disable a trigger. They are now plain app-path tests with the same assertions. - New per-test regressions for the desired-template and migration boot paths assert that none of the ten objects exist, including disabled triggers and function overloads. - Deleted assertions that only exercised raw SQL against the triggers: retarget, rewrite and approval mutation, frozen-manifest rewrite, and tombstone DELETE. The app-path coverage for each remains. - The expand regression in #8320 migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, then validates again. - Rebased onto main `b568d9bf` after #8696 took `0095`; renumbered to `0096`. Blox gate at `7bda1f45`: fmt, clippy and buzz-db `--lib` pass; the PostgreSQL lane ran 219 tests, all pass. - Gate at `c8bc061c` (on main `051dd2d7`, then numbered `0095`, #9622 folded in): on Blox, `cargo fmt --check`, clippy and the buzz-db `--lib` tests pass. The PostgreSQL lane (migrations, single-table guards, floor retirement, fence and deletion) ran 208 tests: all pass. - Earlier gate at `0840ba49`: CI was green, and the Blox PostgreSQL lane passed 840 of 841 (the one failure, `media_reference_full_query_plans`, is a timing check that fails the same way on main on that host). - The rebase updates main's fence-retirement tests to expect the tombstone trigger gone. ## What got simpler Ten database behavior objects and nine desired-state files are gone (about 150 lines). Each rule has a single owner, the application writer. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
44cdd9feef |
push-gateway: lock expired installations before reaping (#9627)
## What The push gateway reaper deletes expired delegations and then expired installations in two statements. A delegation writer (`upsert_delegation`) that holds the installation lock can commit a new child between them. With the foreign key, the installation delete then fails, and the reap transaction rolls back. This PR locks the expired installations with `FOR UPDATE` first, as every authority mutation does. It then deletes their delegations and the installations by id. A writer that was holding the lock commits first, and the delete sees its child. A later writer finds the parent gone and is rejected. No schema change. This is the code half of #9610. The gateway image with this change must run everywhere before the delegation foreign key is dropped. ## Tests Blox at `20b66f8f`: fmt, clippy, and the push-gateway PostgreSQL tests (15/15) pass. - `reaper_deletes_delegation_committed_while_it_waits`: a writer holds the installation lock and inserts a child. The reaper starts and waits. The writer commits. The reaper deletes both rows. - `delegation_for_missing_installation_is_rejected`: `upsert_delegation` for an unknown installation returns `Rejected` and writes nothing. ## What got simpler The reaper now uses the same lock order as every other authority write. The child delete no longer needs a correlated subquery. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b568d9bf95 |
Retire the 0032 roster trigger in migration 0095 (#8696)
## Summary Migration 0095 drops the 0032 channel roster trigger (`trg_events_guard_channel_roster_snapshot`) and its function (`guard_channel_roster_snapshot()`). The trigger repeats a check that the relay already does in Rust. Every kind:39002 roster writer checks the roster against the channel's membership before it saves it (#8316). Since #8611, no relay requires the trigger at startup. This PR is the last step of the trigger retirement sequence in `docs/database.md`. This PR was split out of #8494 so the migration can roll out by itself. A relay from this PR does not change how it stores or publishes roles, and it has no new startup check. It serves correctly whether or not 0095 has run. #8494 stacks on this PR and must not merge until 0095 has run in every environment. ## Details - **Migration 0095.** `DROP TRIGGER` and `DROP FUNCTION`, with `lock_timeout = '1s'` and `statement_timeout = '5s'` as in 0049. `DROP TRIGGER` takes `ACCESS EXCLUSIVE` on each `events` partition in turn, so event reads and writes block while it runs. A timeout rolls it back with no change, and it can be retried. - **Desired-state schema.** `schema/functions/guard_channel_roster_snapshot.sql` is removed. This was the last trigger on `events`, so `schema/triggers/events.sql` and its include go too, as do the pre-attach trigger drops in `scripts/reconcile-schema-after-pgschema.sql`. - **Operator guide.** #8326 added `docs/trigger-retirement-deployment.md` for migrations 0089–0091. (0092 from #9365 and 0093 from #9560 drop nothing; 0094 from #9598 drops two plain SQL functions and has its own section there.) This PR adds 0095 to it: its row, the two ways an older relay fails, the migrate check, and the parent trigger a pgschema deployment must drop first. The Helm chart README names the required stop and points to that guide. - **Tests.** Tests that compared the trigger with the Rust check, or that disabled the trigger first, now test the Rust check alone. Tests that only exercised the trigger against a simulated pre-#8316 writer are removed. The 0075 invite upgrade test now migrates to 0075 exactly. ## Rollout **Required stop: the stop build in `docs/trigger-retirement-deployment.md`** (a relay build at or after `68785206`, the merge of #8325). That build contains #8316 (the app-side roster check) and #8611 (no startup trigger check), so it covers 0095 too. `relay-v0.3.0` contains #8316 and #8611 but not #8325, so it is no longer enough on its own: any build with 0095 also has 0089–0091. Without the stop, an untagged `main` build between 0032 and #8611 refuses to start once the trigger is gone, and a relay without #8316 can save stale kind:39002 snapshots (`docs/database.md` Rule 5). **Merge gate.** Every push to main publishes relay `:main` images, and the Helm chart defaults to `migrate.autoMigrate=true`. Do not merge this PR until the stop build or later runs on every serving and rollback target. That is the same gate #8326 had for 0089–0091. After that, either way works: - With `autoMigrate=true`, the first relay from this PR applies 0095 at startup. - With `autoMigrate=false`, run `buzz-admin migrate` when convenient. Relays from this PR serve with or without 0095. As with every new migration, an older binary with auto-migration on refuses a database that has 0095 (sqlx `VersionMissing`). A rollback past this release needs auto-migration off (`docs/database.md`). ## What happens next #8494 computes the `member`/`bot` label at read time. The 0032 trigger compares labels with the stored role exactly, so it would refuse those rosters. #8494 adds a startup check that refuses to serve while the trigger is installed. Merge it only after 0095 has run everywhere. ### Testing - `migration_0095_retires_the_roster_trigger`: on a database migrated through 0094, the trigger and function are installed. After the remaining migrations, both are gone, and a raw kind:39002 insert that does not match membership is accepted. It fails if 0095 does not drop them. - `embedded_migrator_contains_consolidated_initial_schema` pins 95 migrations and the 0095 statements, and checks that the desired-state schema no longer installs the function. - `migration_schema_desired_pgschema_reconcile_matches_populated_upgrade`: its fixture drops each retired parent trigger before pgschema runs (pgschema drops partition copies before the parent, which PostgreSQL refuses with 2BP01). It now drops the roster trigger too. - Locally at this head: `cargo check`, `cargo fmt --check`, and 245/245 buzz-db unit tests pass; 760/764 buzz-db Postgres tests pass. The four `event_follow_up_contract` tests fail the same way on `main` locally and pass in CI. CI runs clippy and the full PostgreSQL lane. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c01d3292a1 |
fix(db): hard-delete superseded relay-signed lists (#9586)
## Why
The relay republishes its own lists in full on every change:
- the NIP-43 membership list (kind 13534)
- the NIP-IA archived list (13535)
- NIP-29 group state (39000 metadata, 39001 admins, 39002 members)
Each write soft-deletes the previous head. No reader returns a
soft-deleted row, so each retired copy is dead weight in `events` and
its indexes. On the deployments we measured, these retired copies are
about 40–65% of monthly `events` growth. The NIP-33 path already
hard-deletes superseded NIP-RS read state and mesh status in the
replacing transaction. This PR applies the same rule to the relay-owned
lists.
## What
When a write supersedes a head of kind 13534, 13535, 39000, 39001, or
39002, it deletes the old head instead of soft-deleting it. The delete
runs in the same transaction, under the same scope and lock as before.
The change applies on the 3 paths the relay uses to write these kinds:
- `replace_addressable_event_under_lock` (13535, 39000, 39001, including
`buzz-admin` writes through `replace_addressable_event`). It gates on
the new `hard_deletes_superseded(kind)`. Other kinds on this path (0, 3,
10002, …) keep the soft delete.
- `LockedMemberSnapshot::replace_member_event` (39002).
- `write_nip43_membership_snapshot` (13534).
All 3 paths build their head read and supersede statement with one
function, `replacement_sql(in_channel, hard_delete)`, keyed by
`hard_deletes_superseded(kind)`.
Kind 13535 is now relay-only: ingest rejects a client-submitted 13535
with `restricted: relay-only kind`, as it already does for 13534. NIP-IA
defines 13535 as relay-signed, and every relay, desktop, CLI, and mobile
reader filters on the relay's pubkey. No client in this repository
publishes it.
The 39000–39002 paths already use `superseded_with_mentions_sql!`, so
the old head's mention rows are deleted with it, as before.
The gate checks the kind, not the signer, and every supersede is scoped
to the event's own pubkey. A client-signed 39000–39002 is routed to the
NIP-33 path, which keeps the soft delete. Channel deletion
(`soft_delete_discovery_events`) retires the live heads without a
replacement and still soft-deletes them.
This PR has no migration and no schema change.
## Why this is safe
- **Readers:** relay reads of these kinds filter on `deleted_at IS
NULL`, so a retired head was already invisible. One reader includes
soft-deleted rows: the admin event preview (`get_event_preview`). It
will now report a superseded roster id as absent instead of deleted. A
moderation report against an old version of a channel's metadata (for
example, a name it had before a rename) will show no target content. An
operator can no longer look up an old roster or membership list by id to
audit past membership. `docs/admin/README.md` now documents this for
`GET /api/admin/v1/events/{id}`.
- **Operator repair:** when `buzz-admin`'s group-state reconcile
overwrites a 39000–39002 head, the old row is gone, so an operator can
no longer restore it with `UPDATE … SET deleted_at = NULL`. The relay
rebuilds these lists from `channels` and `channel_members`, so no source
data is lost.
- **Replays:** while the coordinate has a live head, a replay of a
deleted head's id is still rejected, because its `created_at` does not
beat the live head's. With no live head (after channel deletion, for
example), the deleted row no longer makes the replay a duplicate. Only
the relay can submit these events: ingest requires the event's signer to
be the authenticated pubkey, 13534 is relay-only, and the relay's
writers sign a new event on every attempt. The existing tests for
soft-deleted replays seed their own rows and do not change.
- **13534 id uniqueness:** the writer still takes `max(created_at)` over
every stored list. The live head is always the newest, so the next
list's `created_at` still moves past every earlier one.
- **13535 strict stamps (NIP-IA, #9476):** each new archived list is
stamped past the live head, which the writer reads behind the
replacement lock. It never reads retired rows, so deleting them does not
change the next `created_at`.
- **Database objects:** no foreign key references `events`, and none of
these kinds is a push kind. The DELETE runs in the same admitted
community write transaction as the old UPDATE. The only trigger left on
`events` is the BEFORE INSERT kind 39002 roster guard
(`guard_channel_roster_snapshot`), and a DELETE does not fire it.
- **Rolling deploy (docs/database.md Rule 7):** old pods keep
soft-deleting and new pods delete. Both leave exactly one live head per
coordinate, under the same locks.
## Follow-up
Rows that are already soft-deleted stay. Rule 3 does not allow a
migration to delete them. A separate PR will add a
`scripts/maintenance/` repair script: bounded batches, the
community-deletion lock, and a validation query. An operator runs it
after this change is fully rolled out.
Not in this PR: the relay-signed NIP-DV DM visibility snapshot (kind
30622, `publish_dm_visibility_snapshot`) is written on the NIP-33 path
and still soft-deletes its superseded heads. We will measure its share
of `events` growth before we change it.
## QA focus
- **Each roster write keeps exactly one stored row.** Create a channel,
then add and remove members, change roles, and edit the metadata. For
each of 39000, 39001, and 39002, the channel must have exactly one
`events` row (live), not one live row plus retired ones. Do the same for
13534 (relay membership add, remove, and role change) and 13535 (`agents
archive` and unarchive).
- **Other kinds still soft-delete.** Replace a kind 0 profile or kind 3
contact list. The old row must stay, with `deleted_at` set.
- **Mention rows.** After a 39002 or 13535 replacement, `event_mentions`
has no rows for the deleted head's id.
- **Admin event preview.** Opening the id of a replaced roster now shows
the event as absent instead of deleted. Check that this is acceptable in
the admin UI, including a report filed against a channel's metadata
before a rename.
- **13535 `since` cache.** Archive and unarchive several times,
including at the same time. Each new list has a `created_at` later than
the one before. A mobile client that asks `since` its list's
`created_at` + 1 gets the newer list.
- **Client 13535 is rejected.** Publishing a kind 13535 signed by a user
key returns `restricted: relay-only kind`. Archive and unarchive (kinds
9035 and 9036) still work, and the relay still publishes its own 13535.
- **Channel deletion.** Deleting a channel still soft-deletes its live
39000–39002 heads. This path is unchanged.
- **Mixed-version rollout.** With an old and a new relay on one
database, each coordinate keeps exactly one live head. Rows that old
pods soft-deleted stay until the follow-up script runs.
- **Existing soft-deleted rows are not touched.** The disk-space gain
shows only in growth after deploy. The follow-up script cleans up the
backlog.
## Tests
- `only_relay_owned_lists_hard_delete_their_superseded_heads`: checks
the kind set, including the neighbours 13533, 13536, 38999, and 39003,
and negative kinds.
- `superseded_heads_drop_their_mention_rows` (Postgres) now expects the
old head to be gone for the 39002 member snapshot, 13535 (global), and
39000 (in a channel). A kind 3 contact list on the same addressable path
is the control: it must stay soft-deleted.
- `replacement_channel_predicate_is_an_index_condition` (Postgres) now
builds its statements with `replacement_sql`, the same function
production uses, for all 4 scope and retire-mode combinations. Before,
it checked hand-copied SQL. It checks that each `DELETE` seeks by
`channel_id` on every populated partition, as the `UPDATE` does.
- The 39002 and 13534 writers take their statements from
`replacement_sql` and `hard_deletes_superseded`, so the index-condition
test covers each statement production runs.
- `nip_ia_archived_list_is_relay_only` (buzz-core): 13535 is relay-only,
and the 9035 and 9036 requests are not.
- `test_client_submitted_nip_ia_archive_snapshots_are_rejected`
(buzz-test-client e2e, against a running relay): a client-signed 13535
is rejected with `restricted: relay-only kind` over both WebSocket and
HTTP. It shares a helper with the existing 13534 test. Against a relay
built without the 13535 gate, it fails at the WebSocket assertion. The
Relay E2E step in `.github/workflows/_ci-relay.yml` now selects it, next
to the 13534 test.
- `late_owner_link_closes_ownerless_agent_sockets_on_owner_revoke`
(buzz-relay, Postgres) copies selected tables into a private schema. The
13534 writer's supersede now also deletes the old list's
`event_mentions` rows, so the fixture copies `event_mentions` too.
- `every_membership_write_commits_its_list` (Postgres): after each
membership writer runs, the community stores exactly one kind 13534 row.
- `concurrent_archival_publishers_stamp_strictly_increasing_snapshots`
(buzz-relay, Postgres, from #9476) counted the 16 stored kind 13535
rows, superseded ones included. It now pins the head an hour ahead and
asserts that the coordinate stores exactly one row, at the pinned
`created_at` + 16 s. That holds only if each of the 16 publishers stored
exactly one snapshot, one second past the head it replaced. A
same-second replacement leaves the row short of + 16 s, and a publisher
that runs out of attempts still fails its `expect`.
- `a_publisher_that_read_before_an_edit_cannot_replace_it` (buzz-relay,
Postgres) counted retired kind 39000 rows to prove that each publisher
stores a new second. It now asserts that the coordinate stores exactly
one row, at the pinned `created_at` + 2 s. The mutation it guards
against (taking the live `created_at` before the lock) leaves the head
at + 1 s, so the test still catches it.
Commands run:
- `cargo clippy -p buzz-core -p buzz-db -p buzz-relay --all-targets --
-D warnings`
- `cargo test -p buzz-core --lib`
- `cargo nextest run -p buzz-relay --lib`
- `cargo test -p buzz-test-client --test e2e_relay -- --ignored` for the
13534 and 13535 rejection tests, against a local relay built from this
branch
- `cargo test -p buzz-db --lib`
- `cargo test -p buzz-db --test observability_source`
- `scripts/postgres-test-run.sh -p buzz-db -p buzz-relay --lib --tests`
(the CI PostgreSQL lane, run locally)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
8b6bc9beb5 |
Add community-scoped user and agent profile cleanup (#9580)
## Summary
Content, account and media cleanup leave profile records behind. Add
`buzz-admin user-deletions profile-batches` to preview or delete those
records in one community. Preview is the default; explicit `--delete`
applies bounded, retryable transactions.
Every run and retry discovers the human’s current direct agents in that
community. Ownership elsewhere cannot authorize deletion here. If Alice
owns an agent in A but Bob owns it in B, deleting Alice in B preserves
that agent. Each write batch locks and rechecks ownership. All profile
data is removed before identity rows, so an interrupted run resumes
without saved agent keys. The command no longer accepts
`--agent-pubkey`.
The handler removes profile/configuration events and projections,
rebuilds shared archive snapshots with valid signatures, and finally
removes identity rows. Repository announcements/state (30617/30618) and
name mappings remain intact without blocking identity removal; other
authored content still requires prior cleanup. Unresolved dependencies,
changed sources, untrusted signers or excessive plans stop deletion.
This includes historical `replaced-by` references in archive requests
and deltas, even after unarchive removes the current archive row. See
[operator instructions and verification steps](docs/profile-cleanup.md).
Writers must be stopped. Coordinator integration, online admission
fencing, media objects, client caches and final account-erasure
verification remain separate. The command always reports
`account_erasure_complete: false`.
### Related issue
Fixes #9576. Continues the standalone handler pattern from #9363
(content) and #9364 (account). This is an independent PR against main.
### Testing
The latest correction adds a PostgreSQL regression that runs content
cleanup followed by profile preview/delete/retry for human and agent
repository owners. It checks unchanged repository events, mentions, name
mappings and other-community data, and verifies ordinary content still
blocks profile deletion. The merge of main brings in `buzz-deletion
--lib` coverage in the CI unit lane and its fallback, covering the
preview-default parser test without duplicate runs. Account, content,
media and profile command dispatch are all preserved. The
archive-history documentation also now distinguishes planning errors
from printed blockers.
The latest main merge includes the shared dependency-policy correction
from #9609 and the content cleanup lock fix from #9615. On `54bd50299`,
PostgreSQL CI passed 1647 tests and failed 18 because content cleanup
still called the retired SQL lock-key function; this also blocked the
new content→profile regression. The merged upstream fix uses the
existing Rust-built key for both the cleanup lock and the test blocker.
Local test suites and hooks remain skipped at the owner’s request. CI
and review of the updated head are pending. The results below apply to
earlier revisions.
At `92aa9c216`, exercised the rebuilt `buzz-admin` against signed
archive/unarchive events stored in disposable PostgreSQL:
- For kinds 9035 and 8002, test a historical `replaced-by` reference to
the human and then to their owned agent after unarchive.
- Run `profile-batches --pubkey <human> --community <A> --relay-pubkey
<relay>` in preview and `--delete` modes. Both refuse the unresolved
reference; full table dumps remain unchanged.
- Keep that history only in community B. Cleanup in A succeeds,
preserves B, and selects zero work on retry.
- Delete the archive subject in B. Its history is removed while the
replacement identities remain intact.
All four scenarios passed. These are signed database fixtures exercised
through the real CLI; they do not claim live relay admission. The
correction also merges main and preserves content, media and profile
command dispatch.
The initial full database run passed 880/881 tests: the new request
fixture lost its required self-`p` tag during signing. Commit
`ff6689386` preserves that tag; all ten profile regressions now pass.
Further local checks and pre-push hooks were skipped at the owner’s
explicit request. The full corrected database suite has not been rerun;
GitHub CI will validate the new head. At `ff6689386`, the production
code matched the CLI-tested revision; the repository-retention
correction above is newer.
Previous ownership validation follows:
At `090d2a1cf`, exercised the rebuilt `buzz-admin` binary against a
disposable PostgreSQL fixture:
- Run `user-deletions profile-batches --pubkey <human> --community <A>`:
preview left table exports unchanged and selected four profile/identity
mutations.
- Repeat with `--delete --batch-size 2`: all four mutations committed;
retry selected zero work.
- Use the same human and agent keys in another community, with the agent
owned by someone else: only the human was selected, and the agent
remained intact.
This fixture uses placeholder profile signatures and validates
database/CLI behavior. It does not claim live signed-event admission.
The earlier live relay and Desktop results below cover the previous
revision.
Independent agent review covered the previous ownership correction. A
later review found the historical replacement-reference bug; the
historical-reference correction addresses that finding. Fresh review of
this revision is still required. Human command verification has not been
recorded; it is not claimed by the agent-run checks. Follow the local
verification steps in `docs/profile-cleanup.md`; preview must leave data
unchanged, deletion must preserve other-community records, and retry
must select zero work.
<details>
<summary>Historical validation at
|
||
|
|
051dd2d7aa |
fix(sdk): timestamp channel messages with millisecond offsets (#9548)
Kind-9 messages sent through the SDK or `buzz messages send` omit the `ms` tag, so clients break same-second ties by event ID. Capture one clock reading in the shared message builder and use it for both `created_at` and the canonical 0–999 millisecond offset, including direct and nested replies. Validation: both new regressions failed before the fix; the full CLI suite (691 tests) and SDK suite (335 tests) pass. The SDK test checks that the timestamp is pinned before signing; the CLI test captures and verifies signed HTTP submissions for roots and both reply depths. The built CLI also sent direct and nested replies through a managed signer to a live relay; readback confirmed one canonical `ms` tag and correct thread tags on both. Client ordering and human testing remain pending; keep this PR draft. To test manually, run `cargo build -p buzz-cli`, then send several kind-9 messages with `target/debug/buzz messages send --channel <channel> --content <text>` and direct/nested replies using `--reply-to <event-id>`. Inspect their raw events: each should carry exactly one canonical `ms` value, and a client that honors `ms` should display same-second sends in timestamp order. Related: #9541 updates mobile display ordering to consume these offsets. No duplicate producer fix found in the open PR/issue search. Repository-wide validation: `just ci` passed Rust/Tauri Clippy and formatting, then failed mobile analysis at `mobile/test/features/search/search_channels_journey_test.dart:933`: `_RenamingSession.subscribeWithStatus` omits the base method's `resumeSince` parameter. Mobile files are unchanged from the base commit. This unrelated failure remains outside this fix. The first push hook run failed the existing WebSocket throttle test `a_throttled_sign_in_reconnects_with_fresh_evidence` (connection reset during sign-in); a subsequent full CLI rerun and the complete normal push-hook retry passed without source changes. The test uses a kind-20001 event and does not call the changed builder. All required push hooks passed. Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> |
||
|
|
3bd121bc15 |
Check product_feedback's community in the writing transaction (#9608)
## Summary Third app-side step of retiring the database foreign keys (after #9399 and #9404). After this, every reference the drop migrations will remove is checked in application code. - **`product_feedback -> communities`:** `product_feedback::insert` now runs in a transaction. It locks the community row `FOR KEY SHARE` and returns `NotFound` when the row is missing. This is the same guarantee the foreign key gives. Any lifecycle state still qualifies. `docs/database.md` says provenance-only tables stay writable while their community is being deleted, and the purge clears their provenance. - **Reader tolerance:** `ProductFeedbackRecord.community_id` is now `Option<Uuid>`. The purge sets `community_id = NULL`, and `list` (used by `buzz-admin list-product-feedback`) failed to decode those rows. The JSON output shows `null` for them. - **One home for reference checks:** `require_workflow` and `require_workflow_run` move from `store/workflow.rs` into `store/reference_check.rs`. The workflow owner and channel checks now reuse `require_user` and `require_optional_channel`, so two duplicate helpers are gone. A new `require_community` joins them. - **Stale comments:** comments that justified behavior by the foreign keys now say what holds both before and after the drop. Touched: the purge order (`deletion.rs`), `command_executor.rs`'s `ensure_user`, the `set_agent_owner` doc, the NIP-43 snapshot lock note (`relay_members.rs`), `attach_scheduled_workflow_run`, and one workflow deletion test. ## Writers and readers checked (RPR #2) `product_feedback.community_id` writers: - `store/product_feedback.rs` `insert`: the only insert. It is now checked. - `store/deletion.rs` `purge_postgres`: sets the column to `NULL`. No check is needed. - `store/relay_admin_actions.rs` status update: does not touch `community_id`. Readers: - `product_feedback::list`: fixed to accept `NULL`. - `store/admin_moderation.rs` inbox queries: already `LEFT JOIN` and accept `NULL`. ## Tests All three tests drop `product_feedback -> communities` in the per-test database first, so a pass proves the application check and not the constraint. - `insert_rejects_missing_community_without_foreign_key`: a community that never existed gets `NotFound` and no row. A fenced community still accepts feedback. An active one accepts it, and a replay returns the same row. - `insert_key_share_locks_community_without_foreign_key`: an insert waits while another transaction holds the community `FOR UPDATE`, then proceeds. - `list_returns_rows_with_cleared_provenance`: a row with `community_id = NULL` is listed with `community_id: None`. ## Not in this PR - The foreign key drop migrations. They come after this PR is deployed (`docs/database.md` expand/contract). - Nothing in the database stops `DELETE FROM communities` on an active community once the community foreign keys are gone. The tombstone trigger rejects it only for inactive communities. Production never hard-deletes communities. This is decided with the drop migrations, since a trigger change conflicts with the no-new-triggers rule. ## What got simpler All in-transaction reference checks now live in one module. Two duplicate helpers were removed. `store/workflow.rs` loses about 80 lines. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
0a05330740 |
buzz-db: stop calling the dropped lock-key function in SQL (#9615)
## Summary Main's user content cleanup still calls the SQL function `community_deletion_lock_key`. Migration `0094` (#9598) drops it. On any database at `0094`, every user-deletion content batch fails with `42883 function community_deletion_lock_key(uuid) does not exist`. #9363 added this caller after #9396 moved the key to Rust. This PR binds the Rust-built key with `hashtextextended($1, 0)`, as every other caller does. - `content_batches/execute.rs`: the batch's exclusive advisory lock uses the Rust key. - `content_batches/safety_postgres_tests.rs`: the test blocker takes the same lock the same way. - `docs/trigger-retirement-deployment.md`: builds from #9363 up to this PR are not valid stops before `0094`. Rebased onto main `e894d75d`. The renumber and the `update_channel` test-call fixes this PR first carried are already on main through #9616, so they are gone from this PR. Deployed relays are unaffected: the deployed build predates #9363. ## Tests The 17 `user_deletion::content_batches` PostgreSQL tests fail on main at `0094` with the error above. This PR makes them pass. ## What got simpler One fewer SQL-side copy of the lock key. Every caller now builds the key in Rust. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>mobile-v1.5.0-rc.2 |
||
|
|
8fb0de8d53 |
Clean up account records and refresh member lists (#9364)
## Summary Add bounded, resumable cleanup for a user’s account records and their current direct agents in each selected community. Preview prints the proposed changes without writing; deletion uses the same selectors through the command and workflow handler. Each run and retry discovers agent ownership again. An agent owned by Alice in one community and Bob in another is cleaned only in Alice’s community. Ownership changes stop the current run, and ownership rows remain available for retries and later handlers. Membership removal rebuilds and signs the current channel lists and community roster in the same transaction as each removal. A failed roster write rolls back that membership removal. The command requires the existing relay signing key when channel or community memberships are present, including users with no channel memberships. Preview does not require a key. The relay, account cleanup and admin reconciliation share the kind 39001/39002 tag builders in `buzz-db`. They preserve the existing identity tags, roster order and role positions. Regular unit-test runs now include `buzz-deletion` through both nextest and the Cargo fallback. **Channel ownership policy:** deletion may remove the last channel owner, including when the human and their agents are all owners. The channel, messages and surviving members remain. A surviving admin can manage the channel and grant ownership. If no owner or admin remains, members can continue normal use, but management recovery requires operator intervention on request. Cleanup does not require a channel ownership handoff or assign a replacement owner. The separate community-owner restriction remains. The content handler now on main advances to account cleanup before the remaining agent stage. Content and account workflow progress goes to stderr so stdout remains one JSON inspection document. The direct account command retains NDJSON stdout. Nullable attribution updates use explicit table and SET clauses so the source-policy guard can inspect them. The handler covers credentials, memberships, read progress, supported personal events and their copies, feedback, and explicit global listener/database-role cleanup. It retains shared records and historical signed lists. Scope files select the human and communities; saved agent keys do not authorize deletion. This remains an offline operator feature: stop relay and external writers before deletion. It does not revoke already-connected sessions. Coordinator integration, remaining handlers and final erasure verification are separate; results always report `account_erasure_complete: false`. The real account workflow still stops at an unimplemented successor. ### Related issue Replaces the account scope of #9354 and #9355 with one focused PR. Those earlier PRs remain intact for reference. Agent cleanup belongs within the business handlers; this change does not integrate the historical standalone agent stage in #8959. ### Testing Exercised the real preview and delete commands in an isolated local relay/database with Alice disconnected and Bob’s desktop app open. Preview left the normalized database dump unchanged. Deletion checks covered all 101 tables and all 30 affected channels; 168 newly signed list events verified. Bob refreshed the member dialog and saw Bob, B1 and Carol, then successfully sent and read a message. A1’s membership in the community where Bob owns it remained intact. The live CLI and desktop evidence above predates the latest follow-up. Independent end-to-end checks at `d45759df2` also verified unchanged preview data, signed channel/community lists after deletion, signing-key preflight, and workflow JSON stdout. The shared-builder follow-up was source-reviewed and formatted; local builds, tests and commit/push hooks were skipped at the author’s request. Validation of the new revision and a repeat of the signed-list end-to-end check are pending. Human testing remains pending. For human verification, use an isolated database and its relay signing key. Preview a community-only member, confirm no writes, then delete and verify the current kind 13534 roster omits them. Run an approved account-stage fixture with `user-deletions run <id> --delete --next-step`; the entire stdout must parse as one JSON document, with batch progress on stderr. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Signed-off-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
a26eacde49 |
perf(mobile): save own thread interest once per unread catch-up (#9614)
iOS was killing the app with watchdog terminations (`0x8BADF00D`, "scene-update watchdog transgression" and "Failed to terminate gracefully") because the main thread spent 5 to 10 seconds in unread catch-up. Symbolicated reports from a 1.4.0-rc.1 user all point at the same stack: `UnreadCatchUp._catchUpUnreadEvents` → `ChannelsNotifier._writeThreadInterestStores` → `jsonEncode` / `SharedPreferences.setString`. For every self-authored event in a catch-up batch whose thread was new to the interest sets, the notifier re-encoded **both** whole root-id sets and wrote both to SharedPreferences. That is quadratic in the batch: a fresh sign-in, whose catch-up returns many of the user's own messages, ran thousands of growing encodes and platform-channel writes on the main thread. Now the catch-up adds the whole batch to the in-memory sets and saves once if anything changed. The live single-event path is unchanged (one write per new thread). ### Regressions None expected. The persisted keys, format and contents are identical; only the number of intermediate writes changes. The storage contract is unchanged: saves were and still are fire-and-forget `setString` calls, so neither version guarantees durability before a process kill. A kill before the save lands now loses the whole batch rather than a prefix of it; a later catch-up can re-add those threads only while they are still after the channel's read timestamp and within the catch-up window. ### Validation - **Writes per catch-up**, 50 own messages across 50 threads: 50 writes per key before, 1 after (new test). - Added test: `unread catch-up saves own thread interest once per batch` (channels_provider_thread_interest_cases.dart). It checks the saved sets and the write count; it fails on the old code. - Full mobile check and test suite pass. - Automated full-app run on an iOS simulator (PR head build, signed in to a real community): cold launch and unread catch-up saved both thread-interest sets; background and foreground; Activity rows and unread dots render; opened a thread and sent a reply, and the participation set grew by one (live path still saves). No errors in the app log. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
e894d75d26 |
buzz-db: fix main (renumber the function drop to 0094, update_channel test call) (#9616)
## Summary Main has two migrations numbered `0093`: - `0093_push_gateway_installation_platform.sql` from #9560 - `0093_drop_plain_sql_functions.sql` from #9598 The file names differ, so GitHub showed no conflict between the PRs. sqlx applies the first version-93 migration and then rejects the second as a changed migration 93. Every migrate run on main fails, including relay startup with auto-migration on. This PR moves #9598's migration to `0094`: - `git mv migrations/0093_drop_plain_sql_functions.sql migrations/0094_drop_plain_sql_functions.sql`. The SQL is unchanged. - `embedded_migrator_contains_consolidated_initial_schema` now expects 94 migrations, with the function drop at version 94. - The Postgres test is renamed to `migration_0094_drops_plain_sql_functions`. It finds the migration by description, so its logic is unchanged. - `docs/trigger-retirement-deployment.md` now names `0094`. #9560's `0093` keeps its number. It reached main first and may already be applied on deployments that auto-migrate. ## Second break on main: `update_channel` call sites Main's buzz-db lib tests also stopped compiling. #9581 added a `sender` argument to `update_channel`, and #8320's cross-community test (`deletion.rs`) landed in parallel with the old three-argument call. This PR passes the channel creator as the sender. The test only renames an open channel, so the private-to-open rule does not apply. ## Deployments No deployment has applied #9598's `0093`: no image built from main after #9598 has rolled out yet. A database that applied #9560's `0093` applies `0094` next. Do not promote any image built from `4e8f8365` (the #9598 merge) or later until this PR merges. ## What got simpler Nothing. This is a renumber and a test call fix only. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f158fdd9a1 |
feat(relay): name the agent whose add policy refuses a DM (#9601)
## Problem When an agent's add policy refuses a DM open or add (from #9125), the refusal says only that an agent refused. The person can't tell which agent blocked it, so they don't know whose owner to ask. ## Change The DM refusal now ends with `(agent <hex pubkey>)` for the first agent refused, in the order the request named them. For example: `forbidden: policy:owner_only — only the agent owner can add this agent (agent 3f9a…)` The prefix is unchanged, so existing clients that match on `policy:owner_only` or `policy:nobody` keep working. Desktop and mobile follow-ups will show the agent's name. ## Tests - `adding_an_agent_follows_its_add_policy` asserts the full refusal including the agent. - `opening_with_several_agents_follows_their_add_policy` adds a second refusing agent and checks the first one named is reported. - DM Postgres tests: 297/297 passed. Clippy is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4e8f836576 |
buzz-db: drop the community_deletion_lock_key and profile_name_fields functions (contract) (#9598)
## Summary Phase 2 of retiring the two remaining plain SQL functions. Phase 1 moved their work into the relay: - #9396 builds the community deletion lock key in Rust (`deletion::community_deletion_lock_key`, locked with `hashtextextended($1, 0)`). - #9397 reads profile names with inline SQL (`PROFILE_NAME_FIELDS` in `buzz-search`). No relay at or after #9397's merge (`279a31da`) calls either function. This PR drops them: - **Migration 0093** runs `DROP FUNCTION community_deletion_lock_key(UUID)` and `DROP FUNCTION profile_name_fields(TEXT)` under a 5s `lock_timeout`, with no `IF EXISTS` and no `CASCADE`. If anything still depends on a function, the migration fails instead. Migrations 0029 and 0064 stay frozen. No database function calls either one any more: 0090 dropped the fence functions, which were the only SQL callers of the lock key. - **Desired state:** removes both `schema/functions/` files and their `schema.sql` includes. Both boot paths stay catalog-equivalent (`admin_schema_parity_between_desired_state_and_migrations`). - **Tests:** - New `migration_0093_drops_plain_sql_functions`. It migrates to 0092, checks that both functions exist and that serving and deletion catalog validation pass, then runs 0093 and checks that both functions are gone and that validation still passes. This covers new code on either side of the drop. - The migration listing test pins 0093's statements and that it has no `CASCADE`. - `desired_state_catalog_has_no_universal_fence_and_still_boots` now asserts that both functions are absent. - Replaces the Rust-vs-SQL lock key parity test with `community_deletion_lock_key_bytes_are_fixed`, a unit test that maps fixed UUIDs (nil, max, and one with hex letters) to their exact keys. Older replicas and the repair-script key in `docs/database.md` build the same string, so a changed prefix or UUID format must fail a test. - Removes two relay test-schema wrappers (`bridge.rs`, `ingest.rs`) that forwarded `community_deletion_lock_key` to `public`. Writers no longer call it, and the wrapper's `CREATE FUNCTION` would fail once the function is gone. - **Docs:** `docs/trigger-retirement-deployment.md` gets a `0093` section with the required stop. ## Deploy gate **Required stop:** any relay build at or after `279a31da` (#9397's merge, which follows #9396). `relay-v0.3.0` does not contain it. A relay older than that which still serves after 0093 fails every write and deletion that takes the community deletion lock, with `42883 community_deletion_lock_key(uuid) does not exist`, and its profile name search fails with `42883 profile_name_fields(text) does not exist`. 0093 takes no table locks and needs no cleanup. Migration number: #8696 and #9398 also propose `0093`. Whichever lands second renumbers. ## Review-Proven Rules - **RPR #2 (every path):** I checked every reference on `main` and at the stop build `279a31da`. At both, only test code reads either function: no boot, readiness, catalog or runtime query depends on them. Serving and deletion catalog validation pass before and after 0093, in the new test. - **RPR #3 (falsifiable):** removing the `profile_name_fields` drop from 0093 turns `migration_0093_drops_plain_sql_functions` red. - **RPR #3 (lock key bytes):** a changed prefix, `.simple()` UUID formatting, or uppercase formatting each turns `community_deletion_lock_key_bytes_are_fixed` red. ## What got simpler Two database functions, their desired-state files, a cross-language parity test and two test-only SQL wrappers are gone. After this PR, the only functions left in `schema/functions/` are trigger functions. ## Validation Blox gate at `95ac71c8`: - `cargo fmt --all --check`, and `cargo clippy -p buzz-db -p buzz-relay --all-targets -D warnings`. - `buzz-db --lib` unit tests: 216/216, including the migration listing test. - `buzz-db` Postgres tests (`migration::`, `deletion::`, `nip_fi_binding::` postgres_tests): 130/130. These include `migration_0093_drops_plain_sql_functions`, `admin_schema_parity_between_desired_state_and_migrations` and `deletion_surface_parity_between_migration_0029_and_schema_sql`. - `buzz-search` `profile_names*` Postgres tests: 4/4, on a fully migrated database where `profile_name_fields` no longer exists. - The two relay tests whose test-schema wrapper this PR removes: 2/2. - Must-fail check: with the `profile_name_fields` drop removed from 0093, `migration_0093_drops_plain_sql_functions` fails. Second Blox gate at `e1b5513a` (the lock key vector test): - `cargo fmt --all --check`, and `cargo clippy -p buzz-db --all-targets -D warnings`. - `buzz-db --lib` unit tests: 217/217. - Must-fail checks: a changed prefix, `.simple()` and uppercase UUID formatting each fail `community_deletion_lock_key_bytes_are_fixed`. The first gate run found that `deletion_surface_parity_between_migration_0029_and_schema_sql` still expected `community_deletion_lock_key` in `schema.sql`. The second commit fixes that. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
66b463fb2f |
fix(deps): clear chrono, humantime and zip advisories from the dependency policy (#9609)
## Summary main's `Security` check (`cargo-deny check`) fails on six new advisories: - RUSTSEC-2026-0545, 0546, 0547, 0548: zip 8.6.0 (fix in zip >= 9.0.5). - RUSTSEC-2026-0543: chrono is unmaintained. - RUSTSEC-2026-0542: humantime is unmaintained (it wraps chrono). This PR adds ignore entries with reasons. It changes only `deny.toml`. ## Why ignore and not upgrade **zip.** zip 8 reaches the graph only through the examples-only `buzz-mesh-smoke` crate, via mesh-llm v0.76.2. mesh-llm builds zip with only the `deflate` feature. It reads archives through `ZipArchive` and copies entries by hand. It never calls `extract`, never decrypts AES entries (`aes-crypto` is off), never enables `legacy-zip`, and never uses `ZipStreamReader`. None of the affected code paths run. mesh-llm v0.79.0 ships zip 9.0.5. But that release removes the `client` feature of `mesh-llm-sdk`, which `buzz-mesh-smoke` and desktop use. A bump needs an SDK migration in both places. That is out of scope for a red-main fix. The new IDs join the existing zip block. Its note said the fix was in "unreleased mesh-llm#2471". That is stale, so the note now names the release and the migration it needs. **chrono / humantime.** Both are unmaintained, not vulnerable. Neither has a maintained release. chrono is a direct workspace dependency of most crates. humantime comes only through `buzz-mesh-smoke` → mesh-llm → hf-xet → xet-runtime. Removing them needs a migration to `time` or `jiff`. ## What got simpler Nothing could. The new ignores are the smallest change that makes the check pass. Identified debt: - The mesh-llm SDK migration to v0.79+ would delete all eight zip ignores. - A chrono → `time`/`jiff` migration would delete both unmaintained ignores. ## Test plan - [x] `cargo-deny check` at this tree: `advisories ok, bans ok, licenses ok, sources ok` (exit 0). - [x] `git diff --check` clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>mobile-v1.5.0-rc.1 |
||
|
|
026b203c64 |
docs: define mobile diagnostic reporting (#9600)
## Summary Records the vocabulary, the two hard-to-reverse decisions and the spec for diagnostic reporting in the mobile app, before any code is written. Nothing here changes behavior. - `CONTEXT.md`: two new terms. **Diagnostic reporting** is sending crash, error and performance data from a mobile installation to a reporting destination. A **reporting destination** is where a build sends it, chosen at build time by whoever distributes the build. - [ADR 0007](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0007-diagnostic-reporting-follows-the-destination.md): a build reports if, and only if, it was given a reporting destination, whatever kind of build it is. It also lists what a report may and may never carry. - [ADR 0008](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0008-sentry-for-mobile-diagnostic-reporting.md): the app reports through the Sentry Flutter SDK, with the comparison against Datadog and Bugsnag. - [`docs/mobile-diagnostic-reporting.md`](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/mobile-diagnostic-reporting.md): the spec for step one. It covers crashes, uncaught errors, error reports for unexpected protocol and decoding failures, and networking measurements by backend and endpoint, all through one reporting module. It sits beside the existing mobile push suppression spec. The term avoids "telemetry" because the repository already uses that word for agent session streams and relay rollout signals. ### Related issue N/A. The Swift Package Manager move that ADR 0008 depends on is #9597. ### Regressions Documentation only. No code, configuration or build changes. ### Validation Checked that every link in the four files resolves within the branch, and that the new glossary anchors match the links that point to them. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> |
||
|
|
148585c804 |
build(mobile): link iOS plugins through Swift Package Manager (#9597)
## Summary The iOS app stops opting out of Flutter's Swift Package Manager integration. The 19 iOS plugins that ship a Swift package are now linked through it. The three that don't (`google_mlkit_commons`, `google_mlkit_selfie_segmentation` and `open_filex`) keep installing through CocoaPods, which Flutter supports side by side. Why now: - CocoaPods is winding down: its spec repo [becomes read-only on December 2, 2026](https://blog.cocoapods.org/CocoaPods-Specs-Repo/), and plugin releases have started to ship as Swift packages only. Staying opted out pins those plugins at their last CocoaPods release. - The opt-out dates from the Flutter 3.47 upgrade (#8419), which kept the existing CocoaPods integration. With it removed, the app builds and runs as before. What is in the diff: - `pubspec.yaml`: the opt-out is removed. - `project.pbxproj` and `Runner.xcscheme`: the edits Flutter's own tool makes on the first build with the integration on (a local reference to its generated plugin package, and a scheme pre-action that prepares the Flutter framework). They are committed so a build does not dirty the tree. - `Podfile.lock`: only the three CocoaPods plugins and their dependencies remain. No Dart code, plugin version or remote Swift package changes. All 19 packages resolve to local paths in the pub cache, so `Package.resolved` is untouched and builds fetch nothing new. ### Related issue N/A. No existing issue or PR for this was found. ### Regressions - **App behavior:** the same plugin code at the same versions. The 19 plugins are linked statically into the app binary instead of embedded as dynamic frameworks, which leaves fewer libraries to load at launch and a slightly smaller app (numbers below). One resource bundle is lost; see the second accepted tradeoff. - **Extensions:** the notification service extension links no plugins, so it is unchanged. - **Build and release:** CocoaPods is still required for the three remaining plugins, so the Podfile, its post-install steps and the release tooling are unchanged. The first build after this change spends about 17 extra seconds adding the integration. - **Accepted tradeoff, build warning:** Flutter now prints a warning naming the three plugins without Swift packages. It goes away when those plugins add support or are replaced. - **Accepted tradeoff, one privacy manifest dropped:** the app no longer bundles `app_badge_plus`'s privacy manifest, and Xcode prints `Invalid Resource 'Resources': File not found` for it. Version 1.2.10's Swift package looks for `Resources` under its source directory, but the manifest sits at the package root, so the Swift package bundles nothing where the podspec bundled it. This is harmless: that manifest declares only UserDefaults access, and the plugin's single source file never touches UserDefaults. The other 16 plugin privacy manifests are still in the release app. Fixing it means a plugin bump, which is left out of this PR. - **Android:** unaffected. ### Validation Unsigned release build, this branch against unmodified `main`: | | `main` | This branch | | --- | --- | --- | | App size | 87.0 MB | 85.6 MB | | Embedded frameworks | 31 | 12 | Focused existing validation: the three iOS steps CI runs (simulator debug build, the 116 native `RunnerTests`, and the unsigned release build) pass locally. Full-app run on an iOS 27 simulator (iPhone 17 Pro), driven by an agent, with the debug build from this branch installed over an existing signed-in install: - The app stayed signed in and loaded its channel list and message history (keychain, preferences and local storage plugins). - Photo library picker, attaching a photo, and sending a video, which uploaded and played back. - Image viewer, the share sheet, and saving an image to Photos. - The file picker, and the camera and microphone permission prompts. - A link in a message opened in the browser, and a `buzz://` deep link reached the app. Two failures showed up and both reproduce identically on unmodified `main` on the same simulator, so neither comes from this change: a recorded voice note is empty because the host Mac has no microphone, and saving an image adds it to Photos but then reports "Could not save image". Limits: no physical device run. Camera capture, QR scanning, selfie segmentation and biometric prompts cannot be exercised on a simulator. Voice note playback was not exercised. Human testing is waived for this PR under the author's standing policy for mobile changes; the agent-driven run above stands in for it. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> |
||
|
|
6b4a398829 |
feat(push-gateway): enroll Android installations and send FCM wakes (#9560)
## What and why Ticket 2 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now enrolls Android installations and wakes them through FCM, next to the existing iOS path. Builds on [#9557](https://github.com/block/buzz/pull/9557) (platform-neutral `/v1/deliveries` route), now merged. - **Platform.** The enrollment request has no platform field. The gateway derives it from which attestation is present (App Attest object or Android attestation chain) and records it in a new `push_gateway_installations.platform` column (`ios` or `android`). It lives only in gateway state; the relay never sees it. - **Android enrollment transcript.** Key Attestation fixes the challenge at key generation, so the client signs nothing at enrollment and sends no `key_id`. The attestation challenge must equal SHA-256 of a canonical JSON transcript under domain `buzz.push.enroll.android.v1` with `v`, `audience`, `challenge_id`, `challenge`, `endpoint`, `endpoint_epoch` and `expires_at`. The gateway derives the key id as SHA-256 of the attested 65-byte uncompressed P-256 key. A request whose `key_id` presence doesn't match its platform gets 400. The iOS transcript (`buzz.push.enroll.v1`) is unchanged. - **Signed calls.** iOS keeps App Attest assertions. After enrollment, an Android installation signs every call (delegate, revoke delegation, rotate endpoint, revoke installation) with its attested Keystore key: ECDSA P-256, DER, over the same transcript bytes iOS signs. High-S signatures are accepted since Keystore does not normalize. There is no counter; the single-use challenge inside the transcript is the replay protection. - **FCM sender.** HTTP v1, high priority, data-only, compiled-in payload (no relay-supplied bytes), one constant collapse key, TTL from the delivery expiry. OAuth access tokens come from the service account key (RS256 JWT bearer). Outcomes map onto the existing delivery outcome classes and metrics (`push_gateway_fcm_*`). - **Token refresh.** A cached token keeps serving until it expires. Once it is due for refresh, one background task fetches a new one, so a wake never waits on a refresh while a valid token exists. A failed fetch keeps the current token and backs off 5 s before the next attempt. Only a cold cache (no unexpired token) makes a wake wait on the token request, single-flighted. A 401 discards the cached token only if it is still the one FCM refused, so a late 401 can't drop a newer token. - **Retries.** 429 and `QUOTA_EXCEEDED` retry after at least 60 s (FCM's hint if longer). 500, 502, 503 and 504 retry. - **Attestation seam.** Android Key Attestation verification sits behind a trait. Tests use a test-only verifier compiled under `cfg(test)`, so production configuration cannot select it. The production verifier fails closed: a gateway configured for Android starts but rejects every Android enrollment until ticket 3. - **Migration.** Expand-only `ADD COLUMN platform TEXT NOT NULL DEFAULT 'ios' CHECK (...)`: the deployed gateway's inserts stay valid and existing rows become iOS. `SET LOCAL lock_timeout` (5 s) and `statement_timeout` (30 s) bound the table lock wait and the CHECK validation scan. No triggers, functions, foreign keys or backfills. Mirrored as gateway `0007` and relay `0093` plus `schema/tables/public`, per docs/database.md. ## Configuration All four are optional and must be supplied together (a partial set fails startup). Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only. - `BUZZ_PUSH_ANDROID_PACKAGE_NAME` - `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS` - `BUZZ_PUSH_FCM_PROJECT_ID` - `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` ## Tests - `cargo test -p buzz-push-gateway` (92 passed, 18 ignored; 94 passed with `personal-dev-app-attest`; iOS rows unchanged), `cargo fmt --check`, `cargo clippy -p buzz-push-gateway -p buzz-db --all-targets -- -D warnings`. - New HTTP tests with a fake FCM sender: Android enroll, delegate, deliver, rotate endpoint and revoke; signed-call rows for wrong key, altered transcript and reused challenge; platform derivation and bad attestations. - Postgres (ignored, run locally): gateway migration test (existing and old-gateway inserts become `ios`, bad value rejected); relay `admin_schema_parity_between_desired_state_and_migrations` now covers `push_gateway_installations` columns, indexes and constraints; the `runtime::migration::postgres_tests` set passes single-threaded. - Break check: making signature verification always succeed turned two tests red (the signed-call rejection rows and the signature unit test); restored. - Token cache tests against a local fake token endpoint with a controlled clock: a due refresh keeps serving the valid token even when it fails; a late 401 does not discard a refreshed token; a queued background refresh honors a foreground failure's backoff. The FCM response table covers 429 with and without an error body, and 502/504 HTML pages. - Android enrollment rows: `key_id` present on Android (400), wrong transcript binding, a 65-byte non-point key, an over-long chain, and exact replay. - Break checks for every new guard (no background refresh, blocking while due, failure dropping the token, unconditional 401 clear, no quota floor, no 502/504 retry, the queued-refresh backoff check, Android requiring `key_id`, skipping the P-256 point check): each turned at least one test red; restored. ## Not here (ticket 3) Real Key Attestation verification (Google roots, revocation list, boot state, boot-key list, app identity). Per-key rate limiting is also left for ticket 3, since it did not fall out of this change. The Helm chart does not pass the Android settings yet. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
ff652ed06c |
perf(mobile): cache and animate custom emoji in the iOS picker (#9479)
The iOS emoji picker's custom emoji downloaded again every time the
picker opened, and animated emoji showed only their first frame.
Now each custom emoji downloads once per install and plays its
animation:
- The native picker gets image bytes from Flutter through the same path
as the rest of the app's images: the in-memory custom emoji cache, then
the persistent media disk cache, then one download through the shared
media HTTP client. Relay media is cached as immutable.
- Swift decodes every frame (no Swift-side cache) and shows the image in
a `UIImageView`, since SwiftUI `Image` draws only the first frame of an
animated `UIImage`. With Reduce Motion on, it shows the first frame,
following the setting live.
- At most four picker downloads run at once, and an emoji scrolled off
screen before its turn never starts. Emoji already saved on disk skip
the queue, so reopening a large set stays instant.
- A picker load joins any download of the same image already in flight
elsewhere in the app. A saved copy that fails to decode is evicted and
downloaded again, and only bytes that decoded are kept in memory.
- Swift decodes at most four emoji at once, including ones from cached
bytes. An emoji whose cell scrolls away gives up its place and stops
decoding between frames, and a cell that leaves the screen keeps only
its first frame.
- Each animation frame keeps its own delay. UIKit spaces animated frames
evenly, so a frame repeats for its share of the loop, and a GIF that
holds its last frame for 3 s still does.
### Why it refetched
The native picker loaded images itself with `URLSession.shared` and an
`NSCache` keyed on the whole request. Every request carried a freshly
signed media auth header, so the key never matched and nothing was
cached on disk.
### Validation
Relay media downloads for the 48 custom emoji matching "nod" (local
relay, iPhone 17 Pro simulator):
| Step | main | this PR |
| --- | --- | --- |
| First open | 48 | 48 |
| Leave and re-enter the channel, reopen | 48 | 0 |
| Relaunch the app, reopen | 48 | 0 |
| Reinstall the app, reopen | not measured | 0 |
Before (main): every reopen downloads again, and animated emoji are
still.
https://github.com/user-attachments/assets/7a43dd6a-61e0-495d-abed-6c11f7d4f965
After (this PR): reopening shows cached emoji immediately, and animated
emoji play.
https://github.com/user-attachments/assets/bf45a5c0-77ef-4501-8843-6f42e15de389
Automated app run: signed in to a local relay, opened a channel,
long-pressed a message, opened the full picker, searched, closed, left
and re-entered the channel, reopened, relaunched and reopened. Repeated
on the final head (
|
||
|
|
1059d81fc2 |
fix(ios): end each bold or strikethrough run at its first closing marker (#9559)
Bold and strikethrough runs in iOS push notification bodies now end at their first closing marker, so a message with two bold runs on one line shows both without their markers. Before, the run's optional group was greedy and stretched to the last marker on the line: | Message | Before | After | | --- | --- | --- | | `option **A** or option **B**` | `option A** or option **B` | `option A or option B` | | `~~x~~ and ~~y~~` | `x~~ and ~~y` | `x and y` | | `**😀** and **b**` | `😀** and **b` | `😀 and b` | The fix makes that group lazy (`(?:.*?\S)??`). Found while reviewing the Dart port in [#9556 Dart notification body](https://github.com/block/buzz/pull/9556), which must match these fixtures. That PR takes the same pattern once this one lands. ### Validation - Added tests: three shared rows in `test-fixtures/notification-body.json`, one per row above. All three fail with the old pattern. - All 70 BuzzPushKit tests pass on macOS, including the other 36 fixture rows, which are unchanged. ### Regressions None expected. The pattern still needs non-space characters right inside both markers and still stays on one line. It now stops at the first closing marker where before it reached for the last one. The output changes only where a one-character run is followed by the same marker later on the line, for example `**a** costs 2**3`, which was `a** costs 23` and is now `a costs 2**3`. Worst-case time for unclosed markers is unchanged (measured during review of the Dart port). Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
50cfc54337 |
Apply the private-to-open rule in update_channel too (#9581)
## Summary - Follow-up to https://github.com/block/buzz/pull/9307, which made the relay refuse to open a private channel that has, or once had, any member other than the sender and the sender's own agents. That rule lived only in the channel metadata edit path (kind:9002). The store's other channel-settings function, `update_channel`, could still open such a channel. - Now both paths apply the same rule, because it runs in the one function that writes channel settings for both. `update_channel` takes the authenticated sender so it can decide the rule. Today only tests call `update_channel`, so nothing user-visible changes; the gap is closed before any real caller arrives. - The user-deletion executor doc now says what the rule needs from a purge: if a purge keeps any of a user's messages in a channel, it must also keep that user's membership row there, marked removed. The relay finds former members only through those rows, so dropping the row would let the channel be opened and its history, those messages included, be made public. ## Details - The check moved out of `apply_channel_metadata_event` into `update_channel_on`, which both paths call. It still runs under the membership lock that a visibility change takes, so members cannot be added between the check and the commit. - One ordering change: a single kind:9002 that opens a private channel with other members, archives it and sets `auto_join` to true now gets the `auto_join` refusal instead of the private-to-open one, because the `auto_join` check now runs first. Both refuse, and nothing is stored either way. - This PR also carries doc-comment wording that was reviewed on https://github.com/block/buzz/pull/9307 but not merged with it: the comments now give the reason, that opening publishes the existing history, so removed members count. - Every call site of `update_channel` is a test, and each now passes the channel owner as sender. ### Related issue Follow-up to https://github.com/block/buzz/pull/9307 (review notes on its store gap and on purge). ### Testing - New Postgres test `update_channel_refuses_opening_a_private_channel_with_other_members`: opening fails for both the owner and the other member as sender, while the other member is current and after they are removed, and the channel stays private. A channel that holds only the owner opens. - The existing kind:9002 test `private_to_open_needs_no_other_members` still passes. Both tests fail when the check is removed. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a8f55e637a |
Add real content cleanup for users and agents (#9363)
## Summary Add one shared content-cleanup handler for a user and their agents in a specified community. Preview is the default; deletion commits bounded batches and preserves other people's replies and reactions. Agent selection requires ownership by this user in the target community. Ownership elsewhere is insufficient. The start record reports missing or conflicting ownership, and every batch rechecks the selected agents before deleting anything. ### Reply preservation and live writes Keep erased placeholders for messages needed by surviving reply chains or reactions. Plain links and quotes may point to a deleted message; their signed source messages stay unchanged. Nested reply ancestry uses the existing parent/root indexes. No new permanent index or schema migration is added. Replies without thread metadata use the existing tags GIN index to search for each selected message ID in lowercase and uppercase. The shared marker parser checks which matches are actual replies. Mixed-case references without thread metadata may be missed; metadata-backed replies use binary IDs and remain covered. Planning and hard-delete rechecks each run the probes in one SQL statement with a one-second timeout and a 10,000-match limit. A reply matching several probes counts several times. Exceeding either bound aborts cleanup. This avoids the broad search through unrelated replies; production-scale performance has not been measured. Each batch revalidates its work under the community lock. Transaction-local timeouts apply before locking, including after reconnect. Planned output is written before locking and receipts after commit. A changed row, owner, or surviving reply aborts the batch; retry replans remaining work. Normal reply insertion retains the added indexed parent-existence check. This changes the live write path and prevents saving a reply whose parent disappeared while the writer waited. Erased messages appear unavailable in moderation lookups instead of carrying an empty author key. ### Included content Supported authored events and owned reaction, subscription and notification records are included. Signer-owned personas (30175), team definitions/catalogs (30176/30178), emoji sets/entries (30030/30180), and project groupings (30621) include shared publications and stored revisions. Deleting a project grouping leaves member repositories, their announcements/state and name mappings intact. ### Testing Local runtime tests and hooks are skipped at the owner's request. Source review, Rust formatting and diff checks were completed. The updated revision requires CI validation; earlier test runs and index benchmarks do not validate this replacement. Regression cases cover ownership conflicts/transfers, missing thread records, nested ancestry, plain links, late replies, lookup limits, reconnects, blocked output, and unavailable moderation targets. No new manual relay or UI test was run for this revision. Account blocking remains unfinished; these changes do not establish complete online account erasure. ### Scope and compatibility **Deferred to a separate follow-up PR to keep this PR smaller:** the following work will extend **the same content cleanup handler** (`purge_content` / `content-batches`), rather than introduce another handler: - Workflow database definitions, runs, traces, approvals, schedules and copied inputs; some source events are already covered here. - Canvas revision events and current canvas text. - Artifact events, revision records and current heads. - Channel topics and purposes. - Gift-wrapped DMs and additional huddle history that require different attribution rules. - Git issues, PRs, patches, comments/status and required repository metadata, subject to preservation rules. Repositories themselves stay. - Remaining stored workflow, delivery and projection copies outside this PR's current coverage. These categories remain unfinished. Deferring them is not a permanent retention decision or a claim of complete content erasure. The follow-up must settle shared-document and mixed-owner workflow behavior and test surviving content. Profiles and managed-agent identity definitions belong to profile cleanup. Memberships, personal preferences and access belong to account cleanup. Media cleanup was implemented separately in #9365 and is now on main. Deletion requests, approvals, progress/history and replay protection stay. The workflow orders account gating, global media cleanup, then per-community content cleanup. Real requests still stop at the unfinished account gate; demos simulate every stage without deletion. Other unfinished real workflow stages fail explicitly. Existing demo requests saved with `purge_db` must be recreated for `purge_content`. Bulk client notifications remain separate work. Open views may retain cached content and counts until refresh. The existing missing reply-count button after refresh and ordinary UI access when the root is deleted are outside this PR. Replaces the content portion of #9355 and #9332. Related prior handler: #8698. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
21802f019e |
Keep transparency in mobile avatar photo crops (#9319)
## Summary Choosing a transparent PNG as a profile photo on mobile produced an avatar with a solid background on every client. The crop step always re-encoded to JPEG ([`profile_avatar_crop_page.dart#L507`]( |
||
|
|
6f1eabe4e8 |
fix(mobile): read presence for a person shown again while still covered (#9595)
## Context Follow-up to [#9480 stop following off-screen presence](https://github.com/block/buzz/pull/9480), from [Wes's review comment](https://github.com/block/buzz/pull/9480#discussion_r4591994023). When a person is retired, presence narrows the live subscription to the people still shown. If that narrowing fails, the old wide stream stays live and still covers the retired person. If that person is then shown again, the tracked set matches the live stream's keys, so `_subscribe` returned early without reading their snapshot. Their dot stayed empty until a live event or the next 60 second poll. The same gap happened when a person was shown again before the retirement's resubscribe ran. `_subscribe` now schedules the pending snapshot read before returning in that case, so a person shown again gets their current presence right away. ## Validation - New test: `a key shown again while a failed narrowing left it covered is read`. It failed before the fix (no snapshot read for the re-shown key) and passes after it. - `flutter analyze` clean; full mobile `flutter test` suite passes. - Automated app test (iOS 27 simulator, signed-in debug build): Home Team filter DM rows show presence dots, and they are still correct after switching to Solo for 70 s and back. The Team list stays mounted offstage while hidden, so that run is a smoke check of the presence flows; the retire and re-show path itself is covered by the new unit test. ## Regressions None expected. The extra read happens only when a newly tracked key is already covered by the live stream. `_schedule` already dedupes and skips while a retry is pending, so it adds at most one small snapshot query per re-shown key. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
c0ce4982fc |
buzz-db: check membership, agent-owner and channel references in app code (#9404)
> Builds on #9399 (its two commits are included here until it merges;
review only the commits after `367d3486`).
## What
This is the second app-side step toward retiring every foreign key,
following `docs/database.md` ("Retiring a trigger, function, or foreign
key"). Each writer below now checks its parent inside the writing
transaction and locks it `FOR KEY SHARE`, the same lock an FK check
takes. The FKs stay in place, so both checks run and agree. A later
contract migration drops them.
The shared helpers are in a new `store/reference_check.rs`:
`require_channel`, `require_optional_channel`, `require_user` and
`require_relay_member`, all community-scoped. A missing parent returns
`DbError::NotFound` and nothing is written.
| FK | Writer | Change |
|---|---|---|
| `join_policy_acceptances → relay_members` | `relay_invite.rs` (both
claim paths), `relay_invite/claim_owner.rs` | One helper locks the
member row, then inserts the acceptance. The existing-member read is now
`FOR KEY SHARE`. |
| `users.agent_owner_pubkey → users` | `user.rs`
`set_agent_owner_with_operation` | Reads the agent row `FOR NO KEY
UPDATE`. A missing agent → `NotFound`; an already-owned agent →
`Ok(false)` without examining the owner; otherwise the owner is checked,
then the UPDATE runs. `NotFound` for a missing owner therefore holds
with or without the self-FK. |
| `channel_members → channels` | `channel_members.rs`
`insert_auto_membership`, `lock_channel_archived_at_in_transaction` |
The auto-add checks the channel. The archive lock now returns
`ChannelNotFound` for a missing row instead of reading as not archived.
A soft-deleted channel still reads `None`. |
| `thread_metadata → channels` | `event.rs`, `thread.rs` | Checks the
channel before writing thread metadata, in the event's own transaction.
|
| `moderation_reports/actions → channels` | `moderation.rs`,
`relay_admin_actions.rs` | Checks a non-null `channel_id` before the
write, after the existing rejection outcomes (not-found,
already-claimed, not-open, replay). |
**Real race closed.** Member removal locks the member row `FOR UPDATE`,
deletes the acceptances, then deletes the member. The acceptance insert
used to follow an unlocked member read, and a membership `INSERT … ON
CONFLICT DO NOTHING` locks nothing when the member already exists. Today
only the FK's implicit `KEY SHARE` stops an orphan acceptance; this
change makes that lock explicit.
**Caller-visible behavior.**
- The huddle join in `audio/handler.rs` maps `ChannelNotFound`, meaning
the channel was purged between the pre-join check and the lock, to
`MembershipLost` before any write.
- `set_agent_owner` has one production caller, `api::write_agent_owner`.
It runs `ensure_user_for_authorization` on both the agent and the owner
first, so its behavior is unchanged.
- `put_members` keeps its existing error.
## Tests
- `store/reference_check_postgres_tests.rs`: 9 tests, one missing-parent
test per writer plus a `KEY SHARE` lock test. Each drops the covered FK
in its per-test DB (`test_support::drop_foreign_keys_between`), so it
proves the app check. The `insert_report` upsert test pins precedence: a
missing channel beats an existing report, and the stored row is
unchanged.
- `relay_members.rs`:
- Two new race tests: a membership claim racing member removal, and an
invite claim racing member removal.
- The existing
`member_removal_waits_for_and_removes_concurrent_acceptance` now runs
against the explicit lock.
- The `wait_for_put_member_behind` query pattern in `api/invites.rs`
tests was updated to the new query text.
- `relay_members.rs`
`invite_claim_conflicting_with_a_member_added_mid_claim_waits_for_removal`:
a `#[cfg(test)]` pause before the membership INSERT
(`relay_invite::test_hook`) lets a member commit mid-claim and a removal
hold it `FOR UPDATE`. The claim must wait, then return `NotFound` with
no acceptance, no orphan, and no invite use.
- `set_agent_owner_rejects_missing_owner_with_and_without_foreign_key`:
asserts `NotFound` and an unchanged owner with the FK installed, then
with it dropped.
Falsification: removing the check at each of the 10 call sites turns its
test red. So does stripping `FOR KEY SHARE` from each helper and from
the invite member read. Swapping the conflict-branch helper for a raw
acceptance insert, or moving the owner check back after the UPDATE, also
turns its test red.
## Validation
Run on a cloud workstation at this tree (
|
||
|
|
ec778bff9a |
buzz-db: enforce five single-table guards in app writers (phase 1) (#8320)
> **Also carries the catalog expand** (`cdc88edd`) for phase 2 (#9398). `validate_serving_catalog`, used at boot and readiness, no longer requires the `communities_deletion_tombstone` trigger, only `community_deletion_lock_key(uuid)`. Without this, a pod would fail boot after `0090` drops the guards. Regression: `migration_schema_single_table_guards_are_optional_for_serving_and_deletion` migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, and validates again. No schema change. ## What This is phase 1 of 2 for retiring five single-table guard triggers (BUZZ-318). Their invariants now hold in the application writers. **All five triggers and their functions stay** for mixed-version pods. A later PR drops them. | Trigger / function | App-side enforcement | |---|---| | `trg_channels_community_id_immutable` | **By construction.** Inserts bind the tenant once. No production `UPDATE channels` assigns `community_id`, and `ChannelUpdate` has no community field. A source policy pins this. | | `communities_deletion_tombstone` / `enforce_community_tombstone()` | **One state machine.** `begin_quiescing`, `fence`, `purge_postgres` and `abort` all go through `transition_community`, using a `FOR UPDATE` row snapshot in the caller's transaction (quiesce, fence and abort also hold the community deletion advisory lock; purge does not, and its tombstone transition fails if a concurrent abort won). Allowed transitions: active→quiescing (plus a quiescing retry); quiescing→fenced, which increments the generation; fenced→tombstone at the same generation, with a one-way `deleted_at`; active/quiescing/fenced→active on abort, which also increments the generation. Every transition rejects an already-deleted row. The UPDATE is conditioned on the snapshot's state and generation. `set_community_icon` updates only an active, undeleted row and returns `AccessDenied` otherwise. Archive and unarchive lock an active row, and their UPDATEs also carry `deletion_state = 'active'`, so every non-lifecycle `communities` UPDATE or upsert carries the active predicate (policy-pinned: a non-active row is immutable outside the state machine). No production `DELETE FROM communities` exists, and the policy forbids adding one. Executor GUCs are unchanged. | | `community_deletion_request_retargeting_guard` | **Mostly by construction, plus predicates.** No production UPDATE assigns target identity or provenance (policy-pinned). Both initial inventory freezes (`freeze_inventory`, `complete_owner_preparation`) require `stage = 'submitted' AND blocked_at IS NULL AND inventory_frozen_at IS NULL` in their UPDATE. Every request UPDATE that assigns an inventory column must carry `inventory_frozen_at IS NULL`, and one that assigns `destructive_storage_*` must carry the frozen-or-equal guard (policy-pinned). The destructive-manifest freeze now also refuses a row that is marked frozen but is missing its manifest JSON. | | `community_deletion_approval_removal_guard` | **By construction.** Approvals are insert-only (`approve`, `complete_owner_preparation`). The policy forbids any production UPDATE, `ON CONFLICT … DO UPDATE` upsert or DELETE. | | `community_deletion_manifest_keys_guard` | **One shared check.** Append, pre-freeze clear and verified cleanup each lock the request row and check its stage and freeze status through `guard_manifest_chunk_write`. Chunk content is never updated: the policy rejects every chunk UPDATE or conflict upsert except `mark_manifest_chunk_deleted`, the only writer that stamps `deleted_at`. That stamp must be the function's only chunk write, a plain UPDATE of exactly `SET deleted_at = now()`, with `request_id = $1`, `chunk_no = $2` and `deleted_at IS NULL` as plain conjuncts (no `OR`, no subquery), so it stays one-way. | **The app is stricter than the triggers, not equivalent to them.** `enforce_community_tombstone()` admits any change when the executor GUC matches, before it looks at lifecycle columns, so the transition graph above lives only in `transition_community`. The chunk DELETE trigger also allows cleanup when the parent request is missing or unfrozen, while `guard_manifest_chunk_write` allows only fenced-and-unfrozen or verified cleanup. Every current caller already runs at those stages. Writer inventory: I searched every production writer of these tables and columns across all crates, excluding `#[cfg(test)]`. That covers buzz-db, buzz-deletion, buzz-relay handlers, side effects and operator/admin APIs, and buzz-audit. Relay, operator and executor entry points all call the store methods above. No other crate writes these tables directly. ## Tests The six PG tests are in `store::deletion::postgres_tests`. Each disables **only** its own trigger, then checks that the app path rejects the forbidden mutation and permits the allowed one: - `single_table_guard_channels_remain_tenant_bound_without_trigger` - `single_table_guard_community_lifecycle_rejects_deleted_row_without_trigger`: icon refused while quiescing; fence refused on a deleted row; then the full fence→tombstone sequence; abort after tombstone fails. - `single_table_guard_abort_invalidates_generation_without_trigger`: abort from quiescing and from fenced, for unarchived and pre-archived communities; asserts active state, community and request generation = previous + 1, restored `archived_at`, null `deleted_at`. - `single_table_guard_request_inventory_freeze_is_one_way_without_trigger`: re-freeze is refused on both the operator and owner-preparation paths. The owner path leaves no approval evidence behind. Owner request-ID retargeting is refused, and a frozen manifest with missing JSON can't be filled in. - `single_table_guard_approval_evidence_is_append_only_without_trigger`: asserts the exact error. - `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` The source policy lives in `crates/buzz-db/tests/observability_source.rs` (`every_production_single_table_guard_writer_preserves_its_invariants`). It scans every crate's `src` directory and reuses the file's existing cfg-test stripping, comment and literal masking, function slicing and SQL normalization. Each rule is checked per function. A minimum count of discovered writers per table makes the test fail if discovery stops matching, and exact sets of production functions hit by each rule (lifecycle exemption, stamp exemption, chunk-guard callers, active-community writers, request-freeze writers) make it fail if a parser stops matching. The parser handles `ON CONFLICT … DO UPDATE SET` (with or without a space before `(`), tuple `SET (a, b) =`, and rejects column-less community inserts. A guard counts only as a plain conjunct of the statement's own WHERE: it must follow the WHERE start or an `AND` (optionally table-qualified, never `NOT`), with no whole-word `OR` outside the frozen-or-equal groups and no subquery, and every `destructive_storage_*` assignment must preserve a frozen value with `COALESCE`. Negative and accept fixtures cover every rule. The shared source filter now also skips `test_support.rs`, which is compiled only under `cfg(test)`. Each check was confirmed to fail when its fix is removed. Seven mutants each failed on an assertion: the `inventory_frozen_at` predicate removed from each of the two freeze paths, and each of the five policy rules disabled. Review rework also falsified the injected `SET icon = NULL` writer, an unguarded inventory/destructive-storage writer, abort keeping the old generation, and the stamp without `deleted_at IS NULL`; every new fixture test fails against the previous policy. Round 1 also falsified the lifecycle `deleted_at` check, the manifest append guard, the icon predicate and the destructive-manifest predicate. ## What got simpler The four lifecycle UPDATE statements, each with its own generation arithmetic and its own GUC setup, are now one transition function with one SQL writer. Both manifest removal modes share one admission check. For inventory freeze, the check lives in the existing atomic UPDATE, with no new helper or transaction. Channel immutability and approval append-only behavior stay construction rules, not duplicated runtime checks. The source-policy scans now share one Rust crate walker, which this PR extracted into `collect_production_rs_files`. **Known policy limits:** the policy is a textual check of Rust source, not a SQL parser or a control-flow analysis. None of these gaps hides an unsafe writer today, but phase-2 reviewers should not read the policy as more than that: - Only `INSERT`, `UPDATE` and `DELETE` statements are recognized, including CTE and `ON CONFLICT` forms. `MERGE` and `TRUNCATE` are not. `UPDATE ONLY <table>` and `DELETE FROM ONLY <table>` are not recognized either, because the table name must follow the verb directly. - A guard negated *after* itself (`deletion_state = 'active' IS FALSE`, `… = false`) is not caught. - A SQL comment inside the literal (`-- AND deletion_state = 'active'`) can supply the guard text. - The frozen-or-equal `OR` text is removed before the `OR` check without checking how it is grouped. - `guard_manifest_chunk_write(` is checked for presence in the writing function only. The policy does not show the result is awaited and propagated, or that the guard runs in the same transaction as the write. With the trigger disabled, `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` shows append and pre-freeze clear refusing after freeze; verified cleanup has no trigger-disabled test. - Function discovery uses a fixed list of signature prefixes, and dynamic SQL is recognized only in known shapes such as `set_parts.push`. - The shared source filter skips files named `test_support.rs` by name. Both such files are compiled only under `cfg(test)` today. **Phase 2 (not here):** a forward migration plus a desired-state change will drop only these five triggers and functions and update `validate_serving_catalog_on` and the schema assertions. It ships after every serving and executor pod runs these writers. **Identified debt (pre-existing, outside this diff):** purge can take the request-row FK lock (checkpoint insert) before the community lock, while abort locks community then request (`deletion.rs` purge vs abort). PostgreSQL detects that as a deadlock and cancels one side, which fails closed; the order is unchanged from the base. `runtime::postgres_tests::writer_pool_rejects_non_read_committed_database_default` hangs until its 120 s bound on clean `177551dda` as well. Some test-only fallbacks still hardcode `localhost:5432`, and one relay test helper hardcodes Redis 6379. ## Verification (Blox, byte-identical tree to this commit) | Gate | Result | |---|---| | `cargo fmt --all -- --check` | pass | | `cargo clippy --workspace --all-targets -- -D warnings` | pass | | `cargo nextest run -p buzz-db --lib` | 166/166 | | `cargo nextest run -p buzz-db --test observability_source` | 30/30 | | `scripts/test-postgres-test-discovery.sh` | pass | | `scripts/postgres-test-run.sh -p` buzz-admin / audit / deletion / push-gateway / relay / search / workflow | all rc 0 (4, 7, 11, 11, 402, 20, 2) | | `scripts/postgres-test-run.sh -p buzz-db` | 515 pass, 1 fail: the pre-existing hang above | The new PG tests are selected by the `postgres-ci` filter `(test(/postgres_tests::/) or binary(/^postgres_/)) and not test(/(^|::)external_infra[^:]*::/)`. The policy tests run in `just test-unit` (`--test observability_source`). --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c8a1b26345 |
docs(mobile): add REVIEWING.md with mobile review principles (#9298)
Adds `mobile/REVIEWING.md`, the principles we review mobile PRs against, and links it from the Reviewing section of `AGENTS.md` so any reviewer (human or agent) applies them to mobile changes and to relay or push-gateway behavior the app relies on. The principles: land Pareto improvements (better somewhere, worse nowhere), no hangs or stutters, use the network carefully, don't clog the pipe, keep the app usable, and don't regress developer experience (above all, no flaky tests). Each comes with past block/buzz PRs as examples. This tightens one existing rule rather than contradicting it. The Reviewing section blocks only on concrete correctness, security or contract defects with a realistic failure scenario. The new file treats a performance, network, reliability, developer-experience or UI-clarity regression as such a defect, as long as the finding names the mechanism and its effect. It also asks authors to say in the PR description why their change is a Pareto improvement. ### Validation Documentation only. Checked that the links and anchors resolve. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
3d97535120 | buzz-db: check workflow references in app code before FK retirement (#9399) | ||
|
|
833c41863a |
fix(relay): enforce channel owner precedence (#9592)
**Category:** fix **User Impact:** Channel admins can manage the conversation while owners retain control of ownership and owner membership. **Problem:** Channel admins can currently grant themselves ownership, change another owner's role, or remove an owner when another owner remains. A racing promotion can stop a removal after admission while its command is still stored and reported successful. **Solution:** Reserve ownership grants, owner role changes, and owner removal for channel owners, enforced during validation and under the database membership lock. Persist each removal and its signed command together so a locked refusal rejects the receipt without storing or broadcasting the refused command; this applies equally to people and agents, with no new role, migration or protocol field. <details> <summary>File changes</summary> **crates/buzz-core/src/channel.rs** Constrain the shared role policy and member admission decision. Keep same-role additions idempotent and preserve ordinary guest-promotion rules; extend the existing role matrix and cover ownership grants through admission. **crates/buzz-db/src/store/channel_members.rs** Reject non-owner removal of an owner under the existing membership lock, including removal of an agent the actor owns. Reuse those locked checks when storing a removal command and its membership change atomically. Retain database coverage for escalation denials, ordinary owner/admin powers and concurrency; move the target-promotion race to the ingest journey below. **crates/buzz-relay/src/handlers/channel_authz.rs** Make removal authorization aware of the target's role and expose an ownership-specific role-change refusal. Extend the existing authorization tables. **crates/buzz-relay/src/handlers/side_effects.rs** Pass the removal target into admission authorization. Persist removals atomically, then run cache invalidation, eviction and best-effort notices only after commit; duplicates run no second removal or notices. **crates/buzz-relay/src/handlers/ingest.rs** Route kind 9001 through atomic persistence and return locked membership refusals as client rejection before dispatch. **crates/buzz-relay/src/handlers/remove_user_postgres_tests.rs** Exercise the real ingest race with a membership-lock barrier: target promotion causes rejection, leaves the Owner intact and stores/publishes no command. Then verify legitimate removal and duplicate replay after rejoin. This replaces the DB-only target-promotion test rather than duplicating it. **crates/buzz-relay/src/handlers/mod.rs** Register the new PostgreSQL ingest journey for automatic discovery. **NOSTR.md** Document owner precedence, including the agent-owner exception's boundary. </details> ### Try it 1. Run the updated relay and create a disposable channel with two owners, one admin, and one ordinary member. Two owners ensure the last-owner guard cannot mask the new permission check. 2. As the admin, attempt to promote yourself or another member to owner. Both requests should be refused. 3. As the admin, attempt to demote or remove either owner. Both requests should be refused and their memberships should remain unchanged. 4. Confirm the admin can still rename the channel and manage ordinary members/admins. 5. As an owner, confirm ownership delegation and co-owner demotion/removal still work. The sole remaining owner must still be unable to demote or remove themselves. 6. Run the PostgreSQL lane's membership regressions and `removal_receipt_tracks_the_locked_membership_write`. The controlled race must return rejection with the target still Owner and no stored/published removal; the same command must succeed once authorized, and its later replay must preserve a rejoined member. ### Validation and remaining checks - At `e7a8fe405`, all **2,048 infrastructure-free tests** across the complete `buzz-db`/`buzz-relay` package inventory pass with nextest process isolation, plus all **five package doctests**. The monolithic Cargo run stalled in shared-process configuration tests; the same package inventory passes with the repository's preferred isolated runner, without exclusions or assertion changes. - The new ingest journey fails on the original implementation with `accepted:true` after the locked refusal, and passes with atomic removal. Its positive controls verify actual publication for a legitimate removal and no repeated removal/publication after rejoin. The existing demoted-actor lock test retains direct-call concurrency coverage. - At the same head, all **1,425 PostgreSQL cases** across both packages pass through the per-test isolation wrapper (PostgreSQL 17.12, UTC; hosted CI uses 16). A rebuilt isolated native relay passes **24 signed WebSocket operations** plus persisted-state and subscriber checks, including the real promotion/removal race, later legitimate retry and replay after rejoin. Temporary services are stopped; Git/media behavior was not exercised. All mandatory push hooks pass, including the broad Rust suite (709.20s) and native/desktop checks (302.32s). - Test churn is **420 lines** (+399/-21); non-test churn is **196 lines** (186 source, 10 maintained docs), versus 279/69 at the preceding head. The new 207-line ingest journey and two-line registration replace the 68-line DB-only target-promotion race; no other authorization or concurrency coverage is removed. - The implementation tree passed 298 core library tests, 1,979 database/relay library tests, and 76 binary/integration-target tests: 2,353 total. Infrastructure-dependent ignored tests were excluded. These runs preceded publication; the publication commit has the identical source tree, with only its commit subject amended. - Disabling the ownership-grant guard made the admission regression fail with `Ok(Owner)`; restoring the guard returned all 298 core tests to green. - At follow-up head `6d4622d3e`, all 769 PostgreSQL tests in the `buzz-db` package profile passed using the repository's per-test database isolation wrapper (PostgreSQL 17.12, UTC; 245 cases outside the selected profile skipped). This includes both new regressions and the existing owner-management journey retained after removing two repeated positive checks. - An isolated native relay passed 18 signed WebSocket operations plus persisted-state checks: admin escalation, co-owner demotion/removal, retained admin management, owner delegation/demotion/removal, and last-owner protection. This membership workflow used local PostgreSQL and Redis; Git/media behavior was not exercised. - PostgreSQL test discovery, formatting, and hosted CI passed at `6d4622d3e`. Maintainer approval and human acceptance remain pending. This relay permission change does not require a client update. Related history: #3017 established bidirectional elevated-role checks and last-owner protection; #8143 introduced the current shared role predicate. This PR adds the Owner-over-Admin distinction to those rules. --------- Signed-off-by: Taylor Ho <taylorkmho@gmail.com> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz> |
||
|
|
97d5a46cc6 |
feat(relay): grow DMs in place, identified by their people (#9125)
## Summary
Lets a DM grow. Today adding someone to a DM always starts a new DM.
This makes the relay side of "growable DMs" work. Joining an existing
DM, and seeing its history, is always opt-in: without `["history",
"include"]` the relay never puts anyone into an existing DM, so older
clients can't add anyone to one unseen.
- **Opt-in tag on kind:41010 and kind:41011.** `["history", "include"]`,
or `["history", "ask"]` on 41011, is the only way anyone joins an
existing DM. Any other value is refused.
- **41011 with the tag:** people and agents join this DM with its
history. When people join, the DM's identity moves to the grown set of
people, so messaging only the original people afterwards starts a new
DM.
- **A DM of at most one person never gains people in place**, even with
the tag. Adding a person to you-and-your-agents starts or opens a DM of
the people, and the original keeps its members. Agents still join it in
place.
- **41011 without the tag:** finds or makes a DM of the source's people
plus whoever is added, as an untagged 41010 does, and adds no one to an
existing DM. Agents already in the source stay behind; agents named in
the add join the new DM.
- **41011 with `["history", "ask"]`:** part of the protocol, because
desktop and mobile use it to know when to ask about history. Agents
alone, and people added to a DM of at most one person, are handled as
with `include`. People who would join a DM of two or more people are
refused with exactly `needs-choice: history` and nothing changes; the
client asks, then sends the add again tagged `include` or untagged.
Agents can't send it, and it isn't accepted on 41010.
- **41010 with the tag:** finds the DM of the named people and adds any
named agents it lacks. A DM still identified by all its members (made
without the tag) moves to its people's identity when reopened this way.
- **41010 without the tag:** finds the DM of those people, which agents
may have joined, or creates a DM of exactly the named members. There is
one DM per group of people, and agents joining it don't fork it
(Morgan's product decision), so no second DM of the same people is ever
created. A DM made this way with agents named gets an all-members
fingerprint, so it never collides with the people's DM.
- **A DM of people is identified by its people.** Agents don't change
which DM it is and don't count toward the 9-person limit. There is no
agent limit, matching channels. A DM with at most one person (you and
your agents) is identified by all its members: an agent joining it moves
its identity, so reopening the original pair starts a new DM.
- **Collisions.** If people join and a DM of the grown set already
exists, the relay returns it (`response:{"channel_id","created":false}`)
and changes nothing here. Agents named with them join that DM. Agents
alone join in place; if the identity the DM would move to is already
taken (only possible for a DM of at most one person, or one still
identified by all its members), the DM gives up its identity, so
reopening its old members starts a new DM.
- **One locked step.** Every DM membership write rereads the DM's
members under its membership lock, checks the agents actually joining,
and compares the DM's identity with the fingerprint actually stored.
Starting a new DM from a DM uses the members it has at that moment.
`created` is true only when this request made the DM, even if a
concurrent open won the race.
- **Agent add policies.** Putting someone else's agent in a DM with
anyone besides you follows its `channel_add_policy`, the same rule as
channels. That covers every agent in a new DM started from another one,
and only the agents that join when a DM grows or is reopened. Messaging
an agent alone ignores it, as today.
- **Only people grow DMs.** An agent can't send the history tag on 41010
or 41011, so a DM an agent opens is identified by all its members and an
agent can't take over or join a DM of its owner's people. Growing never
reveals a DM the actor isn't in. The relay can't be added to any DM.
- **The 9-person limit counts the caller only if they're a person**, so
an agent can open a DM with nine people.
- **A new DM carries people, not agents.** Every fork (Start new DM, the
tagless 41011, a person added to an agent-only DM) holds the source's
people plus the explicit additions. Agents can be added back later, so
no agent's add policy can block Start new DM.
- **Removing an agent keeps an old DM its people's.** A DM identified by
all its members moves to its people's identity when an agent leaves or
is removed, unless they already have a DM.
- **Leaving and removing agents.** kind:9022 lets anyone leave a DM, and
kind:9001 lets you remove yourself or your own agent (as deleting an
agent does). kind:9000 and every other 9001 are refused on DMs; members
join only through 41010/41011.
- **Removals keep identity in step.** When anyone leaves or is removed,
including moderation kicks (which remove members directly in the
database), the DM keeps its identity only if its remaining members still
match it. Otherwise it gives the identity up under the same membership
lock: it keeps its history, and opening that group again starts a new
DM. Removing an agent from a group DM keeps it that group's DM.
- **The relay's moderation DM stays two-party**, on both 41010 and
41011.
- SDK `build_dm_add_member(..., include_history)`, the opt-in
`build_dm_open_with_history` (`build_dm_open` keeps the exact-members
behavior; neither caps pubkeys, since the relay enforces nine people and
agents do not count), and CLI `buzz dms add-member --include-history`.
Without the flag the CLI keeps the old behavior.
Removing other people (beyond moderation kicks) and DM naming are out of
scope.
Client follow-ups: block/buzz-app#2670 (desktop, sends the tag for
history adds, agent adds, and New message opens that show an existing
DM) and the mobile PR (sends it after its choice dialog).
**Deploy this relay change before the app PR merges:** an older relay
ignores the history tag, so the app's Include history would start a new
DM instead.
### Decisions and known gaps
- **No agent cap, on purpose.** This matches channels. The guard is the
add policy instead: every agent the caller doesn't own needs its
`channel_add_policy` to allow it when it joins a DM that holds anyone
besides the caller and that one agent. So a DM stuffed with 40 agents
whose policy is `nobody` is refused. Covered by
`adding_an_agent_follows_its_add_policy` and
`opening_with_several_agents_follows_their_add_policy`.
- **A tagless add opens the DM of the people plus the additions.** Older
clients forking a DM now leave its existing agents behind, as the new
apps do. That shares less than before, never more.
- **Where the protocol is documented.** kind:41010 and kind:41011 have
no NIP today. The history tag is documented on the SDK builders (the
add-member builder also documents `ask` and its `needs-choice: history`
refusal, which it doesn't send) and in the CLI `--include-history` help,
and the `created` field of the response is documented on the SDK
builder.
- **Known gap: lost announcements on retry.** The membership change and
the idempotency record commit separately, the same pattern main uses for
every DM command. If the membership change commits but the idempotency
commit then fails, a client retry finds the members already there and
returns success without posting the join messages, notifications or the
new-DM announcement. Membership and history are correct. This needs a
commit failure between the two writes, and fixing it means moving the DM
writes into the idempotency transaction for all DM commands, so it's out
of scope here.
### Rollout and rollback
- **No kill switch needed.** The new behavior is opt-in per event:
clients that don't send `["history", "include"]` get the old behavior.
- **If the relay rolls back,** DMs that grew are no longer found by
their people, so opening one starts a new DM. History stays in the grown
DM and no data is corrupted.
### Related issue
None found.
### Testing
- Postgres-backed handler tests (`handlers::dm_growth_postgres_tests`,
44 cases) go through `ingest_event`: growing with and without history,
the tagless 41010 and 41011 paths adding no one to an existing DM,
collisions, agents joining in place only with the tag, per-agent owner
DMs, the people-only limit, add policies (including several agents with
no other person), agent actors, not revealing a DM the actor isn't in,
the moderation DM on both kinds, a person added to an agent-only DM with
the tag starting a separate DM, unknown history values, 9000 refused,
leaving, owners removing their agents, kicks releasing or keeping
identity, legacy fingerprints reconciled on agent join and tagged reopen
(with the collision case), an agent joining a one-person DM whose grown
identity is taken, untagged adds that name a person and an agent
starting a DM of exactly those members, `ask` adding agents and refusing
people, untagged opens of a group's people finding their DM with its
agents (after an agent joined in place, and after one of two agents
left), reopening past an existing `owner_only` agent, concurrent opens
all adding their agents, new DMs carrying only people (and named
agents), live membership, the relay key refused, and an agent opening a
nine-person DM. Each new guard was mutation-checked: removing it turns a
test red.
- At
|
||
|
|
f315c7f31f |
feat(workflow): implement send_dm action (#9402)
## Summary
Workflows using `send_dm` currently fail with `NotImplemented`.
Implement the action by creating or reusing a private DM between the
workflow owner and the resolved recipient, then publishing through the
existing relay message path.
- Preserve community scoping, workflow attribution, and authored mention
provenance. Require channel owner/admin authority, as for outbound
webhooks.
- Accept only a fixed hex recipient or `{{trigger.author}}`, including
for previously stored definitions. Require an existing, unbanned
recipient in the run’s community.
- Reuse private conversations without unhiding them or repeating
member-added notices. Retain replaceable discovery events for recovery,
and validate media before creating a conversation. Propagate failures
rather than reporting success.
- Cover template resolution, signed message persistence, conversation
reuse, recipient restrictions, and both agent-mention policy modes.
- Atomically create DMs by participant hash so concurrent first sends
reuse one conversation and only the inserting caller emits membership
notices. Preserve hidden state on workflow reuse.
- Follow current main’s agent-DM policy and per-run mention-authority
gate, including withheld-mention trace output.
### Related issue
None found after searching open issues and PRs for `send_dm`, `SendDm`,
and `sendDm`.
### Testing
- `cargo test -p buzz-workflow`: 176 passed.
- `cargo test -p buzz-relay --lib workflow_sink::tests`: 23 passed.
- PostgreSQL-backed `workflow_sink` tests against an isolated PostgreSQL
17 database: 8 passed.
- `cargo clippy -p buzz-relay -p buzz-workflow --all-targets -- -D
warnings`: passed.
- Concurrent DM creation PostgreSQL regression: passed. A table-lock
barrier forces both callers to INSERT, covering interactive/interactive
and interactive/workflow races, accurate creation flags, and
hidden-state preservation.
- `cargo test -p buzz-db --lib`: 216 passed (763 PostgreSQL tests
ignored); the new PostgreSQL regression was run explicitly.
- Updated `workflow_sink` suite including PostgreSQL integration tests:
31 passed.
- `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings`:
passed.
- Rust formatting, diff whitespace checks, and PostgreSQL test
discovery: passed.
- Pre-push hooks: passed, including the broader Rust unit suites,
desktop/Tauri checks, and file-size gate.
- Previous full `just ci` attempt stopped at unrelated mobile
dependency/formatting checks. Full `just ci` was not rerun after merging
main; targeted tests, lint, and the repository pre-push hooks cover the
updated branch.
Draft pending human testing and the review checklist. Manual check: as a
channel owner/admin, configure a `message_posted` workflow with `action:
send_dm`, `to: '{{trigger.author}}'`, and `text: 'Notice:
{{trigger.text}}'`; trigger it twice as another user. Both rendered
messages should appear in the same private DM with the workflow owner,
and both runs should return a successful send with an event ID. A second
send must not add membership notices or unhide a hidden DM. Plain
members must not be able to save or run this action; arbitrary recipient
templates and unknown/banned recipients must be rejected.
---------
Signed-off-by: Yissachar Radcliffe <yissachar@squareup.com>
mobile-v1.4.0-rc.2
|
||
|
|
b0e55606f2 |
perf(mobile): stop following presence for people no longer shown (#9480)
[#9444](https://github.com/block/buzz/pull/9444) narrows the live presence subscription (kind 20001) to the people the app has shown this session. That set only grows, so scrolling through a long DM list or opening many profiles keeps receiving presence for people who are no longer on screen, and each new person reopens the subscription with everyone seen so far. This was raised in [Jude's review](https://github.com/block/buzz/pull/9444#pullrequestreview-5896221680). With this change, presence follows only who is on screen now: - `track` returns a release callback. DM rows and profile sheets release when they unmount. Counts are per person, so someone shown in a DM row and an open profile sheet stays followed until both are gone. - A person nobody has shown for at least 30 seconds is retired: dropped from the tracked set and the cache, and the live subscription is replaced with one for the people still shown. A sweep every 30 seconds retires everyone whose own 30 seconds are up, so each person stays followed for 30 to 60 seconds after their release and the subscription narrows at most once per 30 seconds. Scrolling back within 30 seconds keeps the current subscription. - A read that started before someone was retired doesn't fill in their presence if they are shown again; they wait for a read of their own. - When nobody is shown, the stream closes, and the next person shown opens a new one immediately. - Switching communities keeps following people still on screen, instead of dropping everyone. ### Regressions - **Mention picker ranking.** The picker reads the presence cache without tracking anyone itself, so it ranks by presence only for people currently on screen (before, also for anyone shown earlier in the session). Keeping a retired person's last value would show stale presence, which is worse. - **Dot pop-in.** A retired person's dot is missing when they come back (scrolling back after 30 seconds, or switching the Home filter to Solo and back after 30 seconds) until the replacement subscription is ready and their snapshot read returns. On a slow link that can take seconds. Before, the dot stayed for the whole session. - **Network.** A retirement costs one replacement REQ and a CLOSE, at most once per 30 seconds of scrolling. A person shown again after being retired costs one snapshot read, the same as the first time they were shown. - **Reliability.** Narrowing uses #9444's replacement path (the old stream stays until the new one is ready), so a failed narrowing keeps the wider stream and the poll retries it. ### Validation iPhone 12 mini on Builderlab (measured on [ |
||
|
|
b303271ad3 |
[buzz] Classify HTTP event request metrics by event type (#9561)
## What Add an `event_type` label to `/events` request-count and latency metrics so operators can inspect and alert on individual operations. ## Why The existing `/events` latency alert combines message sending, profile updates, reactions, typing and identity archive/unarchive into one p95 signal. Slow archive work can trigger the same generic page as slow message sending. The page does not identify which operation is slow or show whether messaging is affected, so on-call has to inspect traces and logs before deciding what needs attention. This change supplies the event-type dimension needed to name the slow operation and choose its notification urgency. Reusing the kind registry also keeps newly registered operations visible automatically. ## How Classify events from the kind already parsed by the HTTP bridge and pass that classification to the outer request timer. Both `http_requests_total` and `http_request_latency_ms` gain a bounded label: - `message`, `profile_update`, `reaction`, `typing` - `identity_archive`, `identity_unarchive` - `kind_<number>` for other kinds registered in the existing `ALL_KINDS` registry, using `registered_kind_label` - `other` for unregistered kinds, `invalid` for malformed event JSON, and `unknown` for requests that fail before parsing New entries in the shared registry automatically receive a distinct metric label without updating a separate metrics list. Friendly names remain for the common operation groups. Latency continues to cover the full request, including admission and processing. Existing metric names and labels remain available, and other routes retain their current labels. Classification uses the existing parse path without changing admission order. No database migration is required. Closest existing PR: none found. --------- Signed-off-by: Helen Tian <htian@squareup.com> |
||
|
|
7d361d1f6b |
update feedback community invite link (#9588)
Replaces the expired Buzz feedback community invite link in the README with the current one. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Diem Nguyen <diem@squareup.com> Co-authored-by: Fizz <6be7be23ec5bba868f3e1db5ec86013d76bd1a293dce5b435a192158fec13641@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d39545ebd4 |
fix(mobile): name the failing step in sign-in errors (#9263)
Organization sign-in shows the same "Couldn't sign in. Try again." (landing page) or "Sign in failed. Try again." (in-app banner) for every failure after the browser hands control back: a rejected or stale callback, a keychain write that doesn't stick, a code exchange the server refuses, a session for a different account, or a malformed response. Server logs can't tell these apart either, because the exchange can succeed on the server and still fail on the device. So a user's screenshot of the error tells us nothing about which step broke. This appends a short code naming the failure, for example "Couldn't sign in (account-storage). Try again." or "Sign in failed (browser-restartLogin). Try again." The code is the failure's enum name, prefixed by where it came from (`browser-` for the callback, `account-` for the exchange and session). An unexpected failure type throws instead of showing a made-up code. ### Validation - Focused test changes: the sign-in banner's recovery test now checks the code in the message for two account failures and one browser failure, at each text scale. - Full mobile suite (`flutter test`) and `flutter analyze` pass. - Not yet: an automated app run reproducing a failed sign-in to capture the new message on screen. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
aec5710453 |
fix(mobile): order same-second messages by millisecond offsets (#9541)
## Summary Messages sharing a Nostr second can appear in hash order on mobile even when their signed `ms` tags establish a send order. Channel timelines and thread replies now compare `created_at * 1000 + ms`, using the same first-tag and canonical 0–999 validation as desktop. Each comparator retains its existing event-ID tie-break. Effective times are computed once per event and memoized. Relay paging still uses whole seconds and IDs. Legacy history now chooses and filters its cursor with the existing relay-order helpers, independently of display order. The channel-window relay comparator is unchanged. The review fixes from #9550 preserve the original event's millisecond time through edits and provisional thread rendering, so cached replies keep their order when the query lands. Effective edits use the relay's greatest `(created_at, id)` rule, independently of display order. ### Related issue Related desktop symptom: #8192. Desktop implementation: block/buzz-app#249. No matching open mobile PR found in the original searches for same-second/millisecond titles. Review fixes: #9550, merged without rewriting its commit. ### Testing - Original regression run against unchanged production source: four failures covering channel/thread millisecond order, window flattening, and legacy pagination; all 218 focused tests passed after the initial fix. - Review regressions cover `007`/`12a` rejection, same-second edit selection in both input orders, and provisional replies before/after query completion. - Final head, including current main: `f3fdf3fa0fae6e495e6fc1b7b38f4834a1751d56`. - `just mobile-install` passed. The required push hook then passed `just mobile-check && just mobile-test` on that clean head, including formatting, analysis, the full Flutter suite, gateway recipe checks and the crypto-package suite. File-size and diff-whitespace checks passed. Draft pending simulator revalidation and human testing of the merged head. Re-run numbered 60-message channel and thread sequences, then a 200-message burst. Verify send order, the newest message at the end, same-second edits, and cached thread ordering as the query completes. Page backward and confirm the fully loaded history has no missing or duplicate messages. Scope note: during backward paging, the oldest loaded second can temporarily show gaps because relay pages select an ID-ordered subset of that second while rendering uses milliseconds. The next page fills those gaps; fully loaded history is complete. Boundary continuity needs a separate loading contract and remains deferred. --------- Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
0dca767e5e |
fix(acp): saturate observer frame size estimates (#9494)
## Summary Use `saturating_add` for the three additions in the observer frame-size estimate. `serialized_len` returns `usize::MAX` on a serialization error; ordinary addition can panic in debug builds or wrap in release builds. Saturation keeps that estimate above the plaintext limit, so the next event stays queued. This is defensive hardening. The current empty envelope contains only JSON-safe fields, so a normal event cannot trigger that serialization error. ### Related issue Follow-up to #9483, addressing [this review suggestion](https://github.com/block/buzz/pull/9483#discussion_r4569450055). No duplicate issue or PR found. ### Testing Manually ran `observer::packing_tests::publish_queue_drain_probe --exact --ignored --nocapture` on the rebuilt debug test executable. All 10,000 events drained in order into 30 frames within the byte limit, with zero pending bytes. To reproduce: ```sh cargo test -p buzz-acp --lib observer::packing_tests::publish_queue_drain_probe -- --exact --ignored --nocapture ``` Generated with AI assistance Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> Co-authored-by: Codex <codex@openai.com> |
||
|
|
9ccad95344 |
feat(mobile): accept mentions with Tab and send with Enter on hardware keyboards (#8733)
## Summary The mobile composer ignored Tab and Enter from hardware keyboards. Tab and Enter now accept the first selectable mention or channel suggestion while its picker is visible. Otherwise Enter or numpad Enter sends the message when attachment controls are closed. Enter leaves the draft untouched while an attachment surface is open. Tab leaves the draft unchanged while the picker is hidden or the field is read-only. A visible picker with no selectable row consumes Tab and Enter without sending. Only unmodified Tab accepts suggestions. Native attachment and emoji pickers own keyboard input until dismissal. Keyboard suggestion acceptance and sending use the same selection haptic as touch. Modified Enter and active IME composition retain normal text-field handling. Android IMEs can emit Enter as a key event too. Sending requires a mapped physical Enter key on Android, so scan-code-free IME Enter keeps newline handling. ### Related issue None found. ### Testing The composer widget regressions reproduce ignored Tab/Enter before the feature and an unintended send from Android IME Enter before its guard. The picker regressions cover Enter accepting a visible suggestion, Enter and numpad Enter retaining an Android draft while the attachment menu is open, and Tab leaving hidden or read-only suggestions untouched. They verify suggestion acceptance, error-only picker handling, native attachment popover ownership, modified Tab, sending, software Return and Android physical-key handling. Rapid Enter while member scanning is pending sends only once through the existing draft revision guard. Native validation and screenshots use an isolated Android API 28 ComposeBar harness at `09fb673f9`, with an observed send callback and a test-only native key injector. Physical Enter sends once and clears the draft; IME Enter inserts a newline without sending. Native validation of picker acceptance, visibility and read-only handling remains outstanding. ### Screenshots | Physical Enter sends and clears the draft | IME Enter keeps a newline without sending | | --- | --- | |  |  | | Mention suggestions | Tab accepts the suggestion | | --- | --- | |  |  | --------- Signed-off-by: John Tennant <jtennant@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Oliver <e78152627ea32fbacb070e5047afcfb8e409fa3343d9e618227baacca5b5e607@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
6f438202a0 |
Fix remote Huddle ending cleanup (#9376)
## Summary When the final Huddle audio connection was routed through another relay, owner cleanup removed the room without archiving the channel or publishing the ended event, leaving Join visible. Share committed-room finalization across local, remote, and pending-last-slot teardown. Retain the admission gate until finalization and recheck fenced owner authority under the database lock. Relay/database only; mobile history access is separate in #9375. Existing orphaned rooms are not retroactively archived. Existing clients remain responsible for disconnecting agents when the last human device leaves. ### Related issue Related: #4879 / #4918 concern discovery metadata after auto-archive. Searched open Huddle issues/PRs; no exact duplicate found. ### Testing This is the unchanged relay patch previously validated in combined commit `4ec349435151ca11ce92bd0ebe59b845b3465639`, split onto current main (whose intervening change is the relay version/changelog release). - Full PostgreSQL package lane: 1,376 initially passed; both initial failures passed after fixing local psql PATH and using actual joined/teardown completion in the test. Cleanup asserts archival and exactly one ended event. - Remote-control, pending-last-slot, and conditional archival regressions passed. - Full relay/database unit packages: 1,960 passed; five identity/archive and audit fixture failures report missing `artifact_heads` outside changed paths. - Relay/database all-target clippy and legacy desktop clippy/tests passed. Broader pre-push Rust groups passed after rerunning the load-generator group with a higher file-descriptor limit and four test threads (110 passed). - Independent relay review completed; formatting/diff/file-size guards passed. The split reused completed test evidence; no full rebuild was repeated solely for the split. Draft pending human/live-call validation. Start an agent Huddle, leave from the final human device, and verify its card stops offering Join, including connections routed through different relay servers. Not deployed. --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
921a05a379 |
fix(mobile): host Duo long-press menus in native sheets (#9536)
## Summary On unfolded Duo landscape, channel/DM actions and Solo details now open in a UIKit sheet above the app’s native controls, while retaining Buzz’s Flutter tiles, member rows, and grouped cards. Content drags take priority over sheet dragging; the native top bar still supports dismissal. The presentation-only engine starts only when an eligible sheet is presented, without account, camera, audio, or storage plugins. It is destroyed on dismissal; other iPhones pay no second-engine launch cost. The main app retains live permissions and actions, and the native sheet dismisses before opening follow-up screens. Cover-display and portrait postures retain the existing bottom sheet. Pending avatar requests are abandoned on dismissal, including after the display wait expires; the display timeout alone lets the download finish and cache. Confirmed lifecycle actions retire the invisible owner route before waiting for the relay. ### Related issue Follow-up to #8568. No duplicate sheet PR found. ### Testing - `just mobile-install mobile-check mobile-test`: clean analysis; 4,900 Flutter tests passed (71 skipped), plus gateway/package checks. - Mobile file-size and diff checks passed. - Earlier signed device preview built, installed, and launched; owner confirmed its scrolling. The later lazy-start and lifecycle fixes have not been rechecked on the device. - Unsigned iOS release build passed for `4ed94c6eb4` (Xcode 116.7s). - Journeys cover bridge permissions, copy/close callbacks, the content renderer, full profile-to-DM return, and reopening the list during a held archive. Avatar tests cover immediate cancellation, display timeout followed by cancellation, and timeout followed by completion and cache reuse; regression probes fail with the fixes disabled. UIKit drag handling still lacks automated interaction coverage. ### Snapshots Actual Flutter sheet contents at 540×580 points with sample data. These show the content layout; they do not show UIKit’s surrounding sheet or its animation. | Surface | Light | Dark | | --- | --- | --- | | Solo details |  |  | | Channel actions |  |  | --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> |
||
|
|
7b8066fb94 |
fix(mobile): keep the relay session across auth reloads (#9543)
## Summary `RelaySessionNotifier.build()` watched the whole `authProvider` but only read the signed-in status. Every `ref.invalidate(authProvider)` therefore rebuilt the session: the socket and all live subscriptions were dropped, and every screen resubscribed and republished presence and read state at once. An invite join invalidates auth twice for the same identity (3 sockets in about half a second), and each community switch does it again, producing a REQ burst the relay answers with `CLOSED rate-limited`. The session now watches only `(status, community.pubkey)` via `select`, so it still rebuilds when the user signs in or out, or switches identity while signed in. Relay URL and signing key changes continue to rebuild through `relayConfigProvider`, which is unchanged. ### Related issue None found. ### Testing - New regression test in `relay_session_test.dart`: with a connected socket and a live subscription, two auth invalidations for the same identity keep 1 socket, 0 disposes, `connected` status and a working subscription; a pubkey change then rebuilds to a second socket, and signing out disposes it. - The test fails on `main` without the fix (`Expected: an object with length of <1>`) and passes with it. - `just mobile-install mobile-check mobile-test`: format clean, `flutter analyze` no issues, 4909 tests passed (71 skipped), plus the native-secp256k1 package suite (27 passed). ### Before and after: first-launch invite join (simulator) Captured on a freshly erased iPhone 17 simulator with a one-use invite for each run, counting relay traffic for this identity in the first 5 s after launch. Before is `main` at `1a5c6939c`; after is this branch at `8beda6aea`. | | Before | After | |---|---|---| | Relay sockets opened during the join | 3 | **1** | | Relay frames in the first 5 s | 72 | 57 | | `OK false` for kinds 20001/30078 | 2 | **0** | | REQs refused with `quota_exceeded` | 16 | 6 | | Message posted after the join arrives live | yes | yes, on the same socket | The session rebuild is fixed: the join keeps one socket and its subscriptions. The original target of fewer than 50 frames in 5 s is not met. The remaining burst is about 31 separate single-document kind 30078 reads (`limit:1`, `authors` = self) at about +1.1 s, and all 6 remaining `quota_exceeded` refusals are among them. Those reads don't come from session rebuilds, so they'll be handled in a separate change rather than in this PR. - Not yet done: a run on a physical device of the first-launch join flow. Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz> |
||
|
|
65b566ca72 |
feat(deletion): clean up media for users and owned agents (#9365)
## Why
User deletion must remove uploads by the user and their owned agents
while preserving files uploaded by anyone else. Attribution can span
communities and survive only in storage, so cleanup must combine
database and storage evidence.
## What
Add one media handler used by both the direct `user-deletions
media-batches` command and the persisted user-deletion workflow. Preview
is read-only by default; deletion requires `--delete`.
The workflow now always runs `gate_user` → `purge_media` → community
stages. The gate and community handlers remain placeholders. Media
failure stays on the same stage for retry; a saved completed media stage
is not executed again on restart.
## How
- Resolve the human and directly owned agents once across communities.
Sharing within that target set does not protect a file.
- Combine candidate discovery from `media_uploaders` and upload audit
history with a sharing check for those hashes. Check outside uploaders
across all communities. Storage-only candidates receive the same
database check in batches.
- Add four nonunique indexes for uploader and hash lookups. Current
membership cannot safely filter historical discovery: departed members
may have no remaining membership row.
- Scan `_uploads/` for candidates, then candidate claims for outside
ownership. List blob and thumbnail versions by each selected `{hash}.`
prefix. A separate `_meta/` listing preserves sidecar coverage when no
matching claim or current membership remains. There is no whole-bucket
listing.
- Finish all discovery before deletion. Read historical claims using
exact `versionId` values. Delete exclusive file versions and markers,
with upload-attribution objects last. Remove target uploader rows after
storage processing succeeds. Shared storage versions and outside
uploader rows remain.
- Stream one JSON document with file identity, keep/delete status,
versions, and outcome counts. Remove per-file owner queries and owner
arrays. Workflow stdout remains inspection JSON; media reporting goes to
stderr.
Database/inventory pages hold at most 500 rows. Storage listings use at
most 1,000 entries per page and 100,000 pages per listing. A disposable
in-memory inventory has a 128 MiB accounting budget and a 250,000-entry
cap, including candidates, filenames, versions, and listing markers.
Accounting includes string bytes, inline data, and a conservative
allowance for tree/allocator overhead; it is not a process RSS limit.
This removes the SQLite dependency without a security-policy exception.
Large jobs may reach capacity sooner than with the former 1 GiB disk
inventory. Exceeding a discovery limit aborts before mutation; no
truncated inventory is used for deletion.
Migration 0092 and the desired schema add the same indexes. The
migration builds missing indexes under short lock/statement budgets and
verifies existing definitions. Large deployments can prebuild
concurrently using the procedure in [the executor
guide](docs/operator-user-deletion-executor.md). Existing relay writes
remain compatible. A stale workflow test call from the merged main
branch also receives its required run-cause argument.
## Risk
This performs real storage deletion. Writers must remain stopped; the
placeholder gate does not prevent uploads. Immutable version IDs are
required for exclusive objects. All results report
`account_erasure_complete: false`. Existing synthetic progress saved
under the older gate-to-community sequence is not migrated into the new
sequence.
Shared storage claims and audit history remain. They can continue
protecting a blob after both uploaders leave; claim retirement is
separate work. Metadata namespace scans remain proportional to their
sizes. Bare blobs with no surviving attribution cannot be assigned to a
user.
## Testing
Before committing the replacement as
`38c60be7f6c3ee3f6942ab89858ce42e2a536c5d`, exercised the actual
`buzz-admin user-deletions media-batches` command against a fresh local
PostgreSQL database and versioned MinIO bucket. Preview preserved all 23
versions and all database rows. Deletion removed 14 exclusive versions,
preserved nine shared/unrelated versions, and removed only five target
uploader rows. Retry removed no further versions; events and
publications remained unchanged.
A standalone probe of the production inventory reached the default byte
budget after 243,148 short-key versions or 90,933 versions with 1 KiB
keys. Peak process RSS was approximately 108 MiB and 124 MiB on macOS;
these measurements describe the probe, not total command memory.
Manually removed `versionId` from the production adapter's request and
ran `cargo test -p buzz-deletion --lib
historical_claim_protects_shared_file_and_bad_claim_aborts_before_deletion`.
The regression failed because the historical outside uploader no longer
protected the file. Restored the adapter before final validation.
Earlier live-lab evidence used the direct command at
`633fdb2a48dce64f904c0077689704f136c722c1`, before this query/storage
update: 38 exclusive files and 300 versions were deleted; 24 shared
files and 10 unrelated files remained. Authenticated downloads returned
404 for all deleted originals and matching hashes for all preserved
originals. That live deletion was not repeated for this update, and does
not attest concurrent-upload safety or complete account erasure.
## Bigger picture
Media tracking:
[BUZZ-415](https://linear.app/squareup/issue/BUZZ-415/delete-user-and-owned-agent-media-and-storage-objects).
Deleted-image UI is separate work:
[BUZZ-727](https://linear.app/squareup/issue/BUZZ-727/show-a-clear-unavailable-state-for-deleted-images-in-chat-and-image).
Related: #9353. This replaces the media portion of #9329 and #9355;
those branches remain intact.
Generated with Codex
---------
Signed-off-by: Ravneet Arora <rarora@squareup.com>
Signed-off-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: salad <7be12d8db721c3c6d5feccf11f8389e39c6b4b717dc6aa7ce30fc80e45e8788f@buzz.block.builderlab.xyz>
mobile-v1.4.0-rc.1
|
||
|
|
63f1d6918c |
Refuse opening a private channel that has other members (#9307)
## Summary - Turning a private channel open changes who can read and join it for everyone who joined while it was private. The relay now refuses that change when the channel has, or once had, any other member. - Removed members count too, because their posts stay in the history that opening would make public. - Opening is still allowed when every member, current or removed, is the person making the change or one of that person's agents. A Solo chat that holds only its owner and the owner's agents is the main case. - Changing an open channel to private is unchanged. - A refused change stores nothing. The sender gets: `invalid: a private channel with other members cannot be made open; create a new open channel instead`. ## Details - The check is in the channel metadata edit path (kind:9002), for every channel type. An agent counts as the sender's own only when its owner is recorded for it through an owner attestation (NIP-OA). A member who has never signed in, or an agent with no recorded owner, counts as another member. - The check runs under the membership lock that a visibility change already takes. Members cannot be added between the check and the commit. - Disclosure levels for agents do not exist yet, so all of the sender's own agents may stay when the sender opens a channel. When levels land, restricted writers will need to be excluded. - `update_channel` in the store does not apply this rule. Only tests call it. User edits go through kind:9002. Both doc comments say so. - Old desktop builds can still send an opening edit. They now get the refusal as an error. - `NOSTR.md` documents the refusal on the kind:9002 row. ### Related issue None found. The client UX is in https://github.com/block/buzz-app/pull/3145. ### Testing - New Postgres tests in `edit_metadata_postgres_tests.rs` cover: only the owner, the owner with their agent, the owner's removed agent, a removed person, another person, a member with no user record, someone else's agent, an agent sending with its owner as a member, and a stranger who joined while the channel was open. - Each refused case checks that the channel stays private and nothing is stored. The tests fail when the check is removed, when it skips removed members, or when the user join is made inner. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
df21064800 |
feat(auth): tolerate client clocks up to 120 s off (#9485)
Lets clients whose clocks are up to 120 s off sign in to NIP-FI communities and stay connected. **Relay** - NIP-42 AUTH and NIP-98 HTTP Auth accept `created_at` within ±120 s, using a shared `buzz_auth::TIMESTAMP_TOLERANCE_SECS`. This covers relay login, audio admission, bridge, admin, invites, NIP-FI policy and Git. - `DEFAULT_REPLAY_TTL_SECS` goes from 120 to 250 s: a 2 × 120 s window, plus 1 s for the inclusive whole-second bounds, plus a 9 s budget for the clock difference between relay pods. A compile-time assert checks the arithmetic. The 9 s is an operational assumption about NTP-synced pods, and the doc comment says so. No `deploy/` override exists. - Media (kind 24242): - Both modes accept `created_at` up to 120 s in the future and an `expiration` greater than `now − 120`. - Strict: the 120 s age limit and the 60 s lifetime cap. - Permissive: keeps its 3600 s age allowance and has no lifetime cap. - `buzz-auth` and `buzz-media` read the time through a `wall_now()` that tests can pin (a `#[cfg(test)]` thread-local), so boundary tests are exact. - Git transport: comments only. It still reuses one proof per session, so the reuse window now matches ±120 s. **CLI** - The desktop-provider lane asks the desktop app for the assertion every time and keeps no copy, so the desktop's cache owns each token's deadline. It looks the token up again after signing and sends that one, so a provider may hand out a new token on every call. - The direct-mint cache sets its deadline to `min(request_start + (exp − iat), receipt + (exp − local_now))`, on a monotonic clock. `request_start` is when the attempt that got the reply was sent, not the start of the retry loop. - An assertion with no local lifetime left is never returned or sent. The cache asks again, up to 3 times, then fails with an auth error that points at the computer's clock. An assertion without a readable `iat` is refused. `iat` may be fractional (a NumericDate); the lifetime is `max(0, floor(exp − iat))` whole seconds. **Cache reuse (CLI, Flutter, iOS):** each cached token records when it arrived on both the monotonic and the wall clock. It is reused only while `max(monotonic elapsed, wall elapsed)` since arrival is under its budget (`refresh point − receipt`, on the monotonic clock). A negative wall elapsed counts as 0. The monotonic clocks used here stop while the device sleeps, so the wall clock ends reuse after a sleep; setting the wall clock back can't stretch a token, because the monotonic bound still applies. **Mobile** - Flutter `HostedRelayAuth`: the same lifetime rule, on a monotonic clock, for async acquisition and for the synchronous `cachedHeaders` media path. A token with no local lifetime left is never sent: issuance is retried up to 3 times, then fails as `unavailable`. A token without a readable `iat` fails as `invalidResponse`. - Flutter refusal hint: the account client reads `Date` when a 403's headers arrive, before the body (`boundedHttpResponse` gains an `onHeaders` callback). The 403 stays `AccountFailure.denied` even if its body is then lost, late or too large. The hint is stored with the refusal it explains (`HostedRelayAuth.failureClockHint`), cleared when that community next gets a token or the account session changes, and left alone by other communities' issuance. The account client records a 403's hint only for the acquisition whose own request was refused (`BuilderlabAccountClient.observingRefusals`), so an unrelated account call, such as the organization key backup, never supplies a sign-in's hint. When the offset is over 115 s, the reconnect and organization banners add "Your device's clock looks about N minutes off, which can cause this. Check your date and time settings." - iOS `BuzzRelayAssertionIssuer`: the same lifetime rule, on `systemUptime`. An assertion without a readable `iat` is refused. - iOS push enrollment: a new grant's window starts 120 s in the past, so `not_before = now − 120` and `expires_at = now − 120 + lifetime`. A fast phone then neither signs a `not_before` the gateway hasn't reached nor goes over its 30-day maximum. A resumed journal resubmits the installation expiry it already attested, byte for byte. The delegation, which is signed fresh each time, expires at the earlier of that expiry and `not_before + lifetime`, so a journal written by an older client on a fast phone still gets a grant the gateway accepts. The saved grant records the delegation's expiry. - Flutter and iOS already sign a fresh proof with a `nonce` on every issuer attempt, so their retries needed no change. **Specs:** NIP-FA proof bounds (120 s old / 120 s future), plus NIP-FI Git (`±120s`), media freshness, the media read residual and the media trace row. `desktop/` is untouched. Not exercised live: Git clone/push, audio join and push delivery with a skewed client clock. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
5a45b2cdbe |
docs: name the required stop as a relay build, not a release (#9577)
## Summary `docs/trigger-retirement-deployment.md` (added in #8326) named "the first relay release that contains #8325" as the required stop before migrations 0089–0091. Relay deployments run images built from main, and no tagged relay release contains #8325. So the doc now names any relay build at or after `68785206` (the merge of #8325) as the stop. It also tells deployments on a tagged release, such as `relay-v0.3.0`, to move to a stop build first. This is the follow-up promised in the #8326 review thread. ## Changes - `docs/trigger-retirement-deployment.md`: "stop release" becomes "stop build" throughout. The required-stop section names the commit. The `0089_retire_created_at_floor.sql` comment still says "release". That migration has merged, and editing it would change its sqlx checksum, so it stays as is. ## What got simpler The procedure no longer depends on a release being cut. Operators follow the image they already deploy. ## Testing Docs-only. No code or migration changes. 🤖 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> |
||
|
|
598fcae0cd |
buzz-db: drop the created_at floor, community write-fence and migration-only NIP-RS triggers (contract) (#8326)
> **Combined contract PR.** This PR now carries all three trigger drops that were stacked as #8326 → #8323 → #8211. Each drop's prerequisite app change has already shipped to production, and none of them depends on another, so they ship as one release with one migration per drop: > - `0089`: `events_created_at_floor` (this PR's original scope, BUZZ-316; phase 1 #8325 is on prod) > - `0090`: the universal community write-fence triggers and functions (from #8323, BUZZ-315; app admission #8219/#8318/#8322) > - `0091`: the migration-only NIP-RS, mention-live and mesh-purge triggers (from #8211, BUZZ-312; prerequisite #8128) > > #8323 and #8211 keep their full write-ups. The commits are cherry-picked unchanged except for the renumbering commit at the tip. #8211's post-rollout cleanup SQL still runs after this deploys. ## Summary Phase 2 of BUZZ-316. This is a destructive contract change. Phase 1, #8325 (merged), added the insert-time application floor check. After phase 1, the app check at every channel-bearing `INSERT INTO events` is the only `created_at` floor guard. This PR removes the database backstop and everything that existed only to verify it: - **Migration 0089** drops the deferred constraint trigger `events_created_at_floor` on `events`. That also removes its partition clones. It then loops over `pg_partition_tree('events')` to drop any child copy that was attached separately, and drops the `events_created_at_floor_guard()` function. Every drop uses `IF EXISTS` and none uses `CASCADE`. The migration sets `lock_timeout` to 5s. Migration 0021 stays byte-for-byte unchanged. - **Desired state:** removes the function file, its `schema.sql` include, the trigger in `schema/triggers/events.sql`, and the eight child-copy drops in `scripts/reconcile-schema-after-pgschema.sql`. Both boot paths stay catalog-equivalent, and `admin_schema_parity_between_desired_state_and_migrations` passes. - **Runtime:** deletes `verify_floor_guard_catalog`, `verify_floor_guard_behavior`, and the boot wrapper that gated the probe on them. Also deletes the writer-pool `buzz.created_at_floor` GUC arming and its `CreatedAtFloor` connection-setup metric step. The setup-series ceiling drops from 71 to 54. `spawn_fence_probe` becomes synchronous and returns `bool`, so the relay's startup error branch goes away. `CREATED_AT_FLOOR_SECS` (960s) stays because the app check and the fence wall both use it. - **Kept:** every other fail-closed probe check. That covers writer-pool isolation and timeouts, partition topology, the activity scan, the heartbeat/epoch checks, and closing on probe error. No other trigger, function, FK, or tenant fence is touched. ## Deploy gate (required) **Required stop:** the new `docs/trigger-retirement-deployment.md` names it (docs/database.md Rule 5). Relay deployments track images built from `main` and no release is being cut, so a docs follow-up rewords it as any relay build at or after `68785206` (#8325's merge). `relay-v0.3.0` has the 0090/0091 prerequisites but not #8325, so a deployment on it must move to such a build first. The doc also covers the auto-migration-off order, the pgschema parent-trigger note, the #8211 cleanup, and rollback. 1. Phase 1 must be running on **every** writer pod and job, with no rollback expected. Pods that are already running never recheck the guard, so a rolling deploy on its own is not enough. 2. Stop out-of-band writers: direct SQL, COPY, restores, seed scripts, and anything that prepares transactions. 3. Hold the replica breaker closed from before the drop until replay catches up and the new scheme is verified. 4. Run the migration off-peak. `DROP TRIGGER` takes `ACCESS EXCLUSIVE` on `events` and every partition, so expect `events` reads and writes to stall for up to the 5s `lock_timeout`. A lock timeout aborts the migration transaction and is safe to retry. Under auto-migrate, the pod fails boot, restarts, and retries. Mixed-version behavior: - **A phase-1 pod that restarts after the drop, default config (`migrate.autoMigrate: true` in the chart):** sqlx finds applied migration 89 missing from its embedded set and returns `VersionMissing(89)`. Boot is fatal and the pod **crash-loops**. A binary rollback is therefore unsafe once 0089 has run. - **The same pod with auto-migrate off:** `verify_floor_guard_catalog` fails, the fence starts closed, and the relay degrades the `ReplicaFenceProbe` startup step. It keeps serving, with cursor reads on the writer. - **This binary against a database that still has the trigger:** boots and runs. It neither requires nor arms the guard. ## Tests `crates/buzz-db/src/runtime/tests/floor_retirement.rs` adds four PostgreSQL tests. CI's nextest filter picks them up through `postgres_tests::`: - the migration drops the parent trigger, its partition clones, and the function, and leaves every other trigger and FK unchanged; - the migration removes a separately attached child copy and can safely run twice; - the desired-state catalog has no floor objects; - the production writer pool no longer arms the GUC, and the probe runs against the retired schema. All four fail when the change is reverted (0/4 pass) and pass with it (4/4). Four tests that only exercised the trigger or the probes are deleted. The outbox durable-failure regression is kept: it now injects an isolated `BEFORE INSERT` failure instead of arming the floor. The phase-1 floor fixture no longer disables a trigger that no longer exists. It still asserts that no enabled floor trigger can mask the app check. With the trigger gone, the floor source policy (`every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it`) is the only guard against a writer that skips the app check or rewrites `created_at`/`channel_id` on an existing row. Phase 1 already makes it scan every crate's `src`. This PR closes two matcher gaps the trigger used to cover: - `UPDATE events SET(created_at, …)` written with no space before the parenthesis; - `INSERT INTO events … ON CONFLICT … DO UPDATE SET channel_id = …`, which names no table but can re-home an existing row below the floor. Each `DO UPDATE` is bound to the INSERT it belongs to, so a watermark upsert that sets `created_at` next to a guarded events insert (the replaceable-event writer's shape) is not flagged. Both gaps have negative fixtures, plus controls for a non-floor-column upsert, `DO NOTHING`, and the watermark shape. The policy also now fails closed on SQL the per-function literal scan could not attribute to a writer (`event_floor_policy_fails_closed_on_sql_it_cannot_attribute`): - `include_str!` is expanded from the file it loads, and `concat!` becomes one literal, with an `{opaque}` placeholder for each non-literal argument. Every delimiter (`()`, `[]`, `{}`) and path prefix (`::core::concat!`) is recognized. - Every SQL literal is checked on its own as well as per function. Anything the policy cannot attribute is a violation: a write target or `SET` column that is a placeholder (`concat!` or `format!`); a `SET` list of floor columns whose `UPDATE` is in another literal; an `UPDATE events` or `DO UPDATE` whose `SET` list continues in another literal or argument (empty, or an item with no `=`, as in `format!("UPDATE events SET {}", …)` or `QueryBuilder::new("UPDATE events SET ").push(…)`); an `INSERT INTO` with no table after it in the literal, or an events INSERT with a placeholder tail; `events` written by `MERGE INTO`/`COPY`; and event-write SQL in a `const`, `static`, or macro body outside any function. A placeholder in a `WHERE` or a value is allowed, so the retention deletes (`concat!` around a predicate macro) and the tenant-severing `UPDATE {table} SET community_id = NULL` pass. - An `include_str!` whose path is not one readable literal and any sqlx `query_file*!` macro are violations. Nothing uses `query_file`. - `PREPARE TRANSACTION` in any production literal, including a dangling `PREPARE`, is a violation (see below). - Function slices are cut to their own item, so a trailing `const` is judged at item level instead of being credited to the function before it. **Prepared transactions.** The fence used to bound a prepared (2PC) transaction by `pg_prepared_xacts.prepared`. That only held because the deferred trigger checked its rows at `PREPARE`; the insert-time check runs earlier, at a time `pg_prepared_xacts` does not expose. So the probe no longer folds `prepared` into the wall: any prepared transaction fails the sample closed (`ProbeError::PreparedTransactions`). No supported writer prepares transactions (now source-policy enforced) and `max_prepared_transactions` defaults to 0, so in supported deployments this never fires. `cluster_global_sample_writer_fails_closed_on_prepared_transaction` asserts 2PC is unavailable at the default setting, and asserts the fail-closed error when the server allows it. CI runs only the default branch; the 2PC-enabled branch and a check-removed falsification run are pinned from the Blox gate. The prepared count is cluster-wide, like the activity scan. ## Verification Head `6ef31ef113` (before the fold). On Blox, fmt, clippy and buzz-db unit pass, and the full buzz-db PostgreSQL lane passes except `media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`, which fails only on the Blox host (it passes in CI). The two `floor_retirement` tests were fixed after that run, so they were rerun on their own and pass at this head. ## What got simpler The change is net −600 lines. Gone are one function, one parent constraint trigger plus its partition clones, two startup probes and their scratch helper, one boot wrapper, the per-connection GUC setup, one metric step, and an async startup branch that could no longer be reached. ## Notes - Migration number: `0089`, the first free number after main's `0088` (workflow run cause). The fence drop (`0090`) and NIP-RS drop (`0091`) follow it in this PR. - Restack: `floor_retirement.rs` now snapshots at `0088` and compares after `0089` alone, then runs the later migrations. The held-writer media prebuild test in `migration.rs` now stops at `0088` while the writer is held, then rolls the writer back before applying the rest. Otherwise a later `DROP TRIGGER` migration in the stack waits on that writer's lock (`55P03`). The floor policy's `SET` list ends at a top-level `WHERE` or `RETURNING` (a subquery's `WHERE` no longer hides later assignments). An `UPDATE` `SET` list that runs to the end of its literal fails closed, and an open events upsert list is read on through later literals (`QueryBuilder` pushes). `events_p*` partitions count as `events` in every check. `replacement_scope!` now leaves `WHERE` to its callers so the policy can see the supersede `UPDATE`'s list end; the SQL is unchanged. - Pre-existing, unrelated to this change: three `buzz-relay` `group_state_postgres_tests` hit `PoolTimedOut` on a clean base too. --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |