Skip to content

feat(relay): add shared mention groups with durable CAS commands - #9589

Closed
LordMelkor wants to merge 7 commits into
block:mainfrom
LordMelkor:sigil/mention-groups-relay
Closed

LordMelkor wants to merge 7 commits into
block:mainfrom
LordMelkor:sigil/mention-groups-relay

Conversation

@LordMelkor

@LordMelkor LordMelkor commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Community-wide mention groups need one authoritative revision that multiple authorized people can edit safely. The relay owns group state, checks revisions on signed put and delete commands, keeps live names unique, and records accepted commands. An exact retry returns the original acknowledgement without repeating the edit or joining members again.

Commands 47000–47002 manage groups and the community's everyone or admins policy. Relay-only kind 39010 publishes current groups, settings and deletion tombstones. Management defaults to everyone and uses effective community membership. Agents do not inherit their owner's admin role. Adding group members joins eligible targets to configured public channels in the same transaction under the existing channel-add policy. Saved defaults that become private or unlisted stay inactive. New nonpublic defaults are refused.

Groups contain up to 20 distinct members, matching mobile's push recipient limit. NIP-11 advertises the limit, protocol version and the relay's open or roster membership rule. Clients reconcile current state after reconnecting. NIP-MG specification

Rollout

Deploy the compatibility release from #9587 to every serving relay, deletion executor and operator tool before applying migration 0097. This branch includes the prerequisite changes for review. After #9587 merges, rebase this PR onto main to account for the repository's squash merge. Migration 0097 adds mention_groups and mention_group_commands and extends communities. Compatibility PR · Migration 0097

External plugins can use the relay contract after deployment. The app capabilities they need are tracked separately. Signing and publishing · Completion providers · Linked mention chips

This design supersedes #2791 and adds revision checks and durable receipts to relay-owned groups. #8819 describes the related author-signed alternative.

Review repairs

  • Group puts lock the full sorted set of default channels before locking the community row. The PostgreSQL regressions wait for a verified blocking relationship in the database and require both writers to commit. The membership, exclusive TTL and row-lock cases deadlocked before the fix and passed after it. Receipt replay also passed after defaults became nonpublic, were soft-deleted or were removed. PostgreSQL regressions
  • The expiry fixture seeds a historical accepted command through the database API. It exercises exact expired replay after a newer edit, rejection of unknown expired and future commands, and preservation of the current head through the relay handler, without a timed sleep. Expiry fixture
  • The push limit now lives in a dedicated Dart file. A change to the constant selects both mobile and Rust checks. An ordinary subscription change selects only mobile checks. The Rust parity check and mobile push behavior are preserved. CI selection scenarios

Known limits

  • Locking before authorization. A put can acquire channel membership and row locks before it returns Forbidden. PostgreSQL applies a five-second timeout per statement.
  • Huddle joins. A huddle join locks the huddle before its parent. A put naming both can still deadlock if the sorted order differs. For a put, the conflict can now occur before authorization.
  • Duplicate receipts. A repeat put waits for channel locks before looking up its receipt. Under contention it can time out before returning the duplicate acknowledgement.
  • Groups, tombstones and receipts can accumulate. Retention and count limits

Validation

Published head 3df54db74f01ebd8f47cc0ecdba50745b17cfefb has the same Git tree as the tested candidate b9ee6ceb0a162c601742be53020c2ee7c951504b, based on main 3876720c345bb6a9b709401707e35225e66bdb31.

  • 2,496 tests passed across the four affected Rust packages. Each of three full isolated PostgreSQL runs passed 1,685 tests. The live WebSocket and HTTP journey passed against a fresh relay with PostgreSQL and Redis after correcting the advertised URL. The CI tooling suite passed 85 tests, and the Dart push check passed.
  • Workspace Clippy, Rust formatting, native Git fixtures on Git 2.56.1, and the branch skew, push scope, file size, Rust and Tauri pre-push checks passed.
  • The full just test pre-push lane failed composition_log_does_not_leak_issuer_url on the candidate and on exact main. The mobile-check lane flagged the same 296 files on both. Flutter test dependency resolution stopped because pub.dev could not be resolved, and just ci stopped at mobile-check. GitHub CI succeeded on exact main, including the PostgreSQL domain job and all three mobile test shards. Main CI run

