Commit Graph

976 Commits

Author SHA1 Message Date
Luke Tornquist
3d97535120 buzz-db: check workflow references in app code before FK retirement (#9399) 2026-11-16 20:15:09 -05:00
Taylor Ho
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>
2026-11-16 17:13:28 -08:00
morgmart
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 990f8b2ed: the 36 handler tests, SDK and CLI tests, clippy (`-D
warnings`) and fmt pass, and the push passed the full pre-push hook.
Every guard added in review was mutation-checked. The lost-insert race
and the stale-member fork are forced with explicit lock waits, not
timing.
- Not yet done: exercising it against a running local relay, and a human
test.

Human test steps (local relay + app on the paired app branch): open a DM
with one person, open its access dialog, add a second person and choose
**Include history**: they join the same DM and see earlier messages;
then message only the original person: a new DM opens. Add a person with
**Start new DM**: a new DM of the people opens, without any agents, and
the original is unchanged. Add an agent: it joins the same DM directly.
In a DM with only you and an agent, add a person: a new DM of you and
that person opens without a question, and the agent DM is unchanged.
Leave a group DM: you're removed, and messaging the group again starts a
new DM.

🤖 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>
2026-11-16 17:01:55 -08:00
yissachar
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>
2026-11-16 17:18:19 -06:00
Helen Tian
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>
2026-11-17 09:01:59 +11:00
Sanket Kanjalkar
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>
2026-11-16 12:20:12 -08:00
klopez4212
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>
2026-11-16 19:15:27 +00:00
ravarora2
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>
2026-11-16 13:13:39 -05:00
Logan Johnson
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>
2026-11-16 17:39:19 +00:00
Will Pfleger
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>
2026-11-16 12:17:14 -05:00
Luke Tornquist
598fcae0cd buzz-db: drop the created_at floor, community write-fence and migration-only NIP-RS triggers (contract) (#8326)
> **Combined contract PR.** This PR now carries all three trigger drops
that were stacked as #8326 → #8323 → #8211. Each drop's prerequisite app
change has already shipped to production, and none of them depends on
another, so they ship as one release with one migration per drop:
> - `0089`: `events_created_at_floor` (this PR's original scope,
BUZZ-316; phase 1 #8325 is on prod)
> - `0090`: the universal community write-fence triggers and functions
(from #8323, BUZZ-315; app admission #8219/#8318/#8322)
> - `0091`: the migration-only NIP-RS, mention-live and mesh-purge
triggers (from #8211, BUZZ-312; prerequisite #8128)
>
> #8323 and #8211 keep their full write-ups. The commits are
cherry-picked unchanged except for the renumbering commit at the tip.
#8211's post-rollout cleanup SQL still runs after this deploys.

## Summary

Phase 2 of BUZZ-316. This is a destructive contract change. Phase 1,
#8325 (merged), added the insert-time application floor check.

After phase 1, the app check at every channel-bearing `INSERT INTO
events` is the only `created_at` floor guard. This PR removes the
database backstop and everything that existed only to verify it:

- **Migration 0089** drops the deferred constraint trigger
`events_created_at_floor` on `events`. That also removes its partition
clones. It then loops over `pg_partition_tree('events')` to drop any
child copy that was attached separately, and drops the
`events_created_at_floor_guard()` function. Every drop uses `IF EXISTS`
and none uses `CASCADE`. The migration sets `lock_timeout` to 5s.
Migration 0021 stays byte-for-byte unchanged.
- **Desired state:** removes the function file, its `schema.sql`
include, the trigger in `schema/triggers/events.sql`, and the eight
child-copy drops in `scripts/reconcile-schema-after-pgschema.sql`. Both
boot paths stay catalog-equivalent, and
`admin_schema_parity_between_desired_state_and_migrations` passes.
- **Runtime:** deletes `verify_floor_guard_catalog`,
`verify_floor_guard_behavior`, and the boot wrapper that gated the probe
on them. Also deletes the writer-pool `buzz.created_at_floor` GUC arming
and its `CreatedAtFloor` connection-setup metric step. The setup-series
ceiling drops from 71 to 54. `spawn_fence_probe` becomes synchronous and
returns `bool`, so the relay's startup error branch goes away.
`CREATED_AT_FLOOR_SECS` (960s) stays because the app check and the fence
wall both use it.
- **Kept:** every other fail-closed probe check. That covers writer-pool
isolation and timeouts, partition topology, the activity scan, the
heartbeat/epoch checks, and closing on probe error. No other trigger,
function, FK, or tenant fence is touched.

## Deploy gate (required)

**Required stop:** the new `docs/trigger-retirement-deployment.md` names
it (docs/database.md Rule 5). Relay deployments track images built from
`main` and no release is being cut, so a docs follow-up rewords it as
any relay build at or after `68785206` (#8325's merge). `relay-v0.3.0`
has the 0090/0091 prerequisites but not #8325, so a deployment on it
must move to such a build first. The doc also covers the
auto-migration-off order, the pgschema parent-trigger note, the #8211
cleanup, and rollback.

1. Phase 1 must be running on **every** writer pod and job, with no
rollback expected. Pods that are already running never recheck the
guard, so a rolling deploy on its own is not enough.
2. Stop out-of-band writers: direct SQL, COPY, restores, seed scripts,
and anything that prepares transactions.
3. Hold the replica breaker closed from before the drop until replay
catches up and the new scheme is verified.
4. Run the migration off-peak. `DROP TRIGGER` takes `ACCESS EXCLUSIVE`
on `events` and every partition, so expect `events` reads and writes to
stall for up to the 5s `lock_timeout`. A lock timeout aborts the
migration transaction and is safe to retry. Under auto-migrate, the pod
fails boot, restarts, and retries.

Mixed-version behavior:
- **A phase-1 pod that restarts after the drop, default config
(`migrate.autoMigrate: true` in the chart):** sqlx finds applied
migration 89 missing from its embedded set and returns
`VersionMissing(89)`. Boot is fatal and the pod **crash-loops**. A
binary rollback is therefore unsafe once 0089 has run.
- **The same pod with auto-migrate off:** `verify_floor_guard_catalog`
fails, the fence starts closed, and the relay degrades the
`ReplicaFenceProbe` startup step. It keeps serving, with cursor reads on
the writer.
- **This binary against a database that still has the trigger:** boots
and runs. It neither requires nor arms the guard.

## Tests

`crates/buzz-db/src/runtime/tests/floor_retirement.rs` adds four
PostgreSQL tests. CI's nextest filter picks them up through
`postgres_tests::`:
- the migration drops the parent trigger, its partition clones, and the
function, and leaves every other trigger and FK unchanged;
- the migration removes a separately attached child copy and can safely
run twice;
- the desired-state catalog has no floor objects;
- the production writer pool no longer arms the GUC, and the probe runs
against the retired schema.

All four fail when the change is reverted (0/4 pass) and pass with it
(4/4). Four tests that only exercised the trigger or the probes are
deleted. The outbox durable-failure regression is kept: it now injects
an isolated `BEFORE INSERT` failure instead of arming the floor. The
phase-1 floor fixture no longer disables a trigger that no longer
exists. It still asserts that no enabled floor trigger can mask the app
check.

With the trigger gone, the floor source policy
(`every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it`)
is the only guard against a writer that skips the app check or rewrites
`created_at`/`channel_id` on an existing row. Phase 1 already makes it
scan every crate's `src`. This PR closes two matcher gaps the trigger
used to cover:

- `UPDATE events SET(created_at, …)` written with no space before the
parenthesis;
- `INSERT INTO events … ON CONFLICT … DO UPDATE SET channel_id = …`,
which names no table but can re-home an existing row below the floor.
Each `DO UPDATE` is bound to the INSERT it belongs to, so a watermark
upsert that sets `created_at` next to a guarded events insert (the
replaceable-event writer's shape) is not flagged.

Both gaps have negative fixtures, plus controls for a non-floor-column
upsert, `DO NOTHING`, and the watermark shape.

The policy also now fails closed on SQL the per-function literal scan
could not attribute to a writer
(`event_floor_policy_fails_closed_on_sql_it_cannot_attribute`):

- `include_str!` is expanded from the file it loads, and `concat!`
becomes one literal, with an `{opaque}` placeholder for each non-literal
argument. Every delimiter (`()`, `[]`, `{}`) and path prefix
(`::core::concat!`) is recognized.
- Every SQL literal is checked on its own as well as per function.
Anything the policy cannot attribute is a violation: a write target or
`SET` column that is a placeholder (`concat!` or `format!`); a `SET`
list of floor columns whose `UPDATE` is in another literal; an `UPDATE
events` or `DO UPDATE` whose `SET` list continues in another literal or
argument (empty, or an item with no `=`, as in `format!("UPDATE events
SET {}", …)` or `QueryBuilder::new("UPDATE events SET ").push(…)`); an
`INSERT INTO` with no table after it in the literal, or an events INSERT
with a placeholder tail; `events` written by `MERGE INTO`/`COPY`; and
event-write SQL in a `const`, `static`, or macro body outside any
function. A placeholder in a `WHERE` or a value is allowed, so the
retention deletes (`concat!` around a predicate macro) and the
tenant-severing `UPDATE {table} SET community_id = NULL` pass.
- An `include_str!` whose path is not one readable literal and any sqlx
`query_file*!` macro are violations. Nothing uses `query_file`.
- `PREPARE TRANSACTION` in any production literal, including a dangling
`PREPARE`, is a violation (see below).
- Function slices are cut to their own item, so a trailing `const` is
judged at item level instead of being credited to the function before
it.

**Prepared transactions.** The fence used to bound a prepared (2PC)
transaction by `pg_prepared_xacts.prepared`. That only held because the
deferred trigger checked its rows at `PREPARE`; the insert-time check
runs earlier, at a time `pg_prepared_xacts` does not expose. So the
probe no longer folds `prepared` into the wall: any prepared transaction
fails the sample closed (`ProbeError::PreparedTransactions`). No
supported writer prepares transactions (now source-policy enforced) and
`max_prepared_transactions` defaults to 0, so in supported deployments
this never fires.
`cluster_global_sample_writer_fails_closed_on_prepared_transaction`
asserts 2PC is unavailable at the default setting, and asserts the
fail-closed error when the server allows it. CI runs only the default
branch; the 2PC-enabled branch and a check-removed falsification run are
pinned from the Blox gate. The prepared count is cluster-wide, like the
activity scan.

## Verification

Head `6ef31ef113` (before the fold). On Blox, fmt, clippy and buzz-db
unit pass, and the full buzz-db PostgreSQL lane passes except
`media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`,
which fails only on the Blox host (it passes in CI). The two
`floor_retirement` tests were fixed after that run, so they were rerun
on their own and pass at this head.

## What got simpler

The change is net −600 lines. Gone are one function, one parent
constraint trigger plus its partition clones, two startup probes and
their scratch helper, one boot wrapper, the per-connection GUC setup,
one metric step, and an async startup branch that could no longer be
reached.

## Notes

- Migration number: `0089`, the first free number after main's `0088`
(workflow run cause). The fence drop (`0090`) and NIP-RS drop (`0091`)
follow it in this PR.
- Restack: `floor_retirement.rs` now snapshots at `0088` and compares
after `0089` alone, then runs the later migrations. The held-writer
media prebuild test in `migration.rs` now stops at `0088` while the
writer is held, then rolls the writer back before applying the rest.
Otherwise a later `DROP TRIGGER` migration in the stack waits on that
writer's lock (`55P03`). The floor policy's `SET` list ends at a
top-level `WHERE` or `RETURNING` (a subquery's `WHERE` no longer hides
later assignments). An `UPDATE` `SET` list that runs to the end of its
literal fails closed, and an open events upsert list is read on through
later literals (`QueryBuilder` pushes). `events_p*` partitions count as
`events` in every check. `replacement_scope!` now leaves `WHERE` to its
callers so the policy can see the supersede `UPDATE`'s list end; the SQL
is unchanged.
- Pre-existing, unrelated to this change: three `buzz-relay`
`group_state_postgres_tests` hit `PoolTimedOut` on a clean base too.

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:49:29 -05:00
Phil Azar
db7d37107a Keep community deletion working across a new tenant table's migration (#9304)
## Why

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

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

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

## What

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

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

## Evidence

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

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

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

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

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

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

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

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

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

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

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

## Limits

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

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

Signed-off-by: Philip Azar <pazar@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:57:23 -06:00
Tom Brow
9398918fa5 feat(push-gateway): accept deliveries on a platform-neutral route (#9557)
First slice of the Android push plan ([design
PR](https://github.com/block/buzz/pull/9555)). The push gateway should
serve every platform from one delivery route, so the relay never learns
an installation's platform (see ADR 0004 in the design PR).

### What changes

- The gateway accepts deliveries at `POST /v1/deliveries`. `POST
/v1/deliveries/apns` keeps working unchanged as an alias until relays
have moved over.
- `BUZZ_PUSH_GATEWAY_DELIVERY_URL` accepts either path. The deployment
guide and NIP-PL describe `/v1/deliveries` as the route to use.
`.env.example` and the compose template stay on `/v1/deliveries/apns`,
because released relays (`relay-v0.3.0` and older `sha-` images) refuse
to start with the new path even with push disabled, and the public
gateway doesn't route it yet. A later change moves them over.
- Signature binding: the gateway already verified only the method and
the signed URL's path (not scheme, host or port). It compared that path
to a constant. It now compares it to the route the request arrived on,
so a request signed for one route is rejected on the other. Each route
accepts only requests signed for its own path.
- The lease `transport` value, priority classes and the delivery request
body are unchanged, and nothing about the device platform reaches the
relay.

### Regressions

None expected. iOS keeps working: the alias route behaves exactly as
before, and relays configured with the old URL keep signing and sending
to it. The signed path check is equivalent on that route, since it now
compares against the same path the old constant held.

Rollout order matters. Don't point a relay at `/v1/deliveries` until (1)
its gateway runs this change and (2) for `push.buzz.xyz`, the edge path
allowlist in front of the gateway admits `/v1/deliveries`. Today that
edge answers `403 RBAC: access denied` there. The relay also needs a
build that includes this parser. An old gateway's 404 or the edge's 403
is a permanent failure for the relay (on a retry, it counts as
replay-terminal), so those notifications are dropped, not retried.

### Validation

- Gateway delivery tests are table-driven across both routes:
path-not-origin binding, signed URL modifiers and non-HTTP schemes,
request queries, method and path routing, and new cross-route rows
(signed for `/v1/deliveries`, sent to the alias, and the reverse, both
rejected).
- Relay config tests cover both paths over HTTP and HTTPS, plus rejected
variants (trailing slash, query, fragment, credentials, other paths,
HTTPS ports).
- Ran the gateway crate's tests, the relay crate's unit tests
(single-threaded, because the default parallel run of the whole lib hung
in untouched tests waiting on shared env locks), formatting and clippy
for both crates, and the repository's pre-push checks.
- Relay tests that need Postgres were not run locally.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-16 10:47:54 -05:00
Will Pfleger
69742376a9 Revert "feat(relay): agents cannot write in DMs except with their own… (#9500)
…er (#9371)"

This reverts commit a09b84d23d, resolved
against current main (#9227 changed the neighboring workflow_sink
tests).

Supersedes https://github.com/block/buzz/pull/9393

Signed-off-by: Joah Gerstenberg <joah@squareup.com>
Co-authored-by: Joah Gerstenberg <joah@squareup.com>
Co-authored-by: Hertz <c6741012416ef5c49a865db79682113385c5fb998e8c890234fb442b59e22748@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:28:19 -05:00
Tom Brow
fc29f6068a fix(relay): stamp each NIP-IA archive list strictly after the previous one (#9476)
### Why

When an admin archives or unarchives an identity, the relay publishes a
new archived identities list (kind 13535). This list replaces the
previous one. It contains all the identities that are archived in the
community. Clients use it to hide archived agents from pickers and
search.

The list can be large (about 228 KB on Block's Builderlab), and it
seldom changes. Thus the mobile app wants to download it only when it
changed. To do this, the app keeps the last list it received, and asks
the relay only for a list that is newer than that one (`since` its
`created_at` plus one, in [#9445 archive list
cache](https://github.com/block/buzz/pull/9445)).

This works only if each new list has a `created_at` that is later than
the previous list's. Today the relay does not always do this:

- The relay calculates the new list's `created_at` as "the current
list's `created_at` plus one second". But it reads the current list
before it gets the lock that controls replacement.
- Thus, when two archive requests occur at the same time, two publishers
can read the same current list. Then both sign a list with the same
`created_at`. The store keeps the one with the lower event id.
- A client that already has the other list does not see the replacement,
because it asks only for lists with a later `created_at`. It continues
to hide or show the wrong agents until the next archive change or an app
restart.
- With many concurrent publishers it is worse: a publisher can lose that
tie again and again, and then stop with `failed to publish kind:13535
after 8 concurrent replacements`. Then no list contains the latest
archive change.

### What changes

- New `Db::replace_addressable_event_after_head`. It gets the
replacement lock first. Then it reads the current list. Then it signs
and stores the new list. Thus only one publisher at a time calculates
the next `created_at`, and each list is stamped strictly later than the
previous one.
- `publish_nipia_archival_list` uses this method. The check that
publishes again when the archive state changed during a publish does not
change.
- NIP-IA now makes this a rule: a relay MUST publish each `kind:13535`
with a `created_at` strictly greater than its previous one. Clients MAY
then ask only for lists `since` their list's `created_at` plus one.

### Validation

New relay test: 16 concurrent publishers all complete, and each stored
list (superseded rows included) has a strictly later `created_at`. On
main the same test fails, because a publisher uses all its retries. The
test needs Postgres and Redis, so it is in `postgres_tests` and runs in
the PostgreSQL Tests lane; a missing database or Redis makes it fail,
not pass. The existing archive tests pass against a local Postgres,
including the stale-publisher test. `just test` passes all 160 steps
except one NIP-FI session deadline test
(`deadline_refused_permit_still_queues_one_denial_when_cancel_wins`),
which this change does not touch and which passes 5 of 5 reruns alone.
Clippy passes.

### Regressions

None expected.

- A publisher now holds the replacement lock a little longer: for one
read and one signature. Only archive-list writes for the same community
wait on this lock, and archive changes are rare.
- The new `Db` method is an addition. `replace_addressable_event` and
its callers do not change.
- Until this is deployed, relays keep the old behavior. [#9445 archive
list cache](https://github.com/block/buzz/pull/9445) accepts that
same-second case on its own.

**Accepted limitation: a database restore.** The rule holds only while
the relay keeps its newest list. If an operator restores the relay from
a backup, the relay calculates the next `created_at` from the restored
list (`max(restored + 1, now)`). If earlier fast publishes went ahead of
the clock, that value can be at or below a `created_at` that a client
already has. That client then stays stale until a list passes its cached
`created_at`, or the app restarts. This change adds no repair for a
restore.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-14 09:21:19 -08:00
Sanket Kanjalkar
5780bd7d94 perf(acp): avoid repeated observer batch serialization (#9483)
Replaces #9413 with the packing optimization refreshed against main on a
branch in this repository.

## Summary

Busy agent activity streams repeatedly build and serialize a growing
JSON batch just to check whether the next event fits. Reuse cached event
sizes, measure the newest outer envelope, and build the batch payload
once per completed frame.

Preserve the wire format, greedy packing, per-channel order, channel
barriers, byte budget, and one-frame-per-second relay cadence.
Exact-limit coverage checks escaping, UTF-8, optional metadata, and
array separators. Move the queue tests into a separate module to satisfy
the file-size rule; their test names stay unchanged.

### Related issue

Related to #7987. This builds on the merged fitting/locking work in
#9381 and retention limits in #9436. Closest earlier batching work:
#4917. No duplicate packing fix found among open PRs.

### Testing

The ignored probe fills the production queue before timing, drains every
event, and checks complete FIFO delivery, frame byte limits, and empty
byte accounting.

```sh
CARGO_INCREMENTAL=0 CARGO_PROFILE_RELEASE_LTO=thin CARGO_PROFILE_RELEASE_CODEGEN_UNITS=4 \
  cargo test --release -p buzz-acp --lib observer::packing_tests::publish_queue_drain_probe -- \
  --exact --ignored --nocapture

BUZZ_OBSERVER_PROBE_EVENTS=100 cargo test --release -p buzz-acp --lib \
  observer::packing_tests::publish_queue_drain_probe -- --exact --ignored --nocapture
```

Five alternating fresh release processes per arm and workload compared
baseline `59ae028a3` with candidate `237b928b9` on macOS arm64, Rust
1.98.1. Both arms used `opt-level=3`, thin LTO and four codegen units,
with incremental compilation and compiler-cache wrappers off. Each
executable was rebuilt separately and its probe identity verified.
Medians:

| Events | Before | After | Frames in both arms |
| --- | ---: | ---: | ---: |
| 100 | 6.760 ms | 0.108 ms | 1 |
| 10,000 | 1,597.509 ms | 7.844 ms | 30 |

The one-event control measured 2.04 → 2.21 microseconds. The timed
region covers packing only; ingestion, validation, encryption, publish
pacing, relay delivery, and rendering are excluded. These local results
do not establish an overall app latency improvement. No timing threshold
was added to CI.

Native and deployed-relay latency, independent review, and human
verification remain pending. Keep this PR in draft.

Generated with AI assistance

Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com>
Co-authored-by: Codex <codex@openai.com>
2026-11-13 17:39:22 -08:00
Matt Toohey
97188e90c6 test(cli,db): freeze the assertion test clock and give pool release tests a test-lane acquire budget (#9442)
## Summary
Two Rust tests failed on loaded CI runners because their timing budget
came from the wall clock or from a production timeout, not from the
behavior they assert. Each fix changes only test code or `cfg(test)`
code.

Commits (cherry-picked unchanged from a local flake-fix series):
- `test(cli): freeze the test clock in the assertion refresh tests`
- `test(db): give the pool release Postgres tests a test-lane acquire
budget`

### Root cause and fix per test


**`federated_identity::tests::short_and_long_assertions_refresh_at_the_earlier_point`**
and its twin in `desktop_provider` (`crates/buzz-cli`): failed in CI
with `assertion left == right failed: lifetime 300`, left 2, right 1, at
`federated_identity.rs:634`.

- CI sighting, 11 November 2026, "Rust / Unit Tests", run 43122921918
attempt 1 (on #9342; the rerun passed):
-
https://github.com/block/buzz/actions/runs/43122921918/job/130868244938
- Root cause: under `cfg(test)`, `cached_assertion::unix_now()` was the
wall clock plus a thread-local skew. The mock stamps `exp = unix_now() +
lifetime`, then `CachedAssertion::get` computes `refresh_at(unix_now(),
exp)` after the HTTP round trip, and the next call checks `unix_now() <
refresh`. The test needed those reads to agree to the second. When the
wall clock crossed a second boundary between them, the refresh point
moved 1 s earlier, `advance(refresh - 1)` landed exactly on it, and the
assertion was minted one step early.
- Fix: a thread-local `FROZEN` base beside `SKEW`, and
`test_clock::freeze(at)` to pin it. Under `cfg(test)`, `unix_now()`
returns `FROZEN.unwrap_or(real_now) + SKEW`, so `advance` and its
existing callers in `client.rs` behave as before. Both tests freeze the
clock at the top of their loop body. The mock adapter runs on the same
current-thread runtime, so `exp`, `refresh_at` and the check share one
"now". Production code paths are unchanged.
- Verification: each test run 1,440 times, 24 in parallel, before and
after. `federated_identity`: 4 failures before, 0 after.
`desktop_provider`: 1 failure before, 0 after.
- Not seen in CI: the `desktop_provider` twin. It passed in the job
above and is fixed here because it has the same race and failed locally.


**`runtime::postgres_tests::pool_release_postgres_tests::silence_after_release_hook_does_not_strand_sqlx_ping`**
(`crates/buzz-db`): panicked at `pool_release_postgres_tests.rs:204:10`
with ``called `Result::unwrap()` on an `Err` value: PoolTimedOut`` after
0.85 s.

- CI sighting, 10 November 2026, "PostgreSQL Domain / PostgreSQL Tests",
run 42851548618 attempt 1 (on #8317; the rerun passed):
-
https://github.com/block/buzz/actions/runs/42851548618/job/129969964659
- Root cause: the test built its pool from the production
`Db::read_pool_options`, whose 150 ms `READER_ACQUIRE_TIMEOUT` also
bounded `connect_with`'s eager first dial (and `fresh_query`'s). On a
busy runner the cold dial through `PausingProxy`, SCRAM and the reader
`after_connect` hook overran it, so the test panicked at the initial
`connect_with(...).unwrap()` before the release-hook recovery path it
asserts ever ran. Production is not exposed: the relay dials the reader
pool lazily, so that budget only governs request-time acquires, which
fall back to the writer by design.
- Fix: a 30 s `TEST_LANE_ACQUIRE_TIMEOUT` on both pool builders in this
file: the reader test's `PoolOptions`, and `writer_pool`'s `DbConfig`,
whose eagerly dialed 3 s default is the same exposure #9273 fixed for
buzz-admin. `test_before_acquire(false)`, `after_connect` and
`after_release` stay as in production, and recovery still completes at
sqlx's 5 s return deadline inside the test's 10 s `await_capacity`
budget. No assertions change.
- Verification, against a local Postgres: 10 rounds of
`pool_release_postgres_tests --ignored --test-threads=6` per binary.
Before, 2 of 10 rounds failed at `:204:10` with `PoolTimedOut`, the CI
signature. After, 0 of 10. Under 28 CPU busy loops, with before and
after runs interleaved: 6 of 10 failed before, 0 of 10 after.
- Not done here: `reader_pool_postgres_tests.rs` already carries its own
5 s test budget on `read_pool_options` for the same reason. This PR does
not unify the two constants.

One sighting of each failure was found in the CI runs from 7 to 12
November 2026 that were searched.

### Related issue
N/A (flake fixes). No existing issue was found, and no open PR touches
these tests or the four files changed here.

### Testing
Human testing is still required. This PR does not carry
`buzz-review-completed`; the author has not yet run these tests
themselves on this branch.

The repetition counts above were measured when the fixes were written,
before this branch was split out. They were not repeated on this branch.

#### Local checks on this branch
The branch is one commit behind `main`; that commit changes only mobile
and docs files, none of them touched here.

Ran and passed at push time, on a checkout of this branch's head
(`42b3faccc`): the organization push check, `branch-skew`,
`push-head-scope`, `file-size-check` and git-lfs.

Did not run:
- The `rust-tests` and `desktop-tauri-checks` pre-push lanes. They were
excluded from the push (`LEFTHOOK_EXCLUDE`) because the machine ran out
of disk part-way through them on an earlier attempt. That attempt did
not complete, so it proves nothing either way about this branch.
- The desktop and mobile pre-push lanes (`desktop-check`,
`desktop-typecheck`, `desktop-test`, `mobile-checks`). This diff touches
no desktop or mobile file.
- `cargo fmt --check`, `cargo clippy`, `just ci`, and the PostgreSQL
lane.

CI's Unit Tests and PostgreSQL Tests jobs are the gate for this branch.
A green run does not prove the flakes are gone: both failures need a
loaded runner.

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

---------

Signed-off-by: mtoohey <mtoohey@squareup.com>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-14 11:45:11 +11:00
Ian Oberst
359839f70b feat(db): label advisory-lock metrics with the locked event kind (#9472)
## Why

On one deployment,
`buzz_db_advisory_lock_wait_seconds{lock_type="replacement"}` added up
to about 245,000 seconds of wait in 7 days. The metric cannot say which
coordinates wait. Replacement locks serialize writers of one `(kind,
pubkey[, d_tag | channel])` coordinate. Relay-owned lists (kinds 13535,
39000–39002) go through the same generic replacement paths as user
replaceables (kinds 0, 3, 10002, 30078, …). The 13534 membership list
takes its coordinate lock under `lock_type="membership"`. Before we
change how these lists are stored, we need to know which kinds the wait
comes from.

## What

- `buzz_db_advisory_lock_wait_seconds` and
`buzz_db_advisory_lock_acquisitions_total` get a `kind` label.
- Locks keyed by an event coordinate record that coordinate's kind,
through the new `observe_event_lock(lock_type, kind, …)`. This covers
all 4 replacement call sites (parameterized replace,
`take_replacement_lock` for addressable replace and group-state
snapshots, the kind:39002 member snapshot, and workflow deletion) and
the kind:13534 membership-list lock. The 13534 lock keeps
`lock_type="membership"`, so totals by `lock_type` do not change.
- All other locks record `kind="none"`, and their call sites do not
change. `observe_advisory_lock` has a `debug_assert` that rejects
`LockType::Replacement`, so a replacement lock cannot lose its kind by
mistake.
- `buzz_core::kind::registered_kind_label(kind)` gives the label value:
the decimal kind when it is in `ALL_KINDS`, otherwise `other`.

## Change to the #6700 label contract

#6700 says no database metric carries event kinds, and
`observability_source.rs` enforces this with a blanket ban on `"kind"
=>`. This PR makes one narrow exception: the two advisory-lock metrics.

- **Bounded:** the value set is the kind registry, not request data. Of
the 135 registered kinds, 39 are replaceable or addressable and can
reach a replacement lock. Any other kind a client sends becomes `other`.
Non-replacement locks are always `none`. New series in the worst case:
39 kinds × 4 outcomes, for the histogram and the counter.
- **Not sensitive:** no community, pubkey, coordinate, or d-tag is
attached. The kind of a replacement lock does not expose any of those.
- **The guard is narrowed, not removed:** `"kind" =>` must appear
exactly twice, inside the advisory-lock observer `observe_lock`, whose
kind must come from `registered_kind_label` inside `observe_event_lock`.
It is still forbidden everywhere else in `observability.rs` and in the
datastore tracing macro. The #7195 guard that forbids a literal
`"other"` in `observability.rs` is unchanged, because the fallback lives
in `buzz-core`.

## Dashboards and alerts

Both metrics gain a label, so existing selectors keep working:
`lock_type="replacement"` still matches every replacement series,
because Prometheus and Datadog selectors match on a subset of labels. A
consumer is affected only if it depends on the exact label set:

- Recording rules or panels that read a series without aggregating it
now get one series per kind. Aggregate with `sum by (lock_type, outcome)
(...)` to keep the old shape.
- Vector matching with `on(lock_type, outcome)` or `ignoring(...)` now
has more series on one side. Aggregate before the join.

To read the new attribution, group by `kind`, for example `sum by
(lock_type, kind) (rate(buzz_db_advisory_lock_wait_seconds_sum[5m]))`.
No consumer in this repository depends on the exact label set.

## Tests

- `buzz-core`: `registered_kind_label_bounds_unregistered_kinds` checks
that a registered kind passes through and that an unregistered or
negative kind becomes `other`.
- `buzz-db` recorder test: checks the replacement series for a
registered kind (`13534`) and an unregistered kind (`other`), and the
`kind="none"` series for a membership lock, on both metrics.
- `kindless_observer_rejects_replacement_locks`: the `debug_assert`
guard panics.
- `membership_list_lock_records_the_roster_kind` (Postgres): a 13534
list write records exactly one `membership` acquisition with
`kind="13534"`.
- `group_state_replacement_takes_its_lock_once` (Postgres): now counts
acquisitions only under the written kind. It expects `kind="39000"` for
the group-state snapshot path and `kind="0"` for
`replace_addressable_event`, so if `take_replacement_lock` drops or
swaps the kind, the count becomes 0 and the test fails.
- `observability_source.rs`: the narrowed guard described above.

Commands run:

- `cargo clippy --workspace --all-targets -- -D warnings`
- `cargo test -p buzz-core --lib`
- `cargo test -p buzz-db --lib`
- `cargo test -p buzz-db --test observability_source`
- `scripts/postgres-test-run.sh -p buzz-db --lib --tests` (the CI
PostgreSQL lane, run locally)

## Local relay check

The relay ran from this branch against an isolated database. `/metrics`
showed one series per locked kind after each write:

- `users set-profile`: `replacement`, `kind="0"`
- `users set-status`: `replacement`, `kind="30315"`
- `channels create`: `replacement`, `kind="39000"`, `"39001"`, `"39002"`
- `channels add-member`: `replacement`, `kind="39002"`
- `agents archive`: `replacement`, `kind="13535"`
- `moderation ban`: `replacement`, `kind="30622"`, plus `membership`,
`kind="none"`
- Invite mint and claim
(`e2e_relay::test_invite_mint_and_claim_admits_new_pubkey`):
`membership`, `kind="13534"`
- Background loops: `deletion` and `partition_maintenance`,
`kind="none"`

`buzz_db_advisory_lock_wait_seconds_count` matched
`buzz_db_advisory_lock_acquisitions_total` for every series. The author
also tested it against the local relay.

buzz-review-completed

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

Signed-off-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:13:23 -08:00
Jordan Mecom
1fb33e4545 fix(relay): publish a git push only when refs changed; check the protocol by refinement (#9425)
## Summary

This PR is stacked on #9064. It does two things to the
Git-on-object-storage code in `buzz-relay`. It replaces the TLA+ model
of the push protocol with one that states what the protocol is supposed
to implement and checks that it does. It also changes the rule by which
the relay decides whether to publish a push, because the new model shows
that the rule #9064 introduces still publishes requests in which git
accepted nothing.

### Relationship to #9064

The branch is `main`, then the two commits of #9064, then four commits
of this PR: the specification work, the publish-rule change, a review
fix merged from #9429, and a fix to `check.sh`. A merge of `main`
follows them; it was needed because `main` changed `Justfile`, which
#9429 also edits, after the branch point. The first two commits are
#9064's, replayed onto current `main` without conflicts and otherwise
unchanged. The base of this PR stays `main` because #9064's branch is
about 200 commits behind it. Once #9064 merges, this branch can be
rebased and the diff shrinks to the last four commits. Until then,
review the commits after the first two.

This PR keeps two of #9064's three changes as they are: the
`published_at` stamp that orders kind:30618 events by the manifest
chain, and `protect_landed`, which lets a landed conditional write stand
when the serving lease lapses after it. It replaces the third, the
publish rule.

### The publish rule

#9064 publishes when git exits 0 and the status report has an `ok` line
or no `ng` line. That handles a push in which one ref is updated and
another refused. The report, however, is not evidence of what git did.

- git exits 0 for a request that carries no commands, and for a push the
pre-receive hook declined. A decline is reported only to a client that
negotiated `report-status`. For a request with no commands, and for a
decline when the client did not negotiate a report, there is no `ng`
line. The relay then writes the pointer and emits a relay-signed
kind:30618 event that names the caller as pusher, although the push
policy approved nothing.
- The report is read from a stream whose framing the client's
capabilities determine, so the decision depends on parsing a
client-shaped stream.

The decision is now taken from the workspace. `push_disposition`
compares the refs after receive-pack with the refs the workspace was
hydrated from. Unchanged refs are answered with git's own output and
nothing is published. Changed refs are published if git exited normally.
Changed refs after an abnormal exit fail the request. The snapshot that
is compared is the one `cas_publish` publishes, so git's per-ref report
is true of the published state. The status-report scanner and its tests
are removed, and the ref-name conflict case they covered moves into the
table-driven test described below.

Three smaller changes follow. The ref-snapshot parser now fails closed:
output that was not UTF-8 used to read as an empty ref set and a
malformed line was skipped, and either would publish a manifest that
lacks refs. `manifest_changed` in `finalize_push` could not be false and
is removed. Taking the snapshot before the publish decision moved its
resource-limit error (snapshot larger than 4 MiB, or more refs than a
manifest may hold) onto a path that answered 500; #9429 restores the 413
the publish path gave before and adds
`snapshot_resource_limit_answers_413`.

### What the specification work adds

- `docs/spec/GitRefDB.tla` is the specification: a ref database in which
a push takes effect in one step, is applied only if authorized and only
against the old values it names, and is reported truthfully.
- `docs/spec/GitOnObjectStore.tla` is the protocol: several refs, an
object graph with reachability, packs, compaction, the pre-receive hook,
the publish decision, the default-branch setter, repository creation,
and a reader. `git receive-pack` is represented by a stated contract
rather than modeled internally.
- The correctness statement is `Refines`: every behavior of the protocol
is a behavior of the specification. TLC checks it together with the
store invariants (fence, reader completeness, closure of published
manifests).
- `docs/spec/check.sh` pins TLC 1.7.4 by SHA-256 and runs 28 checks.
Eight instances must pass. Nineteen seeded design errors must each be
detected with the violation named for them. One coverage check confirms
that a behavior the properties depend on (git reporting `ok` for a
command that changes nothing) is reachable. A name passed to `check.sh`
that is not a check is an error, so a misspelled selection cannot report
success.
- Both earlier publish rules are among the seeded errors: the original
rule (exit 0 and no `ng`) and #9064's status-report rule. For each, TLC
reports a publication the policy did not approve
(`PublishIsAuthorizedChange`) and a violation of `Refines`.
- `docs/spec/GitPushPath.qnt`, the Quint model from #9064 that covers
the serving lease and the event timestamps, is extended. The publish
rule becomes a parameter with three values, a request may carry no
commands or come from a client without a status report, and a new
invariant, `publicationChangesRefs`, states that a published manifest
differs in its refs from the one it replaces. The implemented rule
satisfies all four invariants; the status-report rule violates the new
one with a zero-command request.
- `docs/spec/lean/GitPointer.lean` is a Lean 4 proof, with no
dependencies, of the pointer discipline for any number of clients, refs
and objects: the fence, closure, that every pointer change is a legal
step from the value it replaces, that the length of the pointer's
predecessor chain equals the number of pointer writes, and that a
successful conditional write implies no intervening write.
- `.github/workflows/spec.yml` runs TLC and Lean when a file under
`docs/spec/` changes. On this PR's first run the TLC job took 10 minutes
19 seconds and the Lean job 22 seconds. Quint is not run in CI.
- `docs/git-on-object-storage.md` is revised to match. The push listing
follows the implemented order. The verification section separates
definitions, assumptions, results checked by TLC, results proved in
Lean, results checked with Quint, evidence about the implementation, and
limitations. The invariant names cited by code comments and by migration
0002 are kept as aliases in the TLA+ module.

### Assumptions and limitations

The TLC results hold for the bounded instances in `check.sh`, not for
arbitrary sizes. The Lean proof is unbounded but covers the pointer
discipline only, not the refinement. The Quint results are from random
simulation (2,000,000 runs of at most 14 steps) and a bounded symbolic
check (8 steps, Apalache); neither is a proof for unbounded runs. All of
them rest on the assumptions named in the document: the object store's
conditional-write semantics, ETag equality implying body equality, no
SHA-256 collision among the values that occur, the stated contract for
`git receive-pack`, and the policy endpoint deciding authorization. The
correspondence between the models and the Rust code is established by
reading the code and by the tests below; it is not mechanized.

The document states one assumption that #9064's ordering fix depends on
and that no model covers (Assumption C1). A manifest whose parent
carries no `published_at` (the empty manifest written when a repository
is announced, or a manifest written before the field existed) is stamped
with the writing instance's current time plus one second. Its event is
selected over the parent's only if that value exceeds the parent event's
`created_at`, which was taken from the clock of the instance that
emitted it. This holds when one instance handles both, and otherwise
when the writing instance's clock is not behind the other's by more than
the time elapsed between the two events. The assumption concerns one
write per repository. The document lists its removal as a proposed
extension, for example by having the first push after an unstamped
manifest read the stored event's `created_at` and exceed it.

### Related issue

Related to #2621 (CI for the formal models). This adds the TLC job for
the git model and a Lean job; it does not cover the Tamarin models or
the NIP-PL scripts, so it should not close that issue.

### Testing

Run locally on the restacked branch:

- `docs/spec/check.sh`: 28 checks, each with the expected result (8
pass, 19 seeded errors violate the named property, 1 coverage witness
reached). About three minutes on 16 cores; the largest instance has
6,773,286 distinct states.
- `lake build` in `docs/spec/lean` (Lean 4.33.1): succeeds. The safety
theorems depend only on `propext`, `Classical.choice` and `Quot.sound`.
- Quint 0.33.0, `GitPushPath.qnt`: `quint run --main fixed --invariant
safety --max-steps 14 --max-samples 2000000 --seed 0x1` reports no
violation; `quint verify --main fixed --invariant safety --max-steps 8`
(Apalache 0.62.1) reports no violation; each single-defect module
produces the counterexample the document lists.
- `cargo fmt --all -- --check` and `cargo clippy -p buzz-relay
--all-targets -- -D warnings`: clean.
- `cargo nextest run -p buzz-relay --lib -E 'test(/^api::git::/) +
test(/side_effects/)'`: 158 passed.
- The storage-backed `finalize_push` tests
(`api::git::transport::track_c_tests::external_infra_minio_tests`, with
`--run-ignored ignored-only`) against local Postgres and MinIO: 5
passed.
- `e2e_git` against a local relay built from this branch, with Postgres,
Redis and MinIO: 3 passed (clone/push/fetch/force-push round trip,
concurrent push, partially refused push). The storage probe in that test
needs `BUZZ_E2E_GIT_COMMUNITY_ID` set to the local community's id.
- `just file-size-check` and `just security-review-check`: pass.

Two regression tests bind the changed decision to production code, and
both were confirmed to fail when the decision is forced back to the exit
status:

- `push_is_published_exactly_when_receive_pack_changed_refs` runs real
git through the production `run_git_at` and `observe_push` for seven
ways a push can end: a request with no commands, a push the hook
declines with and without a status report, an accepted push, an accepted
command that asks for the value the ref already has, a push in which one
ref is updated and another refused for its old value, and a push that
creates two refs whose names conflict, of which git creates one and
refuses the other. It needs no services. Which of the two conflicting
refs git creates depends on the git version (2.50 creates the first
command's ref, 2.56 on the flake-check runner creates the other), so the
test accepts either outcome and requires that each ref is in the
published snapshot exactly when git reported `ok` for it. The first
version of this case assumed one outcome and failed the Rust flake check
for that reason. Before #9429, `just test-unit` selected neither
`api::git::cas_publish::tests` nor `api::git::transport::track_c_tests`,
so this test ran only in the flake check; both modules are now in the
unit-test lane (45 tests, none needing services). It is Unix-only
because its hook fixture sets file modes; the first push of this PR
failed Windows clippy for that reason, and the test and its fixture are
now gated with `#[cfg(unix)]`. That gating has not been compiled for
Windows locally, so the Windows CI job is the check.
- `finalize_push_publishes_nothing_when_receive_pack_changed_no_ref`
calls `finalize_push` with an unchanged workspace and checks that the
pointer is not written and no kind:30618 event is stored. It needs
Postgres and an object store.

Not done, or not covered:

- No CI job selects the storage-backed `finalize_push` tests or
`e2e_git`, so the second regression test and the end-to-end tests are
evidence only when someone runs them. Adding them to CI needs a change
to the test fixture, which applies migrations itself, and is left as a
follow-up.
- `just ci` was not run in full.
- No human has tested the change. The human-testing step of the
readiness checklist in `AGENTS.md` is not met, and
`buzz-review-completed` is not claimed.

The local secret-scanning hook (`sadscan`) was skipped for the commits
and pushes that touch `crates/buzz-relay/src/api/git/settings_tests.rs`.
It scans whole files and flags the P-256 test key fixtures that file
already contains on `main`; this branch adds no key material.

---------

Signed-off-by: Jordan Mecom <jm@squareup.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-13 10:20:45 -08:00
Sanket Kanjalkar
bd031a05af fix(acp): bound observer retention by bytes (#7987) (#9436)
Replaces #9366 on a branch in this repository and resolves its conflicts
with main.

## Summary

The ACP observer kept up to 1,000 raw events in both replay and live
buffers. Large valid messages could retain gigabytes before downstream
trimming ran.

Fit telemetry before either buffer retains it. Cap replay at 4 MiB of
serialized JSON and keep the existing live window. Its per-event limit
bounds live JSON below 64 MiB.

Preserve the CPU and locking improvements from #9381: prepare large
payloads and copy snapshots outside the replay lock. Finalize sequence
and timestamp with publication. Account for that final metadata,
including sequence digit-width changes, in the byte limit.

The tradeoffs are extra work per emit, shorter replay history for large
events, and elided oversized telemetry. Agent protocol messages remain
unchanged.

### Related issue

Fixes #7987. Existing publisher byte limits act downstream of these
buffers.

### Testing

The opt-in probe exercises the real in-process emit, snapshot and
stalled-subscriber paths:

```sh
CARGO_INCREMENTAL=0 CARGO_PROFILE_RELEASE_LTO=thin CARGO_PROFILE_RELEASE_CODEGEN_UNITS=4 \
  cargo test --release -p buzz-acp --lib observer::tests::retention_probe -- --exact --ignored --nocapture
```

Compared baseline `a314975ce` with candidate `c2df3cb56` on macOS arm64,
Rust 1.98.1. The baseline observer, fitter, workspace manifest and
lockfile match the candidate's parent `8f3f4e266`. Both arms use
`opt-level=3`, thin LTO and four codegen units, with incremental
compilation and compiler-cache wrappers off. This profile is fixed for
the comparison; this PR does not change build settings.

Values are medians of three fresh-process runs per version and workload,
in alternating order. Peak RSS comes from `/usr/bin/time -l` around each
test executable; compilation is excluded. Each version was rebuilt
separately and its executable and workload identity verified.

| Workload | Peak RSS before → after | Emit time per event before →
after |
| --- | --- | --- |
| 10,000 × 1 KiB | 14.0 → 14.1 MiB | 0.47 → 0.89 µs |
| 1,000 × 60,000 bytes | 199.4 → 80.8 MiB | 8.54 → 22.53 µs |
| 1,000 × 1 MiB | 3,025.8 → 26.4 MiB | 123.50 → 307.89 µs |

For the 1 MiB workload, replay JSON fell from 1,000.2 MiB to 3.997 MiB.
Live JSON fell from 1,000.2 MiB to 5.91 MiB. Replay retained 676 fitted
events; the live subscriber received all 1,000.

Emit time includes payload construction. Peak RSS includes snapshot and
receive copies made by the probe. JSON budgets are not exact heap
limits. These local measurements show the memory/CPU tradeoff;
concurrent producer throughput and native app latency were not
benchmarked. See [the probe
instructions](c2df3cb567/crates/buzz-acp/TESTING.md (observer-retention-measurement))
for workloads, controls and limits.

Human verification remains pending.

Generated with AI assistance

Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com>
Co-authored-by: Codex <codex@openai.com>
2026-11-13 01:08:39 -08:00
Luke Tornquist
279a31daac buzz-search: read profile names without the profile_name_fields function (#9397)
## What

This is phase 1 of 2 for retiring the plpgsql function
`profile_name_fields(text)`. Its only caller, profile name search
(`search_profile_names`), now gets `name` and `display_name` from an
inline SQL expression (`PROFILE_NAME_FIELDS` in
`crates/buzz-search/src/query.rs`) instead.

The function's exception handler made unreadable kind:0 content have no
names rather than fail the search. The inline version keeps that
guarantee in two steps:

- **`pg_input_is_valid(content, 'jsonb')`** rejects the soft parse
errors: a `\^@` escape, a lone surrogate, a huge number, and malformed
JSON.
- **A bracket bound for deep nesting.** PostgreSQL's JSON parser is
recursive. Past about 10k levels at the default `max_stack_depth`, it
raises `stack depth limit exceeded`, and `pg_input_is_valid` does not
catch that. I confirmed this on PG 17: depth 10k is fine and 20k raises.
So content with more than 4096 `[` and `{` is never parsed and has no
names. The count bounds the depth. Ingest already rejects kind:0 content
nested deeper than 128 levels (serde_json), so this only matters for
content stored another way.

`OFFSET 0` keeps the parse from being copied into each reference to
`doc`, so each candidate row is parsed once, plus one validity pass. The
plpgsql function also parsed each row once.

**Behavior change (edge only):** a kind:0 with more than 4096 brackets,
even inside strings, is no longer findable by name. Real profiles don't
come close, and a `picture` data URL is base64 with no brackets.

`pg_input_is_valid` needs PostgreSQL 16 or later. CI runs 16, and the
dev compose runs 17.

**Phase 2 (not here):** a migration and desired-state change drops the
function, its `schema/functions/` file and its `schema.sql` entry once
this release has shipped.

## Tests

- `profile_names_survive_unparsable_content` already stores a `\^@`
profile, a lone-surrogate profile, a `1e1000000` profile and a 60k-deep
profile next to a plain one, and requires the search to return only the
plain one. It now also covers the bound itself: a profile with exactly
4096 brackets, all but one inside a string, is still found.
- Must-fail mutants, each run on Blox: bracket bound removed (the search
fails with a stack overflow), validity check removed, bound tightened by
one, and the string-type check loosened.

## What got simpler

Profile search no longer depends on a database function. Name extraction
lives next to the rest of the search SQL it feeds.

## Verification

Blox, at `be0db303ea90033cc2c37ac8f8f07c27f4b08e31` (clean tree):

| Gate | Result |
|---|---|
| `cargo fmt --all --check` | pass |
| `cargo clippy -p buzz-search --all-targets -- -D warnings` | pass |
| `cargo nextest run -p buzz-search --lib` | 4/4 |
| `scripts/postgres-test-run.sh -p buzz-search --tests -E
'test(/profile_names/)'` | 4/4 |
| Must-fail mutants (no bound, no validity check, bound tightened by
one, non-string names allowed) | 4/4 killed |

Probe on PostgreSQL 17.11: `pg_input_is_valid` returns false for `\^@`,
a lone surrogate, `1e1000000` and truncated JSON; nesting depth 10k is
valid; depth 20k raises `stack depth limit exceeded`. CI runs the full
Postgres lanes.

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


buzz-review-completed

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:34:56 -05:00
Luke Tornquist
745f7dac7c buzz-db: build the community deletion lock key in Rust (#9396)
## What

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

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

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

## Tests

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

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

## What got simpler

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

## Verification

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

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

CI runs the full Postgres lanes.

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


buzz-review-completed

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:34:23 -05:00
Will Pfleger
630922a9e1 fix(cli): pair for the active community, skip stopped desktops, accept a bare relay host (#9417)
## Summary

Fixes to `buzz auth desktop pair` and relay selection:

- **`pair` skips desktops that aren't running.** A desktop that exited
without removing its advertisement no longer counts toward "several Buzz
desktops are running". It uses the same running test as `probe`, where
only a transport failure means not running.
- **`--relay` is global**, so `buzz auth desktop pair --relay …` works
and the flag shows in subcommand help.
- **A bare host means `https://`** for `--relay` and `BUZZ_RELAY_URL`.
An explicit `http://`, `ws://` or `wss://` stays as typed.
- **`pair` with no relay sends `[client]`.** The desktop pairs for its
active community and returns the bound relays, which the CLI stores. An
older desktop answers `invalid_request`, which the CLI reports as "this
Buzz can't pick a community; pass --relay".
- **`docs/local-credential-provider.md`**: covers the one-parameter
`pair`, `unavailable` when no community is active, the older-provider
fallback, skipping stale advertisements, and a lapsed sign-in keeping
the pairing instead of revoking it.
- The existing `concurrent_pair_and_unpair…` test now fails after 60s
instead of hanging when the held pair request never reaches the mock
desktop.
- The CLI tests that run the real `lsof` same-user check now take turns.
A nextest test group, `desktop-same-user-check`, serializes the whole
`desktop_provider::` module for the pre-push hook. Most of its tests
reach the check, and the few that don't run serially too. A test-only
lock around the check does the same in `cargo test`. Waiting for a turn
doesn't count against the request timeout. The check and its 5s limit
are unchanged. `list_tells_a_stale_advertisement_from_a_rejection` keeps
the in-cap `retry_after` of 30 and times from the desktop's first
answer, so waiting for a turn isn't counted.

The desktop half is block/buzz-app#3386.

## Testing

- New tests: `pair_skips_a_desktop_that_is_not_running`,
`an_older_desktop_asks_for_a_relay`,
`relay_flag_is_global_and_a_bare_host_means_https`, plus updated
relay-selection cases.
- `cargo test -p buzz-cli --locked -- --test-threads=4` passes: 689
tests, both with default threads and with `--test-threads=4`, and under
the pre-push hook's nextest run.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
2026-11-12 19:29:12 -05:00
Sanket Kanjalkar
a314975ce7 perf(acp): reduce observer CPU and lock overhead (#9381)
## Summary

The Agent Client Protocol (ACP) observer records agent activity for the
owner's viewer. Sizing currently allocates JSON strings and rescans
whole frames for each trimmed field.

Count JSON bytes directly, reuse fitted sizes, and count changed fields
when cheaper. Skip raw-message copies for disabled observers and copy
replay payloads outside the mutex. Keep sequence numbers, timestamps,
replay insertion, and publication under one lock to preserve replay/live
ordering.

This adds one `Arc` allocation per replay entry, and snapshots pin
entries until copying completes. Replay retains the existing 1,000-event
limit.

### Related issue

Related to #7987. This PR targets `main` independently of #9366, which
owns the byte-budget fix. The changes overlap in observer plumbing, so
the second PR to land will need a rebase.

### Testing

The new ignored probe exercises the production publish queue. Timing
includes template clones and queue ingestion, before encryption. Five
alternating fresh release processes per arm/case compared `75d38b6c2`
with this commit on a busy host. Every pair retained identical queue
bytes and event counts.

```sh
cargo test --release -p buzz-acp --lib observer::perf_tests::publish_queue_probe -- --exact --ignored --nocapture
```

Set `BUZZ_OBSERVER_PROBE_EVENTS`, `BUZZ_OBSERVER_PROBE_BYTES`, and
`BUZZ_OBSERVER_PROBE_FIELDS` for each row. Medians:

| Events / string bytes per event / fields | Before | After |
| --- | ---: | ---: |
| 200 / 1 MiB / 64 | 5605 ms | 228 ms |
| 1,000 / 1 MiB / 1 | 714 ms | 352 ms |
| 10,000 / 1 KiB / 1 | 13.01 ms | 6.90 ms |

A separate 20-trial integration run used the same production Chromium
app build (`block/buzz-app@128cd4c2`) and four real ACP subprocesses.
Three peers emitted 225 synthetic messages over five seconds, each with
1 MiB across 64 strings. A fourth emitted 50 markers, 100 ms apart. Each
arm/mode used five fresh processes and browser contexts, with
alternating arm order.

The real observer, publisher, encryption/signing, browser broker, and
Activity UI ran through a modeled relay transport. Marker timing used
one controller clock, from release through transcript DOM commit plus
two animation frames. Observer timestamps were not the timing origin.
Observation-enabled medians:

| Metric | Before | After |
| --- | ---: | ---: |
| Rust CPU time | 4.49 s | 0.45 s |
| Marker-to-render p95 | 4471 ms | 1018 ms |
| Sampled peak RSS | 342.3 MiB | 296.9 MiB |

All 500 enabled-mode markers rendered exactly once; all 2,250 large
events were delivered with the existing payload elision.
Observation-disabled CPU stayed roughly flat (0.13 s to 0.12 s). The
controlled publication-order regression also fails original `main` and
passes this commit.

These are stress-workload measurements, not a general app speedup.
Native hosting and deployed-relay performance remain unmeasured. The
publish cadence remains one frame per second. No CI timing threshold was
added.

Generated with Codex

Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com>
Co-authored-by: Codex <codex@openai.com>
2026-11-12 14:37:33 -08:00
Luke Tornquist
ce42853982 ci: fix main — stale RunCause call sites and Playwright on ubuntu-26.04 (#9418)
## Summary

Two separate CI breaks are hitting every PR right now. Each one blocks a
required check, and neither fix can go green on its own, so this PR
fixes both.

**1. Rust test targets stopped compiling on main at fc8c8022.** #9227
added a required `RunCause` argument to `create_workflow_run` and a
`may_direct_agents` flag to `ActionSink::send_message`. Two tests that
merged around the same time still used the old signatures:

- `attach_rejects_run_from_another_workflow` in
`crates/buzz-db/src/store/workflow.rs` (from #8317)
- the agent-DM refusal test in `crates/buzz-relay/src/workflow_sink.rs`
(from #9371)

Each PR passed CI on its own base. Together they break Rust Lint, Unit
Tests, Windows Rust and the Desktop E2E Relay artifact build (main CI
run 43291564834). The fix passes `RunCause::Schedule` and `true`,
matching the neighbouring tests. Neither test is about run cause or
agent mentions, so neither assertion changes.

**2. Desktop E2E Integration fails on GitHub's new Ubuntu 26.04
runners.** `ubuntu-latest` is rolling to 26.04, and Playwright 1.60 (our
lockfile) fails with `Playwright does not support chromium on
ubuntu26.04-x64`. Playwright 1.61 is the first release that knows
ubuntu26.04. This PR bumps `@playwright/test` to `^1.65.0` in
`desktop/`, `web/` and `admin-web/` and regenerates `pnpm-lock.yaml`. It
also pins every `ubuntu-latest` job in `ci.yml` and `_ci-*.yml` to
`ubuntu-26.04`, so the next runner image change arrives in a reviewed
diff. macOS and Windows jobs are unchanged.

The newer Chromium bundled with Playwright 1.65 changed two smoke specs.
It reports Tailwind's `items-end` as `align-items: flow-end`
(`doctor-states` now accepts `flex-end` or `flow-end`), and it draws the
textarea resize grip differently, so the
`workflow-template-variable-autocomplete` baseline is refreshed from the
ubuntu-26.04 CI output.

It also exposed a timing race in `profile.spec.ts` "owned agent profile
stays in parity": when the Message click lands while the profile panel
is still settling, Playwright's scroll-into-view retry scrolls the
profile body, which hides the owned-agent action row (aria-hidden +
inert) for good. The test now pins the body to the top and waits for the
row before clicking (12/12 repeats plus the full profile spec pass on
Linux).

## Verification

- `cargo clippy -p buzz-db -p buzz-relay --tests -- -D warnings` is
clean on fc8c8022 with commit 1 applied.
- `pnpm install --frozen-lockfile` succeeds with the new lockfile, and
`playwright --version` reports 1.65.0.
- `tsc --noEmit` passes for `desktop`, `web` and `admin-web`.
- This PR's CI is the E2E check on 26.04.

## Notes

- Workflows that don't run on PRs (release, helm charts, sprig, image
builds, codex-security-review) still use `ubuntu-latest`. This PR can't
exercise them, so they're left for a follow-up.
- The hermit-pinned actionlint (1.7.12) doesn't know the `ubuntu-26.04`
label yet. CI only actionlints `codex-security-review.yml`, which this
PR doesn't touch.

## Simpler

No production code changes. The runner pin swaps an implicit moving
target for an explicit one.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:25:00 +00:00
John Matthew Tennant
432df8aa52 fix(media): run thumbnail regeneration tests in CI and cap rebuild pixels (#9198)
## Summary

Two gaps in the thumbnail regeneration from
[#9174](https://github.com/block/buzz/pull/9174):

- **Its MinIO tests never ran in CI.**
`api::media::tests::postgres_tests::external_infra_minio_tests` is
excluded from the PostgreSQL lane, which skips `external_infra*`
modules, and the backend integration job's only media MinIO step selects
the admin tests. A sibling step now runs them against the same Postgres
and MinIO.
- **Rebuilding a thumbnail skipped the 25 MP pixel cap.** Upload
validation rejects images over 25 megapixels before they reach the
decoder. A thumbnail rebuilt from a stored original goes straight to
`generate_image_metadata_sync`, so that cap didn't apply. The check is
now a shared `check_image_pixels` that upload validation and thumbnail
generation both run before decoding. On a rebuild, an oversized original
gets the same 404 as any other regeneration failure.

### Related issue

Follow-up to [#9174](https://github.com/block/buzz/pull/9174), from its
review.

### Testing

- `missing_thumbnail_is_not_regenerated_when_unsafe` now stores a valid
5001x5000 PNG as an image original without thumbnails and requests one
through the media route. On `main` the relay rebuilds and serves it;
with this change the request is a 404 and no thumbnail is written.
- The new CI step runs both `external_infra_minio_tests` cases one at a
time, since they share the fixture image's storage keys.

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

---------

Signed-off-by: John Tennant <jtennant@squareup.com>
Co-authored-by: Simone <0828be588d5c9c4d092c5b1cf01761d5aef63d6b104807fd8e8284d517dd1a99@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:01:24 -08:00
Blake McAnally
745d2a86e0 fix(cli): treat a retried sidebar write the relay already stored as success (#9202)
Follow-up to #9191. It addresses the review findings that came in as
that PR merged.

## Summary

**A retried write was reported as a conflict.** This was found by the
Codex security review on #9191 (LOW).

- `BuzzClient::submit_event` can resend the same signed event after an
ambiguous attempt, for example a timeout after the relay stored it.
- The relay answers that resend `accepted: true, message: "duplicate:"`.
`publish` turned any `duplicate:` into exit 5 with "a newer update won;
run the command again".
- If you ran `buzz sidebar sections create` again, you got a second
section.

On a `duplicate:` reply, `publish` now re-reads the head from the writer
(`consistency: strong`). It reports success only when the head is the
event it signed. The check is safe because `replace_parameterized_event`
returns `was_inserted = false` for both an exact-id duplicate and a
stale (dominated) write. Only a stored event can be the head with our
id, so a dominated write still exits 5.

**Unknown keys are dropped on decode.** This was raised by joahg on
#9191. The module docs now state the limitation and why it is safe:
- Buzz Desktop (`block/buzz-app`, `validate_sidebar_payload`) refuses to
sign a document with unknown keys, so a new field needs a new `meta.v`.
- `decode` refuses an unknown `meta.v`. The commands then neither read
nor overwrite that head.

## Not changed

joahg also noted the lost-update window between the head read and the
submit. That window is documented in `crates/buzz-cli/README.md` (from
#9191). A kind:30078 replaceable event has no compare-and-set on the
relay, so the CLI cannot detect the case. A test would only check the
fake relay's replace rules.

## Testing

- `cargo test -p buzz-cli`: 665 pass. `cargo clippy -p buzz-cli
--all-targets -D warnings` and `cargo fmt --check` are clean.
- New test: `a_retry_of_a_stored_write_is_success`. The fake relay
stores the event and answers `duplicate:`. The test fails without the
fix (`Conflict("a newer sidebar sections update won; run the command
again")`).
- `a_dominated_write_is_a_conflict` now seeds a newer head under the
caller's own key. Before, every conflict test had an empty own head, so
a looser check (`Some(_)`) still passed. The test now fails under that
change.
- An agent review ran. It found that gap in the dominated-write test,
which is now fixed. Its remaining notes are optional.

### Manual test steps

The retry path needs a lost relay response, so you cannot easily trigger
it by hand. These steps check that normal writes did not change:

1. Run `cargo build -p buzz-cli`. Then set `BUZZ_RELAY_URL` and either
pair with Buzz Desktop (`buzz auth desktop pair`) or set
`BUZZ_PRIVATE_KEY`.
2. Run `buzz sidebar sections list` and save the output.
3. Run `buzz sidebar sections create --name "Retry test"`. Expected:
`"accepted": true`, a non-null `event_id`, and a `section_id`.
4. Run `buzz sidebar sections delete --section "Retry test"`. Then run
`list` again. Expected: the same output as step 2.

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

Signed-off-by: Blake McAnally <bmcanally@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:31:49 -08:00
Will Pfleger
fc8c802253 feat(workflow): add owner-only agent mentions for workflow messages (#9227)
Adds owner-only agent mentions, a relay setting,
`BUZZ_WORKFLOW_AGENT_MENTIONS`. Its values are `any`, the default and
today's behaviour, and `owner`. Any other value fails startup. With
`owner`, a workflow message can direct an agent only if the run's cause
and definition allow it. The setting is relay-wide.

**Recording what caused each run.** `workflow_runs` gets `cause_source`
and `cause_pubkey` columns. Migration `0087` adds them with named checks
marked `NOT VALID`, so it does not scan existing rows under its lock;
`0088` validates the checks separately. `create_workflow_run` now takes
a required `RunCause`, so every place that creates a run has to set one:
- **Event trigger:** the cause is the signer of the message, reaction or
diff. For a reaction, that is the reactor, not the author of the message
being reacted to.
- **Cron and interval schedules:** the cause is the timer.
- **Webhook:** the caller is unknown.
- **Manual trigger:** the cause is the invoking pubkey.

Rows written before this change have no cause. A stored source without
the pubkey it requires, or with one it forbids, is read as no cause.

**Deciding eligibility.** A run's messages may direct agents only when
all of these hold:
- the cause is a schedule, or an event or manual trigger whose pubkey is
the workflow owner's;
- every step of the definition that is running is `send_message` or
`delay`. This is an allowlist, so any other action, including one added
later, makes the definition ineligible, even when an `if:` skips that
step;
- the run did not resume after an approval.

Webhook runs and runs with no recorded cause are never eligible. The
executor decides this from `WorkflowConfig::agent_mentions`, and passes
`ActionSink::send_message` the owner's stored step text with a
`may_direct_agents` flag. The sink adds `buzz:workflow-mention` tags
only when the flag is set, and returns `SentMessage { event_id,
agent_mentions_withheld }`, which is true only when it left out a tag
that a member named in both the stored and rendered text would otherwise
have received. Webhook and manual runs start through `execute_run`, so
`execute_from_step` is used only to resume after an approval.

**The gate.** With `owner`, the relay adds `buzz:workflow-mention` only
to messages from eligible runs. Messages from other runs still post with
their plain `p` tags and still notify people. With `any`, mention tags
are added exactly as before.

**Making it visible.** When a `send_message` step leaves the tags out:
- its output in the run trace gets `"agent_mentions": {"withheld": true,
"reasons": [...]}`, listing each reason that applies: `cause` (not
started by the owner or a timer), `steps` (a step other than
`send_message` or `delay`), `resumed` (resumed after an approval). The
key is absent when nothing was withheld. The trace is what the app's run
history shows;
- the relay logs it at info level under the
`buzz_relay::workflow_agent_mentions` target (visible under the default
filter) with the community, workflow, run, step and reasons;
- the counter `buzz_workflow_agent_mentions_withheld_total` increases
once per reason, labelled `reason`.

**Discovery.** The NIP-11 document always carries
`"workflow_agent_mentions": "any" | "owner"`, so a missing field means
an older relay.

`NOSTR.md` now specifies `buzz:workflow-mention` for clients: what the
tag means, the checks an agent makes before acting, that a relay may
leave it out under a policy, and the NIP-11 `workflow_agent_mentions`
field. The relay policy itself is in the new operator guide,
`docs/operator-workflow-agent-mentions.md`: the setting and its values,
what counts as a run's cause for each trigger, which steps are allowed,
the trace key, the log and metric, the NIP-11 field, when to use
`owner`, rollout across pods, and what it doesn't cover. The
`TESTING.md` and `.env.example` entries link to it.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-11-12 11:34:30 -08:00
klopez4212
cb69ad9e4f Adapt iPhone Duo layouts, rail navigation, and native sheets (#8568)
Duo keeps conversations and Settings details open across closed, book
and flat postures. Book mode splits at the fold; flattening restores the
sidebar. Native rail controls, full-width navigation backdrops and
sheet-local safe areas keep content aligned. Ordinary iPhones remain
single-pane in portrait and landscape; tablet and Duo split layouts
remain enabled.

Includes the recovered preview's matching pane widths, Buzz empty-pane
mark, stable Settings chevrons, Bestie pane routing and Duo-only upward
New menu attachment. Current main's Activity redesign, Search content
fade and unread-navigation button are retained. Menu selection checks
sit beside their labels.

Shared mobile changes remain in scope: the native iOS status editor,
Appearance preview layout, avatar crop preservation, onboarding footer
layout, profile/invite sheet geometry and nested conversation
navigation. This PR is not exclusively Duo-gated. Nested navigator
observers preserve recording cancellation and navigation callbacks; crop
resizing preserves the selected image region. iOS 27.1 APIs remain
compile-time and runtime gated.

Validation on the reconciled source: Flutter analysis, Activity/Home
journeys, the full mobile test suite, file-size checks and Swift package
tests. The iPhone single-pane fix was also exercised on an iPhone 18 Pro
simulator before reconciliation. Fresh hosted CI and physical-device
confirmation of the reconciled build are separate and remain pending.

---------

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: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-12 19:00:58 +00:00
Luke Tornquist
aa9b44ef36 buzz-db: pin explicit FK-child cleanup and same-workflow fire links (#8317)
> Builds on #8219 (merged); rebased onto `main` at `93ffc37cb` (includes
the rustls bump, #8319).

## What

This closes the identified debt from #8212. Every remaining `ON DELETE
CASCADE` / `SET NULL` foreign key was audited against every supported
way its parent row gets removed, with FK actions retired in the per-test
schema (`test_support::retire_foreign_key_delete_actions`). One
production change was needed. The rest is already explicit and is now
covered by tests.

**Production change:** `attach_scheduled_workflow_run`
(`store/workflow.rs`) now links a scheduled fire only to a run of the
**same** workflow (`EXISTS` on `(community_id, workflow_id, id)` in the
existing admitted `UPDATE`). Before this, a fire for workflow B could
reference a run of A. That FK is already `NO ACTION`, so the link would
block A's explicit run delete. The only production caller
(`buzz-workflow` cron tick) attaches the run it just created for the
same workflow, so live behavior is unchanged. A mismatched attach now
returns `false` like any other non-match, and the caller already treats
that as best-effort.

## FK audit (all 12 delete actions)

| Child FK | Action | Parent removal path → handling |
|---|---|---|
| `scheduled_workflow_fires → workflows` | CASCADE | Workflow delete
removes fires explicitly (#8212) |
| `workflow_runs → workflows` | CASCADE | Explicit (#8212) |
| `workflow_approvals → workflows` | CASCADE | Explicit (#8212) |
| `workflow_approvals → workflow_runs` | CASCADE | Explicit, including
cross-workflow approvals (#8212) |
| `join_policy_acceptances → relay_members` | CASCADE | Explicit (#8212)
|
| `channel_members → channels` | CASCADE | Single-channel removal is a
soft delete. The community purge deletes members before channels.
**Pinned here.** |
| `personal_read_frontiers → personal_read_accounts` | CASCADE | No
single-account hard delete exists. The purge deletes frontiers before
accounts. **Pinned here.** |
| `personal_read_frontiers → channels` | CASCADE | Same as above.
**Pinned here.** |
| `users.agent_owner_pubkey → users` | SET NULL | The only production
hard delete of users is the purge deleting all of a community's users in
one statement. **Pinned here** (owner + owned agent). No single-user
hard delete exists. |
| `product_feedback → communities` | SET NULL | Communities are
tombstoned, never hard-deleted. The purge already nulls feedback
`community_id` explicitly. **Pinned here.** |
| `community_deletion_manifest_keys → community_deletion_requests` |
CASCADE | Requests are retained. `mark_logically_verified` deletes
chunks explicitly, and the chunk guard trigger is unchanged. **The
existing lifecycle test now runs with FK actions retired.** |
| `community_deletion_executor_heartbeats → community_deletion_requests`
| SET NULL | Requests are retained, so this action is never reached.
**Pinned here:** the heartbeat stays linked through the purge. |

Audit method: searched `crates/**/*.rs` for `DELETE FROM` against each
parent table. Every direct `DELETE FROM communities` / `users` hit is in
`#[cfg(test)]` fixtures. Production removes rows only through the scoped
purge loop in `store/deletion.rs` and the channel soft delete in
`store/channel.rs`.

**Not added:** per-parent delete APIs. They would duplicate the
community purge for parents that are never hard-deleted. I also left out
a source-text "no hard delete" policy test, because it would pass
without any production fix. If a single-user, channel, read-account,
request or community hard delete is ever added, it has to clear
`agent_owner_pubkey` (only that column) and delete these children
explicitly first.

## Tests

- `attach_rejects_run_from_another_workflow`: a claim for B can't be
linked to A's run, and the fire stays unlinked.
- `purge_removes_fk_children_explicitly_without_fk_actions`: on the
retired-FK schema, `channel_members` and `personal_read_frontiers`
children are seeded through an admitted transaction, and then the
production quiesce → fence → purge runs. Every child must be deleted
explicitly, both users must be removed, feedback must survive with
`community_id = NULL`, and the retained request's heartbeat (selected by
`executor_id`) must stay linked. The quiesce barrier against open
admitted writers is already pinned by
`begin_quiescing_waits_for_open_admitted_writer_note_update`; this test
does not re-claim it.
- `manifest_key_chunks_bind_freeze_execution_and_cleanup` now retires FK
actions first.

Each test was checked to fail when its production behavior is removed:
dropping the `EXISTS` guard, dropping `personal_read_frontiers` from the
purge order (`23503`), dropping feedback provenance clearing, and
dropping the explicit manifest chunk delete. All four failed as
expected.

## What got simpler

The production change is one predicate. No new concepts or APIs. The FK
audit is now settled, so the follow-up migration can drop all 12 actions
at once. No new delete code was needed.

**Identified debt (pre-existing, outside this diff):** the cron tick in
`buzz-workflow/src/lib.rs` logs only `Err` from
`attach_scheduled_workflow_run`; an `Ok(false)` (no matching unlinked
claim) leaves the fire unlinked without a trace.

**Identified debt (unrelated, pre-existing):**
`writer_pool_rejects_non_read_committed_database_default` hangs with no
active query on clean `177551dda` as well (bounded after ~270 s on both
checkouts).

## Verification (Blox, at the exact tree of 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 |
| `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` | 510 pass, 2 fail: the
pre-existing hang above, plus one 150 ms `PoolTimedOut` in
`routed_fallback_spends_one_acquire_budget_when_aurora_cache_is_cold`
(pool setup under full-lane load; it passed on the clean-baseline lane
and passes in isolation at this tree, 1/1 in 1.7 s) |

The new tests are selected by the `postgres-ci` nextest filter
`(test(/postgres_tests::/) or binary(/^postgres_/)) and not
test(/(^|::)external_infra[^:]*::/)`.

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:28:13 -05:00
Luke Tornquist
193fda22f5 fix(db): seek replaceable heads by channel (#9147)
## Summary

`replace_addressable_event_under_lock` read and superseded a replaceable
coordinate's head with `channel_id IS NOT DISTINCT FROM $4`. A btree
can't use that as an index condition, so the read filtered every live
row of the `(kind, pubkey)` across all channels. The relay signs every
channel's state events (39000–39002) with one key, so each channel-state
write walked the whole community's relay state for that kind. Both
`Db::replace_addressable_event` and the relay's locked group-state
snapshots go through this function.

The predicate is now spelled per case, as `channel_id = $4` or
`channel_id IS NULL`, and `$4` is bound only for the first. The head
read becomes an index seek to one channel instead of a filtered walk. It
reads the same rows as before.

The `WHERE` scope and the head read are shared as macros
(`replacement_scope!`, `replacement_head_sql!`), so the plan test checks
the same predicate production runs. The supersede statement is spelled
inside the function itself, which takes `&mut AdmittedTx`, as the
guarded-write source scan requires. `superseded_with_mentions_sql!` now
takes an `expr`, so it accepts a `concat!`.

## Tests

- `replacement_channel_predicate_is_an_index_condition` seeds one relay
head per channel plus one channel-less head and refreshes the
statistics. Then, for both cases, it checks that the head read and the
supersede each have `channel_id` in an `Index Cond`. With `IS NOT
DISTINCT FROM`, the planner walks the newest-first `(pubkey, kind)`
index and applies the channel as a `Filter`. On an empty table it does
that even with the per-case spelling, which is why the test needs the
fixture.
- `addressable_replacement_supersedes_only_its_own_channel_scope`: a
channel write supersedes only that channel's head, and a channel-less
write is ordered against the global head only.
- **Mutants**, each killed by its test:
  - the scope restored to `IS NOT DISTINCT FROM`;
  - the global scope ignores the channel;
  - the in-channel supersede ignores the channel.

## What got simpler

- One predicate per case instead of a NULL-safe comparison the index
can't use.
- The head read and supersede share one scope definition.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:13:35 -05:00
Luke Tornquist
6878520604 buzz-db: check events created_at floor in app writers (phase 1) (#8325)
## What

This is phase 1 of 2 for retiring the `events_created_at_floor` deferred
constraint trigger and its `events_created_at_floor_guard()` function
(migration 0021). The invariant now holds in the app writers. **The
trigger, function and `buzz.created_at_floor` GUC arming all stay** as
the backstop while pods run mixed versions. A later PR drops them.

One helper, `replica_fence::guard_event_created_at_floor(&mut
AdmittedTx, created_at, channel_id)`, runs on the admitted write
connection. If `created_at < clock_timestamp() - CREATED_AT_FLOOR_SECS`,
it rejects the write with the typed, non-retryable
`DbError::CreatedAtFloorRejected`. It uses the same 960 s constant as
the GUC and the fence wall. Channel-less rows skip it and cost no query.

**Why checking at insert time is enough:** the fence wall is
`min(oldest_xact_start, S) - floor - 5s`. A writer transaction that is
open during the probe's activity scan is bounded by its own
`xact_start`. A transaction that starts after the scan samples a clock
later than `S`. So any `clock_timestamp()` sample taken inside the
writing transaction is as strong as the trigger's commit-time sample.
This needs no commit hook, no candidate-row tracking and no ordering
against the TTL refresh, and `AdmittedTx::commit` is unchanged.

| Site | Check placement |
|---|---|
| `store/event.rs` `insert_event_on` | after the `ON CONFLICT DO
NOTHING` INSERT, only when a row was inserted, before follow-ups |
| `store/event.rs` `insert_event_with_thread_metadata_tx` | after the
INSERT, only when a row was inserted, before follow-ups and thread
metadata |
| `store/replaceable.rs` parameterized replacement | after the `ON
CONFLICT DO NOTHING` INSERT, only when a row was inserted, inside the
supersede savepoint (a rejection rolls back to it and restores the old
head) |
| `store/replaceable.rs` addressable replacement | after the `ON
CONFLICT DO NOTHING` INSERT, only when a row was inserted, before
follow-ups (the caller's rollback restores the old head) |
| `store/channel_members.rs`
`LockedMemberSnapshot::replace_member_event` | before the old head is
superseded |

**Writer inventory:** there are 7 production `INSERT INTO events`
functions. The other two are structurally `channel_id = NULL`: `push.rs`
`accept_lease_event` (kind 30350) and `relay_members.rs`
`publish_nip43_membership_locked` (kind 13534). Both write a literal
`NULL` for `channel_id` in their INSERT SQL, and the policy exempts them
only while that NULL sits at the `channel_id` position. No production
UPDATE writes `events.created_at` or `events.channel_id`, and the events
`ON CONFLICT` clauses are `DO NOTHING`.

**Client-visible outcome is unchanged.** The trigger's SQLSTATE 23514
surfaced as a generic DB error, which the relay maps to
`IngestError::Internal` (WS `OK false` / HTTP 500). The new variant
follows the same path. Relay mappings are untouched.

**`scripts/seed-admin-dashboard.sh`** writes a channel event with
`created_at = 1790000000` through raw psql, and it accepted any
`PGHOST`. It now refuses non-local hosts (`localhost`, `127.0.0.1`,
`::1` and Unix socket paths are still allowed), a non-empty `PGHOSTADDR`
or `PGSERVICE`, a multi-host `PGHOST`, and any `PGDATABASE` that is not
a plain name (psql treats URI and `key=value` `-d` values as connection
strings that override `-h`). Both psql paths pass `-X`, so a psqlrc
can't `\connect` elsewhere after the guard.

## Tests

There are eleven new PG tests in `store::event_floor_postgres_tests`.
Each runs in its own per-test database with `ALTER TABLE events DISABLE
TRIGGER events_created_at_floor`, and a `pg_partition_tree` check
asserts that every partition clone is disabled, so the trigger can't
hide a missing app check.
- `insert_event_floor_rejects_old_and_accepts_fresh`,
`thread_metadata_event_floor_rejects_old_and_accepts_fresh`,
`parameterized_event_floor_rejects_old_and_accepts_fresh`,
`addressable_event_floor_rejects_old_and_accepts_fresh`,
`member_snapshot_event_floor_rejects_old_and_accepts_fresh`: each
rejects a too-old event with the typed error, confirms no row was
written, then accepts a fresh event.
- `insert_event_floor_accepts_expired_duplicate`,
`thread_metadata_event_floor_accepts_expired_duplicate`: replaying an
already-stored event whose `created_at` is now below the floor returns
`Duplicate` (inserted = false), leaves one row and runs no thread
follow-ups.
- `parameterized_replay_of_soft_deleted_aged_event_is_a_duplicate`,
`addressable_replay_of_soft_deleted_aged_event_is_a_duplicate`:
replaying a replacement whose stored row is soft-deleted and has aged
below the floor returns a duplicate, not a floor rejection, as the
trigger did (it never fired on `ON CONFLICT`).
-
`cluster_global_event_floor_held_transaction_cannot_write_below_probe_wall`:
runs a real heartbeat probe while a writer transaction is open. It
asserts that the wall is bounded by that writer's `xact_start`, that a
below-wall event is rejected, and that a near-floor event sampled after
the probe lands above the wall.
- `event_floor_samples_statement_clock_after_transaction_start`: waits
on the database until a boundary timestamp that was valid at BEGIN
expires (normally ≤1.1 s), so `now()` would pass where
`clock_timestamp()` fails.

Source policy (`observability_source.rs`): every channel-bearing
production events INSERT in any crate's `src` must call the helper, no
production UPDATE may assign `created_at` or `channel_id` (including
`ONLY`, schema-qualified, aliased and row-constructor forms; quoted
identifiers are normalized), the helper must use `clock_timestamp()` and
the shared constant, and the seed script must refuse a remote host.
Negative fixtures cover each rule.

Each check was confirmed to fail when its fix is removed. All of these
mutants failed on assertions:
- removing the helper from all five writers, which failed all seven PG
tests
- switching `clock_timestamp()` to `now()`, which failed both the clock
PG test and the clock policy
- removing one call
- adding a `created_at` UPDATE
- disabling the policy self-test
- removing the seed guard
- (review round 2) restoring the pre-INSERT check placement, which
failed both duplicate-replay tests; the round-1 UPDATE matcher,
quoted-identifier normalization, buzz-db-only scan, NIP-43 bind
exemption, process-wide canvas base and each seed override were each
restored and failed their tests
- (review round 3) restoring the round-2 seed script, which failed the
extended seed test on its URI and key/value `PGDATABASE` cases;
restoring the script without `-X`, which failed the control's `-X`
assertion

**Fixture changes:** about 40 existing buzz-db PG tests seeded
historical rows (fixed old timestamps) through the serving writers. The
trigger never fired on them because the test pool is unarmed. They now
seed through a `#[cfg(test)]` raw-SQL helper,
`test_support::insert_historical_event` (and
`insert_historical_event_with_thread_metadata` for thread fixtures),
which keeps admission, follow-ups and mentions. The canvas CAS fixtures
keep their logical seconds and ties but each test passes its own fresh
base. The existing trigger backstop tests still exercise raw armed
INSERT/UPDATE plus COMMIT returning 23514.

The new PG tests are selected by the `postgres-ci` filter
`(test(/postgres_tests::/) or binary(/^postgres_/)) and not
test(/(^|::)external_infra[^:]*::/)`. The `cluster_global_` test also
joins the existing serial group.

## Behavior notes

- Prepared transactions (2PC) are covered only by the retained trigger,
which runs at PREPARE. The insert-time app guard runs earlier, and no
app writer issues `PREPARE TRANSACTION`. The comment in
`replica_fence.rs` now says so, so the trigger drop has to keep this
case covered.

- One extra round trip for each newly inserted channel event. Duplicate
replays add none.
- Ordinary and thread event writes check the floor only for newly
inserted rows, before follow-ups, mentions or thread metadata. Replaying
an already-stored id stays `Duplicate` even when its timestamp has aged
below the floor, as with the trigger. (Internal writers such as the
admin outbox worker do replay relay-signed events with their original
`created_at`.) A too-old new row returns the non-retryable
`CreatedAtFloorRejected`, and the owning transaction rolls back; every
current caller propagates the error and drops the transaction. The
transaction-composition seam documents that contract.
- Replacement writers check after their INSERT, only when it inserted a
row, so a replay of any stored id (live or soft-deleted) stays a
duplicate. The locked roster writer checks before the old head is
superseded.
- The trigger is stricter for a row that ages below the floor between
the app check and COMMIT. The proof above doesn't need that strictness,
and phase 2 gives it up.

## What got simpler

The NIP-43 insert drops a bind for a literal `NULL`, the floor and
follow-up policies share one workspace walk, and the canvas fixtures
lose their process-wide `OnceLock`. No commit-time machinery was added:
no candidate tracking, commit hook, cleanup protocol or new lock.
Test-only historical writes now go through one helper instead of being
scattered through the serving APIs. Nothing could be deleted in this
phase because mixed-version pods still rely on the trigger. **Phase 2**
drops the trigger and function, the GUC arming,
`verify_floor_guard_catalog` / `verify_floor_guard_behavior` and the
schema reconciliation entries. Its deploy gate: the whole fleet on this
binary, no rollback expected, and the replica breaker held closed
through the drop.

**Identified debt (pre-existing, outside this diff):** three
`buzz-relay` `handlers::group_state_postgres_tests::*` tests fail with
`ensure community: Sqlx(PoolTimedOut)` on the Blox host. They fail the
same way on a clean checkout of the base (`state.rs` test pool, 100 ms
acquire timeout).
`writer_pool_rejects_non_read_committed_database_default` and
`writer_pool_metrics_stop_after_session_timeout_setup_failure` hang on
that host at base too.

## Verification

Head `b046df76d` (after the placement fix and main's newer test
fixtures): on Blox, fmt, clippy and buzz-db unit (241/241) pass, and a
filtered buzz-db PG lane over the floor tests and every converted
fixture passes 88/88. CI is running at this head.

Earlier full gate, at tree `67c4fe5e1` + this diff, before the placement
fix:

| Gate | Result |
|---|---|
| `cargo fmt --all -- --check` | pass |
| `cargo clippy --workspace --all-targets -- -D warnings` | pass |
| `cargo nextest run -p buzz-db --lib` | 167/167 |
| `cargo nextest run -p buzz-db --test observability_source` | 22/22 |
| `scripts/test-postgres-test-discovery.sh` | pass |
| `scripts/postgres-test-run.sh -p buzz-db` (excluding the two host
hangs) | 517/517 |
| `scripts/postgres-test-run.sh -p` buzz-admin / audit / deletion /
push-gateway / search / workflow | all rc 0 (4, 7, 11, 11, 20, 2) |
| `scripts/postgres-test-run.sh -p buzz-relay` | 402 pass, 3 fail (the
pre-existing `PoolTimedOut` failures above) |

Local gates used a reverted `rustls` lock bump, because the build mirror
lacks 0.23.46. The committed `Cargo.lock` is unchanged, and CI uses the
real lock.

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:36:59 -05:00
Tom Brow
e715fbb362 fix(relay): treat empty filter sets as match-nothing in SQL (#9342)
Fix for a COUNT regression introduced by #9339 (now on main), found in
its review.

With #9339, a filter with a nonempty `#a` takes the exact SQL COUNT
path. But `filter_to_query_params` dropped an empty `authors`, `ids` or
`#e` list and never represented an empty `#p`, `#d` or unpushed tag set.
So `{"kinds":[7], "#a":[A], "authors":[]}` counted every reaction to
`A`, while REQ (which post-filters) correctly returned nothing. Before
#9339 that COUNT returned 0. The same gap already existed for filters
without `#a`.

Any empty `authors`, `ids` or tag set now maps to the existing `kinds:
[]` match-nothing sentinel, which every read (REQ, COUNT, `/query`,
`/count`) answers without a query. An empty string value such as `"#d":
[""]` is still a real constraint.

Why nothing gets worse: only filters that provably match nothing change,
and they now skip the database instead of reading or counting.

### Validation

Added tests:
- Unit table over empty `authors`, `ids`, `#e`, `#p`, `#d`, `#h`, `#k`
and `#t`, each with and without `#a`, plus `"#d": [""]`. It fails with
the sentinel disabled.
- Postgres table: WebSocket and HTTP COUNT are 0, and REQ and `/query`
are empty, for each empty set beside a matching `#a` and for
`{kinds:[7], authors:[]}`. The first commit contains only the tests.

Existing workspace unit tests pass (pre-push). The Postgres lanes run
separately on an isolated cluster.

🤖 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:21:21 -08:00
Tim Mellor
0e6037c74d buzz-cli: add --before and --before-id to messages search (#9382)
## Summary

`buzz messages search` returns at most the newest 100 matches after
`--since` and had no end time. So an author-only search could never
reach older messages. This adds two flags to page back in time:

- `--before <unix ts>` — sent to the relay as the filter's `until`
(inclusive).
- `--before-id <event id>` — requires `--before`. Sends the relay's
existing `before_id` cursor, so events from the same second are neither
repeated nor skipped. This is the same `(until, before_id)` cursor that
`social notes --before/--before-id` already uses.

Without the new flags, the filter and output are unchanged.

### How to page

1. Run `buzz messages search --author <key> --since <ts> --before <now>
--limit 100`.
2. For the next page, pass the last result's `created_at` as `--before`
and its `id` as `--before-id`.
3. Stop when a page comes back empty.

Results are newest first, and events from the same second are ordered by
ascending id. That matches the relay's cursor order.

### `--query` rule

`--before-id` with `--query` is a usage error (exit 1). Full-text
results are ranked by relevance, not time, and the relay's search path
does not apply `before_id`. `--before` on its own still works with
`--query` as a time bound.

No relay change was needed: the relay's non-search query path already
honors `until` and `before_id`.

## Tests

- New unit test for the filter the command builds. It covers: no flags
(unchanged filter), `--before` mapping to `until`, `--before-id`
lowercased, `--before` with `--query`, and the usage errors
(`--before-id` with `--query`, without `--before`, malformed id).
Removing the `before_id` line makes it fail.
- New clap test: `--before`/`--before-id` parse, and `--before-id` alone
is rejected.

## Checks run

- `cargo fmt --all -- --check`
- `cargo clippy -p buzz-cli --all-targets -- -D warnings`
- `cargo test -p buzz-cli` (686 passed)
- Ran the built CLI against a live relay. Paged an author-only search
back across several full pages: no overlaps at page boundaries, and the
union matched an independent time-sliced query exactly (no gaps). A
manual check confirmed the relay applies `before_id` at a shared
timestamp.

buzz-review-completed

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

Signed-off-by: Tim Mellor <117199716+tmellor-block@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:58:58 -08:00
Joah Gerstenberg
a09b84d23d feat(relay): agents cannot write in DMs except with their owner (#9371)
## Summary

Agents stop writing in direct messages, except a DM with only their
owner. This is the relay-side backstop for block/buzz-app#3261, which
takes away the app agents' DM tools. An agent holding its own key could
still sign DM events directly, and only the relay can stop that.

A key counts as an agent when it has a stored owner
(`users.agent_owner_pubkey`, written when the agent authenticates with a
NIP-OA owner attestation). For those keys:

- **Writes into a DM channel** are refused with `restricted: agents
cannot post in direct messages; start a Solo chat that includes your
owner instead`. The check sits in `check_channel_membership` for
`ChannelWrite::Post`, so it covers stream messages, reactions,
deletions, typing and other channel ephemerals, artifact moves and edit
validation. Non-DM channels skip it at no extra cost.
- **Workflow `send_message`** (which posts as the workflow owner and
checks `may_post` directly) applies the same rule before persisting, so
an agent can't route a DM post through a workflow.
- **Put-user (9000) and edit-metadata (9002)** skip the generic gate, so
they get their own check in a DM: an agent never adds DM members with
9000 (an addition to an owner-only DM always widens it), and edits topic
or purpose only in its owner-only DM (the edit posts a system message
with the text).
- **Huddle admission** checks `may_post` directly, so it applies the
same rule to the huddle channel and its lifecycle parent.
- **DM open (41010) and DM add-member (41011)** are refused unless the
resulting participant set is exactly the agent and its owner.
- **Exemption:** a DM whose live members are exactly the agent and its
owner stays open (for example, a personal assistant's home chat).
- Lookup failures fail closed. Confirmed agent owners are cached per
community (`agent_owner_cache`, 5 min TTL). The link is first-write-wins
and never changes once set. A missing link is never cached, because
another relay process may write it later. `link_agent_owner` primes the
cache.

Humans are unaffected: they can still open DMs that include an agent and
post in them. The agent answers elsewhere.

Not covered:
- A key that never presented an owner attestation has no stored owner
and looks human.
- The huddle join commit re-check (4e) doesn't repeat the DM rule; the
pre-join admission check enforces it.
- Agents also can't delete their own earlier messages in a non-owner DM
via kind 5, since deletions pass the same `Post` gate.

### Related issue

Companion to block/buzz-app#3261. AGNTOPS-780.

### Testing

New Postgres ingest tests (`handlers::ingest::postgres_tests::agent_*`),
run locally:
- An agent is refused in a 1:1 DM with someone else and in a group DM
with its owner; the humans in both still post.
- An agent posts in a DM with only its owner.
- An agent can open a DM only with its owner; a human can still open a
DM with an agent.
- An agent can't add members to its owner DM, through 41011 or 9000.
- An agent can't set the topic in a DM with a stranger.
- An agent is refused admission to a huddle in a DM with a stranger and
admitted in its owner-only DM; a human still joins.
- An agent's workflow `send_message` is refused in a DM with a stranger
and allowed in its owner-only DM.
- An owner linked after a lookup miss is seen on the next lookup (no
negative caching).

`cargo clippy -p buzz-relay --all-targets -D warnings` is clean. The
other ingest and command-executor tests pass locally (214), except two
that fail only because of my local database: one needs the desired-state
FTS schema, and the other fails creating its restricted role in setup.
Neither reaches DM code. I pushed without the local pre-push `just
test-unit` lane because a `buzz-cli` unit test hung there for about 30
minutes; CI runs that lane.

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

---------

Signed-off-by: Joah Gerstenberg <joah@squareup.com>
Co-authored-by: Hertz <c6741012416ef5c49a865db79682113385c5fb998e8c890234fb442b59e22748@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:18:49 -06:00
Tom Brow
1b190d21fc fix(relay): bound each cross-node delivery attempt (#9305)
**Context:** #9302 (merged) stopped the relay from closing connections
when cross-node fan-out falls behind. It also removed the 30 s delivery
deadline. This PR is the fix from the review of #9302.

**Problem:** Since #9302, a fan-out worker waits for the access-gate
database read with no time limit. If a database connection stops
answering in the middle of that read, the worker never continues. Its
queue fills, and one sixteenth of the node's channels get no live events
from other nodes until the relay restarts. Before #9302 the deadline cut
that delivery off after 30 s.

**Fix:** Each delivery attempt has a 30 s limit
(`MAX_DELIVERY_ATTEMPT`), measured from when the worker starts it. When
the limit passes, the relay counts the event in
`buzz_multinode_fanout_dropped_total{reason="stale"}`, resyncs the
artifact syncs the event matched, and continues with the next event. It
closes no connection. An event that only waits in the queue is still
delivered late, as #9302 intends. The queue-full drop and the new stale
drop share one helper.

### Validation

- Added test:
`hung_delivery_is_dropped_at_the_bound_and_the_worker_moves_on` drives
the production worker with a database that accepts the connection and
never answers. It checks that the delivery stops at the limit, is
counted, resyncs the matched sync, closes nothing, and that the next
event on the same worker is delivered. With the limit removed it fails
(the worker waits out the pool's one-hour acquire timeout instead).
- The other `handlers::multinode_fanout` tests pass. The full local
`buzz-relay` suite was not run; CI on this head covers it.

🤖 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>
2026-11-11 21:10:40 -08:00
Brad Seiler
4c60be6a1e Enforce single-community relay mode (#9149)
## Summary

Add `BUZZ_MULTI_COMMUNITY_RELAY` (default `true`, strict boolean). With
`false`, ordinary HTTP/WebSocket traffic serves only the community at
the normalized `RELAY_URL` authority, including a nondefault port. Other
hosts receive a generic 404 before tenant lookup or handler execution.

Authenticated admin/operator inventory and cleanup remain available
through their configured authorities. Existing extra rows do not prevent
startup and are not deleted automatically. Canonical bootstrap and
legacy convergence on the existing canonical community remain available;
operator creation is disabled. Invite minting and git callbacks also
check their target community. Availability retains its free-name meaning
and adds `can_create` to report policy permission.

Changes require restarting every serving revision. An older image can
ignore this setting. Removing it, setting it true, or rolling back to an
older image can reopen serving and creation. Keep operator/admin
authentication configured throughout rollout and rollback.

### Current draft gates

Published candidate `8319e9a4b299deb2bb2cb72400a2c6aff396b362` includes
the independently reviewed deletion-fixture correction. Normal push
hooks and all local validation passed at this head: 2,028 package tests,
full `just ci`, all 1,393 isolated UTF-8/UTC PostgreSQL tests and the
binary build. A running local relay passed 16 HTTP/WebSocket and signed
admin/operator assertions, including extra-host denial and cleanup
access. Hosted PostgreSQL and full CI must still pass on this head.
Human acceptance and the background-work decision remain open; keep this
PR draft.

Background workers currently retain their prior behavior:
cleanup/retention/recovery/revocation continue, as do scheduled
workflows, reminders, configured push/listener delivery, storage-usage
reporting and artifact sync under existing lifecycle rules. Whether to
pause ordinary background work for extras is an open product decision
and an acceptance gate. No worker changes are included yet.

### Rollout and acceptance

1. Resolve the background-work decision, finish validation/review, and
complete the repository-required human test.
2. Obtain separate staging rollout authority, use an immutable
supporting image and explicit false on every serving revision, and
review generated configuration.
3. Verify an extra host returns 404 for HTTP and WS; canonical HTTP/WS
and NIP-FI still work. Verify authenticated admin reads/actions and
operator inventory/archive/delete still reach an extra community.
4. Only after staging acceptance, obtain separate production rollout
authority. This draft grants no merge, deployment or cleanup authority.
5. Rollback by returning the setting to true or the previous image
explicitly reopens serving/creation. Preserve operator/admin access.

### Related issue

No duplicate creation-only policy PR found in the open-PR search.
Related creation surface work: #2398.

Creation-only validation is superseded; see its [historical CI
run](https://github.com/block/buzz/actions/runs/42123475841). It does
not qualify the current candidate.

Generated with Codex

---------

Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Sarnow <1894dcbafaa4df1ac607a9bf879ac0b7d77fbccb0e0f4619ecc252c8adbad8a2@seiler-test.communities.public.builderlabstaging.xyz>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
2026-11-12 00:10:38 +00:00
Jemiah Westerman
695c1c3aae fix(relay): match #a tag filters in SQL before LIMIT (#9339)
## Summary

**Intent:** let clients find and count reactions to an **addressable
event** at the SQL layer. Addressable events are NIP-01 kinds
30000–39999, which NIP-33 called "parameterized replaceable events".
Clients reference one by its address, not its event id.

An addressable event is identified by its address `<kind>:<pubkey>:<d>`.
Each edit publishes a new event with a new id at the same address. A
reaction (kind:7) that tags the address with `a` therefore still applies
after the target is edited. A reaction that tags only the current
revision's id with `e` is left behind on the old revision.

Use cases:
- **Agent personas (kind:30175).** A ⭐ on a shared persona is a kind:7
tagged `["a", "30175:<owner>:<slug>"]`. A client that lists shared
personas by popularity needs `{kinds:[7], "#a":[...]}` and the matching
COUNT to return every star across persona edits, not only stars on the
current revision.
- **Other addressable kinds**, such as teams and channel metadata, work
the same way with no extra code.
- **Replaceable events, such as user profiles.** Kind:0 profiles and
kind:10100 agent profiles are *replaceable* (kinds 0, 3 and
10000–19999), not addressable. NIP-01 still gives them an `a` address
with an empty `d`, `0:<pubkey>:`, so reactions that tag a profile that
way are matched by the same filter.

Before this change, the relay applied `#a` only after the SQL `LIMIT`. A
selective read fetched the newest kind:7 rows across the whole community
and then dropped the ones that didn't match. It could return fewer than
`limit` matches, or none, while older matches existed. COUNT also could
not take its exact fast path.

What changed:

- **`EventQuery.a_tags`** (buzz-db) works like `e_tags`. It is an exact
positional tag match (`tag->>0 = 'a' AND tag->>1 = ANY(..)`) with JSONB
`@>` as the prefilter on the existing GIN index `idx_events_tags_gin`.
  - **No schema change, migration or backfill.**
- It gets the same MATERIALIZED CTE fence as `#e`, so the planner cannot
walk `created_at` backward looking for a rare match.
  - It reads the table whole rather than recent partitions first.
  - It is counted in `count_events_sql`.
  - An empty set matches nothing, as the NIP-01 post-filter does.
- **`filter_to_query_params`** fills `a_tags` for every filter, and
**`filter_fully_pushable`** treats `#a` as pushed. REQ, COUNT and the
HTTP bridge `/query` and `/count` all go through these two functions.
- **`per_channel_scope`** now skips per-channel reads for every fenced
query, through a shared `reference_tag_fence` helper. Before this, it
excluded `#e` reads explicitly, and `#a` with a multi-value `#h` would
have wrapped the fence around the per-channel lateral, which is invalid
SQL.

Not included: `#k` and other low-cardinality tags. Postgres's estimate
for JSONB `@>` assumes any match is rare, so pushing a common value
could switch to a slower plan. They remain post-filters.

### Related issue

None found.

### Testing

- `req.rs` unit test: `#a` maps to `a_tags` (including empty and absent)
and is fully pushable; `#a` + `#k` is not.
- buzz-db shape tests: an `#a` read is fenced, COUNT applies the match,
an `#a` read is never split into recent and older passes, and `#a` makes
a read ineligible for per-channel scope. An empty `#a` is answered
without a database read.
- buzz-db Postgres: an `#a` case added to
`pushed_down_tag_filters_reject_positional_decoys`, covering query and
COUNT.
- New `handlers/tag_pushdown_postgres_tests.rs`:
- REQ returns an older `#a` match ahead of a full page of newer
reactions to another address. COUNT is exact, and an empty `#a` counts
0. This test fails when `a_tags` is removed from
`filter_to_query_params`.
- REQ and COUNT with `#a` + a multi-value `#h`. This test fails, with
`CLOSED database error`, without the `per_channel_scope` fix.
- Full buzz-db and buzz-relay suites, unit and Postgres lanes, run
locally.
- Live check against a local relay built from this branch, over
WebSocket with NIP-42 auth. Two reactions to one address (each on a
different head event, as after an edit) and six newer reactions to
another address were published. `REQ {kinds:[7], #a:[needle], limit:2}`
returned exactly the two needle reactions, newest first. COUNT returned
2 for the needle, 6 for the hay and 0 for an empty `#a`. `#a` + `#e`
with `limit:1` returned the newest needle reaction.

buzz-review-completed

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

Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:41:05 -08:00
Brad Seiler
75d38b6c2d chore(release): release Buzz Relay version 0.3.0 (#9362)
## Summary

Prepare Buzz Relay 0.3.0 from freshly fetched `main` at
`e5dee91c90fdc5f81f04fd609b7c99e31fa7570f`. Bump only the relay crate
version and its root lockfile entry from 0.2.1 to 0.3.0, and prepend the
relay changelog. Desktop, CLI, mobile, Helm, and dependency versions are
unchanged.

The changelog contains all 297 non-merge commits selected by the relay
release recipe from `relay-v0.2.1` through the pinned base. Internal
ticket identifiers were removed from historical subjects to follow the
repository's public-source policy; entries and PR/full-SHA source links
are preserved. [Full source
comparison](https://github.com/block/buzz/compare/relay-v0.2.1...e5dee91c90fdc5f81f04fd609b7c99e31fa7570f).

### Related issue

Release preparation request; no duplicate release 0.3.0 PR found.

### Testing

- `just bump-relay-version 0.3.0`: completed; the lockfile changes only
the `buzz-relay` version, without transitive dependency updates.
- `cargo metadata --locked --no-deps --format-version 1`: confirms relay
version 0.3.0.
- `git diff --check` and mandatory pre-commit formatting: passed.
- `bash scripts/test-release-ref-contract.sh` passed in a clean local
clone of `3def95c9435b2884c01446fe1a1f92f4fe9960fc`.
- Mandatory pre-push checks passed at
`3def95c9435b2884c01446fe1a1f92f4fe9960fc`. Independent review of the
commit and published head/body/draft state found no defects.
Repository-wide `just ci` passed at
`3def95c9435b2884c01446fe1a1f92f4fe9960fc` after reproducible dependency
setup; the worktree remains clean. [GitHub CI attempt 2
passed](https://github.com/block/buzz/actions/runs/43092559585/attempts/2)
at that exact head. The prior attempt failed before tests in three
artifact downloads; retrying the failed jobs resolved the service errors
without code changes. Local checks and independent review passed; human
acceptance remains separate. The existing ready state is preserved.
Local integration validation is blocked: Docker Desktop starts and its
daemon answers, but managed sign-in policy denies container access until
the operator signs in.

### Release hazards

Preparation only: **merging this PR automatically creates `relay-v0.3.0`
and starts image publication**, including stable version aliases and
`latest`/`debug-latest`. No merge, tag, or deployment is part of this
preparation.

The [relay
tagger](e5dee91c90/.github/workflows/auto-tag-on-release-pr-merge.yml (L64-L105))
tags the merge commit rather than the reviewed PR head. Changes arriving
on main before merge would also ship; the changelog is accurate only
while main remains at the pinned base. Regenerate and revalidate before
merging if main advances. The branch must stay `relay-release/0.3.0`:
the tagger derives the version from its name and does not compare it
with the crate manifest.

The recipe's changelog path selection omits some shipped components,
including `buzz-feature-flags`, `buzz-datastore-tracing`,
`buzz-deletion`, `buzz-relay-mesh`, `Dockerfile`, `web/`, and root
dependency lockfile changes. Use the full comparison above for the
complete source change set. The Helm chart's existing `appVersion:
"0.1.0"` remains a separate follow-up.

The release recipe's bump and changelog generation were executed in an
isolated worktree. Publication uses an ordinary push and explicit draft
PR instead of the recipe's reset/force-push/non-draft publication steps.
No release automation changes are included.

Generated with Codex

Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
2026-11-11 17:43:44 -05:00
Tom Brow
2c5c8343ef fix(relay): bound invite preview host lookup (#9308)
**Context:** #9306 (merged) added link-preview tags to the invite page.
To build the media URLs, the relay looks up the community for the
request host. This fixes a problem found in our review of #9306.

**Problem:** The invite page waits for that lookup with no time limit.
When the database is slow, the lookup can take as long as the pool
acquire timeout (3 s) plus the statement timeout (120 s by default).
During that time, a person who opens an invite link gets no page. Before
#9306, this page did not use the database.

**Fix:** The lookup gets 250 ms. If it does not finish, the relay sends
the page without the preview tags. A healthy indexed host lookup
finishes well inside that, so crawlers still get the tags, and nothing
else changes: the media route, the router and the build are untouched.

### Validation

- Added test: a host whose lookup never finishes gets the plain page.
Without the timeout, this test hangs (confirmed locally; it was killed
after 30 s).
- The existing `invite_preview` and router invite tests pass.

🤖 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>
2026-11-10 21:15:13 -08:00
Dave Grochowski
47674dc322 fix(relay): saturate filter limits instead of casting (#9230)
## Problem
Four request paths converted a client-supplied `usize` filter limit with
an inline `as` cast before clamping: `(l as i64).min(max)` (REQ query
params, bridge feed) and `(l as u32).min(max)` (WS NIP-50 search, bridge
channel window).
- A limit above `i64::MAX` turns negative (`usize::MAX as i64 == -1`).
On REQ and the bridge `/query` general path it reaches Postgres as
`LIMIT -1`, which fails the query. On the bridge feed it trips
`feed_count >= limit`, so the feed comes back empty.
- A limit that is a multiple of 2^32 wraps to `0` through `as u32`. That
returns no rows (one row in the window, via `.max(1)`) instead of the
page max.

Bridge thread and HTTP search already clamped before casting. COUNT
drops the row limit, so it was not affected.

## Change
- Add `buzz_core::filter::clamp_limit(limit, default, max) -> u32`. It
returns `default` when the limit is absent; otherwise it saturates the
request to `u32` and then caps it at `max`.
- Use it at every filter-limit site: `filter_to_query_params` and WS
search in `handlers/req.rs`; channel window, feed, thread and HTTP
search in `api/bridge.rs`. The inline casts are deleted, and
`BRIDGE_FEED_MAX_LIMIT` is now `u32`.
- Each site keeps its default, max and `limit: 0` behaviour. In-range
limits are unchanged.

## Testing
Failing before the fix (`cargo test -p buzz-relay --lib
huge_filter_limit`):
```
assertion `left == right` failed
  left: Some(-1)
 right: Some(1000)
test result: FAILED. 0 passed; 1 failed
```
After:
- `cargo test -p buzz-core --lib clamp_limit` → 1 passed (table test
covering absent, 0, in-range, at/over max, the u32 boundary and
`usize::MAX`)
- `cargo test -p buzz-relay --lib -- huge_filter_limit req:: bridge` →
152 passed, 0 failed (135 Postgres tests ignored)
- `cargo clippy -p buzz-core -p buzz-relay --all-targets -- -D warnings`
→ clean; `cargo fmt --all` → clean
- pre-push hooks (incl. rust-tests) passed

## Not covered
No Postgres-backed tests were run locally. The bridge call sites rely on
the shared helper's table test; they have no per-handler tests.

## Review
Every server-side read of `Filter.limit` now goes through `clamp_limit`.
The per-site default, max and `limit: 0` behaviour is unchanged. No
inline casts are left. Scores: minimalism 9, elegance 9, correctness 9.

Blockers: none.

Fixed in review:
- `PAGE_LIMIT_MAX` had been inserted between `filter_to_query_params`'s
doc comment and the function, so the doc comment ended up on the const.
Moved the const above it.
- Corrected the problem statement. The bridge feed returned an empty
feed rather than a Postgres error, COUNT was never affected, and thread
and HTTP search were already safe.

Optional:
- WS search, bridge window and bridge feed have no per-handler
regression test. Reverting one of them to an inline cast would not fail
any test.
- `bridge.rs` now has two functions called `clamp_limit`: the local
moderation `clamp_limit(Option<i64>)` and
`buzz_core::filter::clamp_limit`. They don't collide, but they are easy
to confuse.

## Exercised on a local relay

**Commit tested:** `88d76f7f1`. Dev profile, isolated harness relay on
:3030, authenticated channel member. Human rate limits were raised so
seeding wasn't throttled. I seeded 1,100 kind-9 events in one channel.
The filters were sent as raw JSON so the large integers arrived exactly.

| Path | `limit` 18446744073709551615 | `limit` 4294967296 | `limit` 50
(control) |
|---|---|---|---|
| WS `REQ` | EOSE after 1000 | EOSE after 1000 | EOSE after 50 |
| WS `REQ` with `search` | EOSE after 1000 | EOSE after 1000 | EOSE
after 50 |
| HTTP `/query` | 200, 1000 events | 200, 1000 | 200, 50 |
| HTTP `/query` with `search` | 200, 500 | 200, 500 | 200, 50 |
| HTTP `/query` `top_level` (channel window) | 200, 201 (200 + bounds
event) | 200, 201 | 200, 51 |
| HTTP `/query` `feed_types` | 200, 100 | 200, 100 | 200, 50 |

Every huge limit came back as that path's maximum. None of them produced
a database error, and none came back empty. The relay log has no error
lines, and the access log records the raw `limit` as
18446744073709551615 with `outcome:"served"`.

**Postgres-gated tests:** the PR adds or modifies none. As a related
check I ran `cargo test -p buzz-relay --lib -- --ignored limit`. Run in
parallel, it gave 10 passed and 1 failed:
`rate_limited_query_logs_one_denied_line`. That test passes on its own,
and the whole set gives 11 passed with `--test-threads=1`. It looks like
interference between tests that share the access-log capture, not a
problem with this change.

**Not exercised:**
- Bridge thread path.
- A before/after comparison against main.

Signed-off-by: David Grochowski <dgrochowski@squareup.com>
2026-11-10 22:46:43 -05:00
Logan Johnson
30e1fa47fb fix(relay): fence pending subscriptions on close or replacement (#2382)
## Summary

A REQ handler runs as a spawned task and can pause in its access checks.
Before this change it took its subscription ID only when it registered.
So:

- `REQ x`, then `CLOSE x` while the REQ was still in its access checks:
the relay sent `CLOSED x`, and then the REQ registered `x` anyway and
sent events and `EOSE` under an ID the client had closed.
- `REQ x` (A), then a newer `REQ x` (B): if A finished its checks after
B registered, A replaced B, or A's refusal retired B and sent a `CLOSED`
the client could not tell from B failing.

Now the read loop admits each REQ and sync REQ, in arrival order, before
it spawns the handler: the newest request owns the ID from the moment it
arrives. A `CLOSE` or a newer same-ID request fences an older one that
is still pending. A fenced request does not register, and does not send
`NOTICE`, `CLOSED`, `EVENT` or `EOSE` for the ID.

This builds on the owner token and lifecycle lock that #8522 added. That
PR fenced output after registration; this one moves the token to
admission, so the same fence also covers the time before registration.

The pubsub retain no longer waits on a full subscriber command queue.
Callers hold a connection's lifecycle lock while they retain. A retain
past a full queue now leaves a coalesced wake-up, and the subscriber
subscribes every retained topic it is missing. A retain that fits in the
queue leaves no wake-up, so first retains do not each make the
subscriber rescan the map.

## Behavior

- `close::admit` runs in the read loop before spawn. It records the
request's token in the connection's subscription map, with a flag that
says whether the request has claimed yet. It also applies the
subscription limit, which moves there from the handlers.
- Claims (`claim_admitted_live`, `claim_admitted_search`, the sync
claim) register only while the request still owns its token.
- Refusals after admission go through `close_if_owner`. The two REQ
refusals that also send a `NOTICE` send it in the same critical section.
- Refusals before admission (rate limit, admission quota) still retire
the old holder, as before.
- The old holder stays registered until the newer request claims or is
refused, as before.
- A channel-access eviction that removes an old holder while a newer
same-ID request is still pending retires only the old holder. It sends
no `CLOSED` for the ID, because the client already replaced that holder,
and the newer request still claims.

Client-visible changes to the subscription limit:

- The limit is checked on arrival, before scope, auth and filter checks.
On a full connection, a REQ for a new ID that would also fail those
checks now gets `CLOSED "error: too many subscriptions"` instead of the
other refusal.
- Requests still in their access checks count toward the limit.

## Scope

Live fan-out does not check the token. A same-ID request that has
arrived but not yet claimed does not stop live events to the old holder.
That path is unchanged here.

If a handler panics before it claims, its token stays in the map until a
`CLOSE`, a same-ID REQ, or the disconnect removes it. Until then it
counts toward the subscription limit.

## Testing

- `close_fences_a_req_whose_handler_has_not_run` (REQ and sync REQ):
`REQ x` then `CLOSE x` before the handler runs gives only `CLOSED x` and
no registration.
- `only_the_newest_same_id_req_answers`: of two same-ID REQs, only the
newer one answers.
- `superseded_or_closed_requests_cannot_claim`: an older request cannot
claim after a newer one, and a closed request cannot claim or close.
- `revoke_of_a_replaced_holder_spares_the_pending_replacement`: a revoke
of the old holder sends no `CLOSED`, keeps the pending request's token,
and the pending request then claims its own channel.
- `queue_full_retain_does_not_wait_and_schedules_reconciliation`
(pubsub).
- `live_subscriber_recovers_a_dropped_subscribe_hint` (pubsub, requires
Redis): it runs the real subscriber on a live link and drops a topic's
subscribe hint with a full queue. The topic is still delivered without a
reconnect and without `Confirm`. The same holds after the topic is
released, unsubscribed and retained again.
- Mutations: with no owner check in `close_owned`, both connection tests
fail. With no owner check in `claim_admitted_live`, the claim test
fails. With no `replaced` check in the eviction, the revoke test fails.
With no reconcile arm in the subscriber, or no `notify_one` in
`retain_topic`, the Redis subscriber test fails.
- CI: the four new relay tests and the full-queue pubsub test are added
to `just test-unit` and `scripts/run-tests.sh`. The Redis subscriber
test runs in a new Redis-backed backend-integration step.
- `cargo test -p buzz-relay --lib` (with `--skip config::tests`, which
hangs locally when run in one process), `cargo test -p buzz-pubsub --
--include-ignored` against a local Redis, `cargo clippy -p buzz-relay -p
buzz-pubsub --all-targets -- -D warnings`, `cargo fmt --all -- --check`.

🤖 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>
2026-11-10 14:16:48 -05:00
klopez4212
773849665e Serve video and poster previews for invite links (#9306)
Invite links currently return HTML without preview metadata. Add
server-rendered `og:video` and `og:image` tags for `/invite/<code>`, and
bundle the approved MP4 and wordmark-only poster from #9282 into the
relay image. Media URLs use the request’s resolved community host, with
only TLS posture from `RELAY_URL`. Unknown hosts and lookup failures
receive no metadata; previews stay generic and never redeem invites.

Validation: production web build, workspace Clippy, 52 router tests
(including real HTTP and MP4 range requests), metadata tests, and
independent agent review pass. `just ci` stops at unrelated mobile
dependency/format checks. The full relay suite was attempted but stopped
during database-dependent tests without local infrastructure. Broad
local Rust/desktop hooks were stopped for disk pressure; desktop/mobile
hooks also lack dependencies and were skipped to publish this draft.
Full-stack and native Messages playback remain unverified. The new
preview regressions run in both CI test-runner paths.

Rollout: merge and deploy the resulting relay image with its web bundle,
verify the invite HTML and both public media URLs, then share a fresh
invite in Messages. Full-stack and human validation remain outstanding.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-09 23:12:34 +00:00
Jemiah Westerman
5b1698ec24 fix(db): give the replica-fence probe its own pool and instrument it (#9297)
## Problem

The replica-fence probe (`replica_fence::run_probe`) commits a heartbeat
token every 500 ms. It borrowed its connection from the **serving writer
pool**, so under load each beat queued behind request traffic.

In a production deployment during a reconnect/replay storm:

-
`buzz_db_pool_acquire_duration_seconds{pool_role="writer",operation="maintenance"}`
went from ≤50 ms max to 2.7–3.0 s, which is the writer pool's acquire
timeout.
- `buzz_db_replica_heartbeat_age_seconds` went from about 0.47 s to
1.25–3.02 s, in the same 10 s buckets.
- Bounded reads then failed the freshness check
(`buzz_db_route_decision{decision="writer",reason="stale"}` went from
0–6 to 1.3k–6.4k per 10 s), so read traffic spilled onto the writer
exactly when it was saturated. Replica lag stayed at tens of
milliseconds the whole time.
- No `replica fence probe failed` warning fired, because each beat
eventually succeeded, just late. The probe had no span or metric of its
own (`maintenance` is shared by 15+ call sites), so this was only
visible indirectly.

## Change

- **Dedicated pool** (`replica_fence::connect_probe_pool`):
  - lazy, one connection, `application_name=buzz-replica-fence-probe`;
- same credentials and `max_lifetime` as the writer, so it follows
failover;
  - modelled on the push producer's pool.
- It doesn't run the writer pool's `after_connect`: the probe never
writes `events`, so no floor-guard arming is needed. Instead it installs
its own session timeouts:
- `lock_timeout` 1 s. While the probe waits for the exclusive floor
lock, new channel writes queue behind it, so failing a beat fast is
cheaper than holding the queue for the serving writer's 5 s budget.
Retained proofs stand.
- `statement_timeout` and `idle_in_transaction_session_timeout` 2 s. The
idle timeout reaps a stalled client that still holds the exclusive lock.
  - A 5 s client-side deadline bounds the whole probe.
  - Cost: one extra writer connection per relay process.
- The `Db::connect_writer_pool` doc now names this pool and the
push-enqueue pool as deliberate exceptions to its "every writer pool
uses this constructor" rule, and says why.
- **Spans** (via `datastore_span`, which also records
`buzz_db_operation_duration_seconds{operation=…}`):
- `replica_fence_probe` carries `acquire_ms`, `lock_ms`, `scan_ms`,
`heartbeat_ms`, `commit_ms`, `beat_gap_ms`, `token` and `error_kind`.
- Child spans `replica_fence_probe_acquire` and
`replica_fence_probe_lock` cover the two waits.
- **Logs:**
- Failure: `warn` with `error_kind` (`acquire_timeout`, `lock_timeout`,
`statement_timeout`, `deadline`, `masked_activity`, …),
`consecutive_failures`, `heartbeat_age_ms` and per-phase timings.
  - Recovery after failures: `info`.

- **Reader spill metric:** new `buzz_db_reader_spill_total{path,
reason}`. It counts only the routed reads the replica could have served
but the writer did. `buzz_db_route_decision{decision="writer"}` already
existed but merges three different causes under `reason="stale"` and
also counts configuration (`disabled`). Reasons:

  | Reason | Meaning |
  |---|---|
| `heartbeat_stale` | The newest beat is older than the bounded-read
budget. The probe is late, not the replica. |
| `heartbeat_missing` | No live proof: before the first beat, or nothing
within `FENCE_STALENESS`. |
| `fence_wall_behind` | The read's upper bound is newer than the fence
wall. |
| `replica_lag` | The session proved only an older entry than the read
needs. |
  | `reader_acquire_timeout` | Couldn't check out a reader connection. |
| `reader_proof_timeout`, `reader_token_behind`,
`reader_validation_error` | The reader couldn't prove the fence. |

`buzz_db_route_decision` keeps its labels and values unchanged for
existing dashboards. History reads rejected on a saturated reader stay
`decision="rejected"` and aren't counted as spills.
- **Heartbeat interval versus budget:**
- The problem: at 500 ms beats, a 1000 ms `BUZZ_REPLICA_READ_MAX_AGE_MS`
tolerates no missed beat. Just before each commit the newest entry is
already about one interval old, so a single late or failed beat puts
every bounded read over budget.
- The default beat interval stays at **500 ms**. Every beat takes the
deployment-wide exclusive floor lock that channel writes queue behind,
so beating faster costs more lock drains. The budget is what should
absorb a slow beat.
- New `min_read_budget(interval)` = interval + `PROBE_LOCK_TIMEOUT` (1
s) + 200 ms, which is **1700 ms** at the default. That covers one beat
that waits out the lock timeout, plus commit latency. `Db::new` warns at
startup when the configured budget is below it. A deployment running a
1000 ms budget will see this warning until the budget is raised.
- The interval is now configurable with
`BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS`. Unset means the 500 ms default.
Values outside 300–10000 ms fail startup. The 300 ms floor keeps the
120-entry proof ring covering more than the 30 s staleness gate, and the
ring assertion checks against that floor.

The proof ordering is unchanged: exclusive lock, then `S`, then activity
scan, then token commit last. `committed_at` is still captured before
the `UPDATE` round trip.

## Tests

- New `fence_probe_beats_while_serving_writer_pool_is_exhausted`: goes
through `Db::new` + `spawn_fence_probe`, holds the serving pool's only
connection, and requires two fresh beats and exactly one probe session.
It fails on `main`'s wiring, which I checked by temporarily reverting
the `spawn_fence_probe` change.
- New `cluster_global_probe_pool_bounds_the_floor_lock_wait`: a held
shared floor lock makes the probe fail with `lock_timeout` after about 1
s, the retained proof survives, and the next beat succeeds after
release.
- New `reader_spills_are_counted_by_cause`:
  - fresh heartbeat → no spill;
- late heartbeat → `heartbeat_stale`, with the legacy `stale` still
emitted;
  - past the staleness gate → `heartbeat_missing`;
  - routing disabled → no spill.
- Unit tests cover the log throttle and the interval/budget helpers. The
epoch-rotation test now runs through the one-connection probe pool.
- The `observability_source` source-policy test now asserts the probe
never takes a serving-writer `Maintenance` checkout and is spawned
through `connect_probe_pool`.
- Existing replica-fence and `spawn_fence_probe` tests pass unchanged,
apart from signature updates.

## Not done / follow-ups

- Locally: `buzz-db` unit tests and clippy (`-D warnings`) pass, and 38
replica-fence and routing Postgres tests pass on a fresh database. I
didn't run the full Postgres suite, because it needs the nextest
per-test-database wrapper, so CI's Postgres lane is the gate there.
- No local relay run yet. This needs a reader-configured relay, then
pool exhaustion to see the spans and logs end to end.
- The deployed `BUZZ_REPLICA_READ_MAX_AGE_MS` lives in deployment
config. Check it against the new startup warning.
- The `PROBE_DEADLINE` path has no test. It's only reachable through a
stall that no server-side timeout catches.

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

---------

Signed-off-by: Jemiah Westerman <jemiah@squareup.com>
Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:06:53 -05:00
Luke Tornquist
dd9da3ac6d fix(relay): never close connections when cross-node fan-out falls behind (#9302)
## Summary

Cross-node fan-out no longer closes connections when it falls behind.

Before this change, an event closed its local recipients when:
- it was not delivered within 30 s of this node reading it from Redis,
- its worker queue was full,
- or the access gate still could not check a recipient by that deadline.

Dispatcher lag also closed every subscribed connection. A rate-limited
closer spread the closes out, at 1% of a node's connections per second
with a floor.

The trouble is that a database stall slows every node's deliveries at
once. So the closes landed on every node together. Each reconnect then
does AUTH, membership reads, NIP-11 and REST catch-up against the
database that was already slow. That turned a short stall into a
reconnect storm and bursts of 503s. On small nodes the closer's floor
dominated, so a node could close all of its connections within tens of
seconds. Review-Proven Rule 9 (design every client-driven path for the
whole fleet running it at once) is the reason: a server-forced close
starts a fleet-wide reconnect.

## What changes

Kept from #9195 and #9235:
- One dispatcher plus 16 workers, routed by `(community, topic)`. Each
channel stays in order and channels deliver concurrently.
- The bulk membership read in the access gate, and denying an event for
a channel that no longer exists.

Removed:
- The delivery deadline and `ChannelEvent.received_at`.
- The live fence (`fence_live_delivery`, `live_fenced`).
- `LagCloser` and its rate limit.
- The queue-full closes and the dispatcher-lag closes.
- The access-gate retry loop
(`buzz_multinode_fanout_gate_retries_total`).

Behavior now:
- A slow delivery holds only its own worker and arrives late.
- A full worker queue or dispatcher lag drops the event on this node.
The drop is counted in
`buzz_multinode_fanout_dropped_total{reason="queue_full"}` or
`buzz_multinode_fanout_lag_total`, and the affected artifact syncs get
`CLOSED "resync: live delivery lagged"` (NIP-AR Sync rule 5). This is
the same as before the closer existed.
- A recipient the access gate cannot check misses that event, and a sync
among them resyncs. Same as the local fan-out path.

Trade-off: a plain subscription that misses a dropped event is not told.
Its client may replay the event on its next reconnect, but not if later
deliveries moved its resume cursor past the event by more than its
replay slack (5 s for the ACP client). That was the behavior before
#9195. Queue-full and lag drops stay visible in the counters, so we can
see whether they actually happen before adding any recovery mechanism.

## What got simpler

Net −700 lines.
- `multinode_fanout.rs` drops from ~940 lines to ~350.
- `deliver_pubsub_event` loses its retry loop and goes back to the
shared `route_fanout_matches` path. The Redis path and the local path
once again apply the access gate the same way.
- `ConnectionManager` loses the fence flag and the split send helper.
`SubscriptionRegistry` loses `subscribed_connections`.

## Testing

- `handlers::multinode_fanout::tests`:
  - in-order delivery through the workers;
- a full queue resyncs only the matched syncs and closes nothing, and a
local echo is not counted as a drop;
  - dispatcher lag resyncs every sync and closes nothing;
- a recipient the gate cannot check misses the event with no retry,
stays connected, and still gets the next event.
- `handlers::event::tests` is unchanged apart from removing
`received_at`.
- Mutants killed: the queue-full resync, the lag resync and the
local-echo skip.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:00:56 -05:00
Matt Toohey
85996fdff4 test: fix timing-dependent unit tests in buzz-cli, buzz-agent and buzz-admin (#9273)
## Summary
Split out of the `flakey-monday` flake-fix series. Three Rust unit tests
in `buzz-cli`, `buzz-agent` and `buzz-admin` depended on wall-clock
timing or on a production-sized pool budget and failed on loaded CI
runners. Each now waits on, or counts, the thing it actually asserts.

Commits (cherry-picked from `flakey-monday`, original messages kept):
- `test(cli): throttle the first desktop sign-in by count, not clock`
- `test(agent): wait for both responses in
steer_rejected_on_empty_prompt`
- `test(agent): pin steer_rejected_on_empty_prompt to the empty-prompt
guard`
- `test(admin): give the NIP-FI Postgres tests a test-lane pool budget`

### Root cause and fix per test


**`client::desktop_throttle_tests::a_throttled_sign_in_reconnects_with_fresh_evidence`**
(`crates/buzz-cli/src/client.rs`): failed once in CI with `conns` left
1, right 2.
- Root cause (confirmed): the fake desktop throttled a sign-in only when
`last.elapsed() < 300ms`, and `last` was captured before the provider
handshake and credential setup. When that setup took over 300 ms, the
first sign-in was signed straight away, nothing was throttled, the
client never reconnected, and the relay saw one connection.
- Fix: the fake desktop throttles exactly its first `sign_event` call
via an atomic counter, which is the scenario the test describes. The
relay's unsigned-socket deadline goes from 200 ms to 5 s, as in the
sibling deadline tests, so it no longer shapes the scenario. Assertions
are unchanged: two connections, only "c1" signed, a fresh assertion on
the reconnect.

**`steer_rejected_on_empty_prompt`**
(`crates/buzz-agent/tests/fake_llm.rs`): panicked with "empty steer
prompt was not rejected".
- Root cause (confirmed): `session/prompt` runs in a spawned task while
`_goose/unstable/session/steer` is answered inline from the stdin loop.
The fake LLM finishes the turn almost at once, so the prompt response
can arrive before the agent has read the steer. The receive loop broke
on the prompt response and never saw the steer's -32602.
- Fix: keep reading, bounded at 40 messages as before, until both the
steer and prompt responses have arrived in either order. The follow-up
commit also asserts `error.message == "steer: prompt must not be
empty"`, because `steer_session` returns -32602 for "no active run to
steer" and an `expectedRunId` mismatch too, which are exactly the
replies a steer gets when the turn ends first. The empty-prompt check
runs right after decoding, so the message is deterministic in both
orderings.


**`nip_fi::postgres_tests::{backfill_binds_only_bindable_hosts_and_reports_the_rest,
backfill_skips_a_community_being_deleted,
bind_refuses_hosts_outside_the_suffix_and_unbind_keeps_the_last_issuer}`**
(`crates/buzz-admin/src/nip_fi.rs`): `connect to test DB:
Sqlx(PoolTimedOut)` after about 3.5 s.
- Root cause (confirmed): the tests built their pool from
`DbConfig::default()`, sized for a warm relay pod (3 s acquire timeout,
two eager spare connections). In the first wave of the PostgreSQL lane
every nextest worker clones its database from the template at once, so a
first connection can take longer than 3 s.
- Fix: keep the production writer pool (`Db::new`, so the session policy
is still exercised) but set `min_connections` 0 and a 30 s acquire
timeout, the budget sqlx's `PgPool::connect` defaults give the other
PostgreSQL tests. `Db::connect_cold_start` uses the same values.

### Related issue
N/A (flake fixes; none found).

### Testing
Human testing is still required. This PR does not carry
`buzz-review-completed`; the author has not yet run these tests
themselves on this branch.

#### Verification
These changes were verified locally on the `flakey-monday` branch before
the split:
- buzz-cli throttle test: old code under CPU saturation (40 busy loops
on 32 cores) failed every iteration with `left: 1`, the CI failure. New
code, `desktop_throttle_tests` with `--test-threads=16`: 30/30 passed
unloaded, 15/15 under the same saturation.
- buzz-agent steer test: forced CI ordering (temporary 500 ms delay
before sending the steer) made the old test panic and the new test pass.
`fake_llm steer` tests with `--test-threads=16`: 30/30 passed. The
follow-up ran 100/100, and was falsified: with the empty-prompt guard
removed and the steer sent after the turn, the code check still passed
and the new message assertion failed.
- buzz-admin NIP-FI tests, against docker Postgres: the three tests, 10
iterations at `--test-threads=3`: 10/10. Behind a proxy delaying each
new connection by 4 s: the old config failed with the CI `PoolTimedOut`
at 3 s, the new config passed.

Note: `crates/buzz-cli/src/client.rs` also changed on `main` since the
series forked. The cherry-pick applied cleanly; only hunk offsets differ
from the original commit.

Nothing was re-run on this split branch: the workstation was overloaded,
so no tests, builds or linters were executed after cherry-picking. CI on
this PR is the verification for the split branch.

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

---------

Signed-off-by: mtoohey <mtoohey@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:40:29 +11:00
Bradley Axen
2b16d0ea1a feat(relay): let an operator mint invites for a community owner or admin (#9265)
## Summary

Adds `POST /operator/communities/invites`, so a deployment's trusted
operator (its account service) can mint an invite link on behalf of a
community owner or admin. The website where people manage their
communities never holds the owner's own key, so it can't call `POST
/api/invites` (owner-signed NIP-98).

- **Trust model:** the same as
`/operator/communities/{archive,transfer}`. A configured operator signs
the request (NIP-98, payload-bound, replay-checked) and vouches only for
**which identity** its signed-in caller is bound to (`actor_pubkey`).
The relay decides that identity's authority from **its own roster at
mint time**: owner or admin only, the same check `/api/invites` makes.
Nothing the operator says about roles is trusted.
- **Same invite:** it mints through `db.mint_relay_invite`, with the
same lifecycle gate and restriction check, the same
`ttl_secs`/`max_uses` bounds and defaults (`validate_mint_request`), and
the same response (`minted_invite_json`, extracted from `/api/invites`).
The link is an ordinary `https://<host>/invite/<code>` that every
client's join flow already claims.
- Archived, deleted and deleting communities return 404
(`lookup_community_host` only resolves active ones).

Request body (unknown fields rejected):
```json
{ "community_id": "<uuid>", "actor_pubkey": "<64-hex>", "ttl_secs": 259200, "max_uses": 5 }
```

Errors keep the `/api/invites` text in `error` and add a stable `code`,
so the operator can tell its own misconfiguration from the actor's
refusal without matching on text:

| Status | `code` | When |
|---|---|---|
| 403 | `not_operator` | the signer is not a configured operator |
| 400 | `invalid_request` | bad JSON, an unknown field, a bad pubkey, or
out-of-range limits |
| 404 | `community_not_found` | unknown, archived, deleted or deleting
community |
| 403 | `not_owner` | the actor isn't an owner or admin in the relay's
roster |
| 403 | `restricted` | the actor is banned or restricted
(`invite_restricted`) |
| 503 | `unavailable` | community writes are paused |

This is an HTTP operator route rather than an event kind because it
belongs on the existing operator plane (operator-signed, outside the
event data plane), like the other operator community actions.

### Stack (invite links on the Builderlab Communities page)

1. **This PR**: the relay route. It ships first.
2. The account service endpoint that calls it (private repo). Depends on
this PR.
3. The website UI (private repo). Depends on 2.

### Related issue

None found.

### Testing

- New Postgres journey
`operator_mints_invites_only_for_relay_owners_and_admins` (run against a
freshly migrated local database):
- An owner mints with the defaults. The URL, null `max_uses` and the 72h
expiry match `/api/invites`.
- A joiner **claims the minted code through `POST /api/invites/claim`**
and becomes a member.
  - An admin mints with limits.
  - A banned admin is refused.
- A member and an outsider get 403 with the same refusal text as
`/api/invites`. The test pins each error's `code`.
- Out-of-range `ttl_secs` and `max_uses`, an unknown field, a bad pubkey
and a non-operator signer are all refused.
  - An unknown community and an archived community get 404.
- `cargo test -p buzz-relay --lib -- --include-ignored api::invites
api::operator`: 78 passed and 2 timed out under heavy machine load. Both
timeouts (`claim_follow_up_survives_a_client_disconnect`,
`temporary_listing_failure_is_recovered_for_each_admission_path`) also
pass on this branch when run on their own, as on `main`.
- `cargo fmt` and pre-push hooks (clippy) passed.
- **Not yet done:** a run against a local relay with `curl`, and a human
check.

---------

Signed-off-by: Bradley Axen <baxen@squareup.com>
Signed-off-by: Kalvin Chau <kalvin@block.xyz>
Co-authored-by: drone03 <3efda7d0089450ac8094dd25cfa734546dc0d6bad0ab87b64dacfff867bdc4d3@buzz.block.builderlab.xyz>
Co-authored-by: Kalvin Chau <kalvin@block.xyz>
Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:23:56 -08:00
Matt Toohey
b082b1464c test(relay): give every media e2e upload its own blob hash (#9272)
## Summary
Split out of the `flakey-monday` flake-fix series. Two Relay E2E media
tests shared one deterministic blob hash across every test in their
binaries. In enforce mode (`BUZZ_MEDIA_READ_MODE=enforce`, on for the
Relay E2E lane since #9077), a rejected publish of that shared hash left
a sticky publication marker that made ranged GETs from the other tests
return 404. Every media e2e upload now has its own blob hash.

Commits (cherry-picked from `flakey-monday`, original messages kept):
- `test(media): give each video e2e test its own MP4 blob`
- `test(media): publish images of their own in the media e2e tests`

### Root cause and fix per test

**`test_video_range_request_206` / `test_video_range_request_416`**
(`crates/buzz-test-client/tests/e2e_media_video.rs`): a ranged GET
returned 404 instead of 206/416 in 9 of 55 Relay E2E jobs.
- Root cause (confirmed): `build_test_mp4()` was deterministic, so every
test in the binary uploaded the same sha256, and the tests run in
parallel against one relay. In enforce mode, `validate_media_references`
records a sticky `media_publications` marker for every hash an event
publishes, before dispatch, so a later rejection does not undo it.
`test_video_poster_imeta_rejects_video_as_poster` published the shared
hash and was then rejected by imeta validation. From then on
`media_access` gave an uploader with no readable reference `Restricted`,
served as 404, until the accepted poster test stored its event in an
open channel.
- Fix: `build_test_mp4()` appends a top-level `free` box holding a
random UUID, so each call yields a distinct, still valid fast-start MP4.
The upload validator allows `free` and does not inspect its payload. The
relay is unchanged: the pre-dispatch marker is the documented
fail-closed contract in `docs/operator-private-media.md`.

**`test_video_poster_imeta_accepted_via_ws`** and
**`e2e_media_extended::test_ws_valid_imeta`**: hardening, not a fix for
an observed failure. Both published a fixed 1x1 JPEG byte-identical to
`tiny_jpeg()` in `e2e_media.rs`, which `test_upload_and_get` reads back
through an uploader preview. That currently passes (a readable live
reference wins before the marker matters), but a publishing test that
shares a fixed blob with other media tests is one rejected or private
event away from the same flake. Both now publish an 8x8 PNG of random
pixels from a new `unique_png()` helper; `test_ws_valid_imeta`'s imeta
declares `image/png` and the real size; `tiny_jpeg()` is removed from
`e2e_media_video.rs`.

### Related issue
N/A (flake fixes; none found).

### Testing
Human testing is still required. This PR does not carry
`buzz-review-completed`; the author has not yet run these tests
themselves on this branch.

#### Verification
These changes were verified locally on the `flakey-monday` branch before
the split, against an enforce-mode relay with docker Postgres/MinIO:
- Old code, fresh enforce-mode relay: reject test then range tests
failed both range tests with 404 at the CI lines (reproduction).
- Whole `e2e_media_video` binary, `--test-threads=8`: 20/20 passed.
- Reject test then range tests against the polluted hash: 3/3 passed.
- The CI "Media read-auth e2e" command (`e2e_media`,
`e2e_media_extended`, `e2e_media_video`, `--ignored`), 5 back-to-back
runs on the same scratch database (the persistent-relay case): 5/5 runs,
40/40 tests each time.
- `cargo fmt --check` and `clippy --tests`: clean.

Nothing was re-run on this split branch: the workstation was overloaded,
so no tests, builds or linters were executed after cherry-picking. CI on
this PR is the verification for the split branch.

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

---------

Signed-off-by: mtoohey <mtoohey@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:56:58 -05:00
kazemek21
3071279cd8 NEXUS-4336: Wait for desktop-provider socket ownership proof (#9270)
## TL;DR

Retry missing desktop-provider socket ownership proof on the same open
connection, within the existing five-second limit. Credentials and
provider requests remain withheld until the exact server-side socket
belongs to the caller's UID; a wrong UID or lookup error still fails
immediately.

The ownership code moves into its own module to keep the existing
oversized file within the repository's file-size ratchet. The macOS
lookup now bounds output and checks the child exit status while
retaining cancellation cleanup.

### Related issue

Fixes NEXUS-4336.

### Testing

42 provider tests passed on Linux, including synthetic transport tests
for delayed/absent proof, wrong UID, lookup failure, deadline expiry,
zero early request bytes, and child cleanup after timeout/cancellation.
Targeted Clippy, formatting, and file-size checks passed. Removing the
retry or bypassing proof caused the production-path regression to fail.

Native macOS execution, installed/source parity, and the cause of any
live authentication failure remain unverified. This source change does
not establish installed or live recovery. No human-test attestation is
claimed.

Generated with Codex. Posted by Codex (gpt-6.1-sol) on behalf of kylez.

Signed-off-by: Kyle Zemek <kylez@squareup.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-09 10:11:26 -08:00
Luke Tornquist
15174bc2b2 fix(relay): deliver slow cross-node events late instead of closing their recipients (#9235) 2026-11-09 10:10:54 -05:00