To repeat the live journey, run the test against an isolated open relay with this schema.

BUZZ_MG_TEST_RELAY_URL=ws://127.0.0.1:<port> \
  cargo test -p buzz-test-client --test e2e_mention_groups -- --ignored --nocapture

Human acceptance and fleet deployment are pending.

@LordMelkor
LordMelkor requested a review from a team as a code owner November 16, 2026 21:29
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

🔐 Codex Security Review

Status: review required for the current range.

The current range is 3876720c345bb6a9b709401707e35225e66bdb31...3df54db74f01ebd8f47cc0ecdba50745b17cfefb.
A new review must complete for this exact range. When manual authorization
is required, a user with write access must comment exactly
@buzz-security-review 3df54db74f01ebd8f47cc0ecdba50745b17cfefb to authorize a new review.
Any previous review applies only to its recorded range.

@joahg joahg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Commenting rather than approving. This is a high-risk relay change covering authorization, fan-out and a migration, and I only read the code without building or running it. I found no P0 or P1.

What looks right:

  • CAS: the community row lock serializes all commands and group rows are FOR UPDATE. A name collision rolls the transaction back, and receipts are written in the same transaction as the state.
  • Tenant isolation: every query is scoped by community_id.
  • Migration: additive, with bounded timeouts. Its table names match what #9587 registered.
  • Channel joins: only open, listed channels are accepted.
  • Replay and caps: exact retries return duplicate: with the original summary, the age window is ±120 s, and the 20-member cap is advertised in NIP-11.
  • Tests: they cover concurrent CAS and name races, retries, expired receipts, fenced writes and purge.

P2:

  • Authorization happens after the community lock. store/mention_group.rs takes lock_community (FOR NO KEY UPDATE) before authorize_command. Any member can send commands that end in Forbidden, for example under admins, and each still serializes against every group write on that community. I didn't find a per-actor command limiter. Authorizing first, under a shared lock, then escalating, would close that.
  • A channel turning private breaks group edits. The channel visibility check runs for every listed channel even when no members are being added. If a referenced channel later becomes private or unlisted, every put of that group returns InvalidData, including a rename or a member removal, and only delete still works. Skipping or warning on stale channels when no members are added would keep groups editable.
  • Join fan-out is large and runs in the request. One put can join 20 members to 32 channels, which is 640 joins. After commit, finish emits a system message, a membership notification and a type lookup for each join, plus a discovery event per channel, all serially. Someone who left a channel is re-added every time they're toggled out of and back into the group. Moving that work to a background task and rate-limiting per actor would help.
  • No growth bound. There's no cap on groups per community, and deleted ids and receipts are kept forever. A manager can create and delete groups in a loop, and clients read all of that state, tombstones included, on every reconnect.
  • An open relay has no policy owner. With no stewards, any signer can set the management policy. That fits the open model, but the NIP should say so.

P3:

  • Probing private channel ids. A private channel id returns an explicit error while a nonexistent one passes silently, which confirms that a given id exists and is private.
  • Group names. Zero-width and bidi characters (U+200B, U+202E) are allowed, and there's no Unicode normalization. Uniqueness uses Postgres lower(), which depends on collation. A name collision and a CAS conflict share 409 and differ only in message text. here and everyone aren't reserved.
  • Stale membership. Removed community members stay in groups, and channels added to a group later aren't backfilled for existing members.
  • Timeouts. SET LOCAL statement_timeout='5s' covers the whole transaction, join loop included, and a timeout surfaces as a 500.

@LordMelkor

LordMelkor commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Update, Nov 18: Closed for now. Mention Groups is being redesigned around community-scoped NIP-AR artifacts (#9638), which would replace these tables and commands. Thanks for the follow-up review. If this approach comes back, its channel-lock and test points come first. We'll reopen what's needed when the redesign is complete.


The stale-default edit failure is fixed: a saved default that later becomes private or unlisted remains an inactive reference. Renames and member removals succeed, and adding someone to the group skips that channel with channel_closed. Newly selected nonpublic defaults still refuse the whole command. Previous defaults come from the locked group row, and lock ordering is unchanged. NIP-MG also now states explicitly who may set policy on an open community without stewards.

For the other observations:

  • Both transports already enforce shared per-actor quotas before the command: ProvenCaller::rate_limit_and_replay / enforce_http_admission for HTTP, and enforce_ws_admission for WS. There is no dedicated cost-weighted group bucket. I retained authorization under the community lock to preserve receipt replay and ordering against membership/policy changes; upgrading a shared row lock is not a safe drop-in replacement.
  • Serial notice fan-out remains a latency consideration at the bounded 20×32 maximum. A background implementation needs durable delivery; detaching the current loop would lose notices on cancellation/restart.
  • Total group/tombstone/receipt growth remains a known limit. Permanent tombstones and durable retries are specified behavior; a total-count or retention policy needs a separate protocol/product decision, tracked in #9594.
  • Name collation, effective membership filtering and no backfill on default-only edits are specified in NIP-MG. I have not added name reservations or normalization. The difference between private-channel and missing-channel errors remains a separate privacy improvement.
  • PostgreSQL's statement_timeout applies per statement, not to the transaction's cumulative duration. Timeout failures still use the existing storage-error response.

Validation at merged head 9148c337e0a158bbe97e782c13b368a41721eec2: all 2,050 database/relay unit tests passed. The full PostgreSQL lane ran 1,543 tests: 1,542 passed, and the unchanged cluster-global heartbeat test failed with MaskedActivity { masked: 1 }; the exact same test passed an isolated retry without assertion changes. The stale-default regression fails before the repair and passes afterward. A fresh relay built from this head passed both HTTP visibility-transition journeys, including stored group heads, absence of new private-channel membership and refusal of newly selected nonpublic defaults. Independent source reviews found no repair or merge blocker.

Normal push hooks passed and the published PR head was verified at 9148c337e0a158bbe97e782c13b368a41721eec2. The compatibility-first rollout requirement in the description is unchanged.

@joahg joahg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Followup on 9148c337. 89ff687a fixes the stale-default P2. Previous channels come from the locked group row. A saved default that has since become private or unlisted is skipped as channel_closed rather than refused, so renames and member removals work again. Newly selected nonpublic defaults are still refused, and the new Postgres test covers both the private and the unlisted transitions. The NIP-MG text also now says who can set policy on an open community with no steward, which closes that P2. Apart from that, the merge from main brings in no changes of its own to this feature.

On your other replies: per-actor admission quotas on both transports do bound the forbidden-command traffic I raised, so I'm fine keeping authorization under the community lock for ordering. Fan-out latency, growth bounds and name normalization are reasonable as follow-ups. I'd still like an issue tracking the total-count or retention policy before groups see real use.

I'm still commenting rather than approving. This is a high-risk relay change (authorization, fan-out and a migration), and I've read it without building or running it. It needs a relay maintainer's approval.

@brow brow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Tom's pre-review recommends a small rework. The feature itself is sound, but this head breaks three things outside it:

  1. Channel changes can fail. A group put takes the community row (mention_group.rs:116) and then each default channel's membership lock, TTL lock and channel row (channel_members.rs:953-1015), while a channel visibility, TTL or unlisted edit and a channel delete take those channel locks first (channel.rs:1265-1287) and then UPDATE communities (channel.rs:1421-1427, 1884). When the two overlap on one channel PostgreSQL aborts one with a deadlock and nothing retries it, so an admin's channel change or delete (or the group save) fails and has to be repeated. Taking the put's full sorted lock set (membership locks, then per channel the shared TTL lock and the channel row) before lock_community, with the statement timeout set first and no eligibility checks or joins before the receipt check, removes the cycle. Please cover it with a PostgreSQL test in which a holder of a channel's production locks can still update the community row while a put waits.
  2. A sleeping, clock-dependent test. expired_exact_receipt_retry_survives_a_later_edit_but_unknown_expired_commands_fail stamps its command 105 s old and sleeps about 16 s of real time on every run (16.8 s in CI), and its first ingest_event(...).unwrap() fails if the machine stalls more than 15 s. Only the handler checks freshness, so the test can seed an already expired command through Db::accept_mention_group and keep the retry and unknown-command cases on ingest_event, with no sleep.
  3. Mobile PRs run the Rust lanes. mobile/lib/shared/push/push_subscription.dart is now in the rust path filter (ci.yml:53-54, lefthook.yml:103), so any PR that touches that 584-line file also runs the Rust, desktop, relay, security and PostgreSQL jobs and the pre-push just test-unit (this PR's run was 111 jobs and about 400 runner-minutes, against 54 jobs and 53 for a recent mobile-only PR). Moving buzzPushHellthreadParticipantLimit into its own small Dart file and pointing the parity test and the filters at that file keeps the guard without the cost.

The head also conflicts with main: migration numbers 0093 to 0095 are taken there, and #9587 is still open. The lock analysis was done on this head, so please recheck it after the rebase, since main changed channel.rs and channel_members.rs.

LordMelkor and others added 7 commits November 17, 2026 22:31
Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz>
Signed-off-by: Krish Ray <kray@block.xyz>
Signed-off-by: kray <kray@squareup.com>
Store relay-owned groups and management policy with atomic signed heads, accepted-command receipts and default-channel joins. Expose NIP-MG discovery and conflict responses, with persistence, admission and live transport coverage.

Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz>
Signed-off-by: Krish Ray <kray@block.xyz>
Signed-off-by: kray <kray@squareup.com>
Use the shared event writer for relay-signed group heads. Limit groups to 20 distinct members, advertise the cap, and derive refusal text from the core constant. Check parity with the mobile push limit and run that check for Dart-only changes.

Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz>
Signed-off-by: Krish Ray <kray@block.xyz>
Signed-off-by: kray <kray@squareup.com>
Retain saved defaults that become private or unlisted as inactive references,
without granting channel access. Refuse newly selected nonpublic defaults.
Clarify policy authority for open communities without stewards.

Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz>
Signed-off-by: Krish Ray <kray@block.xyz>
Signed-off-by: kray <kray@squareup.com>
Co-authored-by: Codex <noreply@openai.com>
Signed-off-by: kray <kray@squareup.com>
Signed-off-by: Krish Ray <kray@block.xyz>
Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz>
Co-authored-by: Codex <noreply@openai.com>
Signed-off-by: Krish Ray <kray@block.xyz>
Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz>
Co-authored-by: Codex <noreply@openai.com>
Signed-off-by: Krish Ray <kray@block.xyz>
Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz>
Co-authored-by: Codex <noreply@openai.com>

@joahg joahg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Follow-up on 3df54db. This is a comment, not an approval. A human maintainer needs to review this PR.

I read the code and the range-diff against 9148c337 without building or running it. CI is green on this head, including the PostgreSQL lanes. The only red check is the Codex Security Review job, which failed with "No review output from action or output file" and needs a maintainer to re-authorize it.

What changed since 9148c337

  • The first four commits differ only by rebase noise: the migration is renumbered to 0097 (main is at 0096), and there is a deletion_state = 'active' guard on the policy UPDATE plus the shared test database-URL helper.
  • f7d5de2: a group put now takes its sorted default-channel locks (membership advisory lock, then shared TTL lock, then channel row FOR NO KEY UPDATE) before lock_community. This is the same order the channel settings and delete writers use. statement_timeout is now set first, so lock waits are bounded.
  • 266ab62: the expiry test seeds the historical receipt through accept_mention_group and no longer sleeps.
  • 3df54db: the mobile limit moved into push_contract.dart. The Rust path filter, the lefthook glob, the parity test and ci-selection.test.mjs all point at that file. A change to push_subscription.dart now selects only the mobile lane.

Earlier findings

  • Settled: stale default channel (P2). Settled: NIP-MG policy text for an open community (P2).
  • Settled, from the CHANGES_REQUESTED review: the channel/community lock-order deadlock, the sleeping test, mobile PRs running the Rust lanes, and the migration number clash.
  • Accepted earlier: authorization under the community lock, given the per-actor quotas.
  • Still open as follow-ups: join fan-out latency, name normalization and reservation, and the private-versus-missing channel error difference (all P2/P3). Group, tombstone and receipt growth is tracked in #9594.

Lock ordering check. I found no cycle.

  • Group puts sort and dedupe channels in parse_command, and the DB layer rejects a command that differs from the parse. So two puts lock in the same order.
  • Channel writers take membership, then TTL, then row, then UPDATE communities. A put holds every channel it needs before it waits for the community row, and the put's later queries take no further channel locks.
  • The policy command and group delete take no channel locks.
  • The three new cluster_global_ PostgreSQL tests (membership, exclusive TTL and row writers) hold the production channel locks, prove via pg_blocking_pids that the put is waiting, update the community row, and then expect both to commit. The replay-after-channel-removal assertions also confirm the lock phase makes no eligibility decision.

New findings

  • P2: the channel locks are now taken before the receipt, authorization and CAS checks (inline comment). A forbidden, stale or duplicate put now locks up to 32 channels for as long as it waits on the community row. Before this change those commands never touched channel locks.
  • P3: the lock-order tests use one channel. Nothing covers the multi-channel sorted-order guarantee, which is the part that stops put-versus-put deadlocks (inline comment). The channel delete path (lock_channel_for_delete) is not covered either.
  • P3: the first commit is #9587, which is still open. The migration follows the "pending-catalog release first" rule in docs/database.md, so #9587 must be merged and deployed everywhere before this migration runs. That is a merge and release gate for maintainers.

Status. P0: none. P1: none. The earlier P2 and P3 follow-ups remain as noted. This is a high-risk relay change covering authorization, locking and a migration, so it needs a relay maintainer's approval.

// Match that order using the full normalized put set, locks only:
// mutable eligibility and authorization stay after the receipt check.
if let Operation::Put { channels, .. } = &command.operation {
crate::channel_members::lock_group_default_channels_in_transaction(&mut tx, channels)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 P2: these locks now run before the receipt, authorization and CAS checks. A member who is refused (for example under admins), sends a stale prev, or retries an accepted command takes the membership advisory lock, the shared TTL lock and the row lock on up to 32 channels, and holds them while it waits for lock_community. Joins, leaves and settings edits on those channels then stall behind it, bounded only by the 5 s statement timeout and the per-actor quota. Before f7d5de2 these commands never reached channel locks. Cheap fix that keeps the ordering: do an unlocked read of the actor's role and the manage policy, and an unlocked receipt lookup, before this call, and return Forbidden or Duplicate early when they already decide the outcome. Keep the authoritative checks after lock_community, since the early reads only decide whether the locks are needed.


// A settings writer already holding a channel lock must be able to finish
// its community invalidation while a group put waits for that channel.
async fn assert_channel_writer_precedes_group_put(updates: crate::channel::ChannelUpdate) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 P3: this helper locks one channel. The property that prevents put-versus-put deadlocks, sorted locking across several channels, is not exercised. Consider one test with two overlapping puts over two or more channels, plus one for the channel delete path (lock_channel_for_delete), so a later change to the normalization or to the lock order fails a test.

@LordMelkor LordMelkor closed this Nov 18, 2026

This branch had an error being deployed

1 failed deployment
codex-review — 3df54db7 Deployed Nov 18, 2026 by LordMelkor via Run Codex Security Review #15899
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants