Skip to content

BUZZ-615: Add verified compact membership host reads - #2661

Closed
bradseiler wants to merge 7 commits into
mainfrom
honor/buzz-615-client-membership
Closed

bradseiler wants to merge 7 commits into
mainfrom
honor/buzz-615-client-membership

Conversation

@bradseiler

@bradseiler bradseiler commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Why

Login currently uses full channel rosters to learn the viewer’s memberships. BUZZ-615 introduces a smaller signed response that separates membership discovery from peer rosters. This first slice adds the verified read path needed by that migration.

What

Add dedicated native and browser host operations that build the filter, sign the HTTP request, and return that attempt’s request ID, signer, origin and response together. Validate the signed snapshot and schedule reads through the existing reader.

How

The validator checks signature, event ID, tenant, viewer, request ID, host including port, type scope, completeness and content identity. Each read fetches fresh capability metadata from the same origin and pins its signing key. Only explicit unsupported behavior selects legacy fallback; denials, cancellation, malformed results and outages remain errors.

Each compact read starts a fresh attempt. The later session integration must serialize refreshes per viewer/community and accept only its newest outstanding attempt. Normal refresh costs two relay reads: NIP-11 and /query. An array or 404 adds one descriptor refresh, for three reads.

The rebase keeps main’s admin-add import alongside the snapshot imports in transport.ts. Parent commit 2 also adapts compact broker accounting to main #3459’s per-community inflight Map: keyed reads and increments admit each read, and finally decrements/deletes the entry at zero. The child PR documents the three conflict resolutions in its layer and the DM membership guard.

Risk

This slice is dark: startup remains legacy, no consumer requests compact snapshots, and session.ts is unchanged. It reuses native signing, cancellation and HTTP admission, so regressions in those shared paths still matter. PR 1 can merge before block/buzz#9117 and #9118 because no runtime consumer calls this path. Success means green CI and unchanged app behavior. Revert PR 1 if its shared-path changes regress behavior; the relay capability flag becomes the rollback lever when the later startup slice calls this path.

Testing

The rebased candidate uses main f7b1208ada0cf7daa8ceb49aa8e97e61a309f426. Parent #2661 has 7 commits, ending at 5961cda97028e77e19ee18649008f0fbb7da8811. Child #2700 adds 11 commits, ending at 1ca2f637e0650eea1f3b9d0ba8b11998258feb56 with tree 9b825574f7cf9da14e3b1d1257a089a7b0735ddb.

At the parent candidate, 358 broker and relay tests passed. TypeScript, Biome, diff checks, and Cargo formatting passed. At the exact child, 2,646 tests passed across 69 focused files, with TypeScript and Biome clean. These checks ran on Linux. Independent review of these exact heads found no code blockers and matched all 18 rebased commit trees. At the exact parent, Linux Rust membership tests passed 4/4, refusal 19/19, cancellation 1/1, all relay:: tests 243 passed / 2 ignored, and browser permissions 1/1; Clippy and formatting are clean. An earlier Cargo built-in Git fetch returned 503; using CARGO_NET_GIT_FETCH_WITH_CLI=true fetched the already-locked dependency successfully without source or lockfile changes. Lefthook allowed the atomic push. Its test jobs defer to PR CI for refs other than the checked-out HEAD. GitHub CI and production app acceptance are pending. Current GitHub CI

Ramirez ran the six local macOS Rust checks at parent 5961cda9. Membership passed 4/4, refusal 19/19, and cancellation 1/1. The relay suite passed 246 tests with two ignored. Clippy and formatting passed. The worktree was clean before and after, and the lockfile checksum matched.

GitHub CI passed at the previous published head 706975f11. Previous GitHub CI

At previous published child 9884d75c, a full Linux Vitest run completed with six workers: 22,956 passed, 3 failed, 30 skipped across 1,149 files. The three timing-sensitive failures were outside files touched by this stack, and each affected file passed in isolation on both that child and its previous main pin. This is prior-head evidence and does not replace the pre-push checks or hosted CI.

The macOS launcher fixture fix is already on main through #3485, which supersedes #3290. All four fixture tests passed on macOS at the pinned base.

Earlier validation

The original full local suite at 2915904a6 failed in Node integration (307 passed, one failed, one skipped) on a missing launcher-fixture helper. The same failure reproduces at clean pinned main 3b9d1354c; the launcher fixture fix now on main addresses that failure. Separate complete stages at clean child 2915904a6: Vitest 20,837 passed / 25 skipped, Rust 138 passed, browser 2,438 passed / 15 failed / 10 skipped. None of the three earlier unhandled rejections recurred. Corrected local native-fixture setup removes four setup errors. Matched complete huddle-file runs passed on main and child (57 passed / one skipped each). The remaining nine-file comparison produced 130 passed / the same four failures on each head: Chromium search scrolling, native layout keydown in both engines, and the WebKit settings viewer. Assertions and trace error values match; no child-only failed case appeared. The other seven original non-setup failures and a later plugin-cli-reload navigation timeout did not recur; their causes remain unknown. Both original full-suite and complete-browser results remain failed. Independent review of the final receipts has no open findings; human app testing remains pending.

Earlier published parent: 40bf69c88ef3a901eff7ab768894fbd2696ea3f4 on main 3b9d1354c87b21bff10604caa98b528a88b24178. Mandatory hooks passed from stacked child 2915904a6. Independent review has no open findings. Parent CI passed at this exact parent head, including CI required. Matched diagnostics found no child-only failed case; human app testing remains pending. Earlier evidence below retains its original commit scope. Human testing remains pending.

Exercised an actual local relay at relay head da52f34397f120e00046470f4dfbe713936b5078 with 468 memberships: signature, request binding, content identity, removal and role change passed. The real relay-to-client-validator witness accepted a signed host with its port and rejected the same result when the expected origin omitted the port.

Coverage spans membership-snapshot.test.ts, native.test.ts, reader.test.ts and browser-host/membership-broker.test.mjs. Ran pnpm exec vitest run at 7cff167b3: 18,183 passed, 22 skipped. At the published head, pnpm exec vitest run src/features/relay/native.test.ts passed 70 tests; required pre-push checks passed with BUZZ_TEST_WORKERS=2. Local workflow commands were node OUTBOX/BUZZ_615_LOCAL_WORKFLOW.mjs and node OUTBOX/BUZZ_615_CLIENT_HOST_PORT.mjs from the validation workspace.

Human testing is pending. Full native tests crashed with SIGSEGV in existing window-state code; the same crash also reproduces on baseline 3ce52cefc. Browser startup throughput and zero-roster startup acceptance belong to the later startup slice.

Bigger picture

Part 1 of BUZZ-615, based on the relay contract in block/buzz#9117. Follow-ups migrate viewer authority, add bounded peer-roster demand, then switch compact startup with hint fencing, cache isolation and reconnect repair. No deployment or production enablement is included.

Generated with Codex

Stack created with GitHub Stacks CLI • Give Feedback 💬

@bradseiler bradseiler changed the title honor/buzz 615 client membership BUZZ-615: Add verified compact membership host reads Nov 5, 2026
@bradseiler
bradseiler added this pull request to stack #2701 November 5, 2026 23:49
@bradseiler
bradseiler force-pushed the honor/buzz-615-client-membership branch 4 times, most recently from 40bf69c to 2a4afc5 Compare November 11, 2026 20:48
@bradseiler
bradseiler marked this pull request as ready for review November 11, 2026 20:48
@bradseiler
bradseiler requested a review from a team as a code owner November 11, 2026 20:48

@loganj loganj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Larry and Auto: an independent adversarial review of 2a4afc5659. Source review only; we did not run the tests or the app.

Approve, no must-fix. The validator binds everything the description claims: signature and ID (eventDto → verifyEvent), the signer pinned to NIP-11 self = session relayAuthor = descriptor pubkey, the request ID in the d tag and in the content, matched to the host attempt's own auth event, community_id, the host including its port, exact types, complete, sorted unique channels, and the recomputed content identity. Legacy fallback is selected only by an absent or newer descriptor, the exact disabled 404, or a 200 array; readApiFailure never forwards arbitrary upstream text, so a lookalike body cannot select it. relay_membership_snapshot is a fixed-filter subset of what relay_http already grants. Nothing outside tests calls the new path, so it is dark.

Network, client cost and drift. Native and browser hosts share the admission and normalization code, and their filters mean the same thing. The descriptor and the /query result cannot drift silently: any key or community mismatch is an error, never a fallback. The cost items below matter once the startup slice calls this path: today every refresh is NIP-11 plus a signed /query (about 25 KB at ~170 channels, about 590 KB at the 4096 cap), and three requests on a 404 or array. Reconciling the snapshot with 39000/39002 (hint fencing, own-role authority) falls to the consumer, which is where drift will live.

The inline comments are all advice except the first, which we'd fix before a consumer calls this path. A further idea for the relay contract: snapshot_id could allow an "unchanged" response, so steady-state refreshes need not move the full list.

if (!record(info) || info.self !== host.relay) throw invalid();
return membershipCapability(info.membership_snapshot, host.relay);
};
const capability = await discover();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

advice (network): every call reads NIP-11 before /query, so each refresh costs 2 requests. The spec asks for a descriptor recheck on resume, reconnect or a capability change, not on every foreground or backstop refresh. Letting the consumer pass a per-generation capability would make the steady state 1 request per refresh, which counts fleet-wide after a relay restart.

read(
[],
// A later hint must never join an attempt dispatched before it.
{ ...options, fresh: true, deadlineMs: LARGE_READ_DEADLINE_MS },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

advice (network, for the startup slice): fresh: true means concurrent identical reads never coalesce, so N callers cost 2N relay requests. The description leaves serialization to the consumer, and the spec forbids overlapping reads; worth a test in that slice that a second refresh while one is in flight does not start another.

@wesbillman wesbillman 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.

🤖 Star Lord: changes recommended at 2a4afc5 for three refusal/error-handling defects in the new compact read operation. Source review only; the operation has no startup consumer yet.

}
if (result.status !== 200)
throw new ReadError(
"unavailable",

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.

[P2] Preserve the denied error kind. Admission keeps genuine relay 401/403 responses and maps untrusted ones to 502, but this branch labels all failures unavailable. Consequently readErrorKind and isTransientFailure treat a real denial as retryable instead of following the existing denial contract. Use httpReadError(result.status) or retain the 401/403-to-denied mapping, and cover the result through both hosts.

Comment thread src-tauri/src/relay/membership.rs Outdated
let viewer = host.viewer().await?;
let body = filter(&viewer, types)?;
let assertion = evidence(host, Some(fi), &url).await?;
let (response, identity) = send_correlated(

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.

[P2] Preserve community-refusal observation for the correlated attempt. Calling evidence/send_correlated directly bypasses send()'s observe_refusal wrapper. An exact community access/sign-in refusal, including a SIGNED_OUT evidence error, therefore fails this read without emitting relay-refusal, leaving the session/cache teardown observer uninformed. Observe the whole attempt's result, including evidence errors, and add refusal-broadcast coverage for this command.

Comment thread browser-host/relay-broker.mjs Outdated
]);
const result = await admitMembershipSnapshot(
admissions(relay, viewer).api,
async () => {

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.

[P2] Bind the queued callback to this response's async context. A sidebar operation plus five queries can fill the six-slot API lane while leaving room under inflight; this compact read then starts from another request's completion context. fetchUpstream reads that request's refusalTarget, so it can mark the wrong response or lose the community refusal after headers were sent. Wrap this callback in AsyncLocalStorage.bind, matching admittedRelayRequest, and extend the queued-refusal regression to the compact endpoint.

@bradseiler
bradseiler force-pushed the honor/buzz-615-client-membership branch from 2a4afc5 to 706975f Compare November 18, 2026 02:42
bradseiler and others added 7 commits November 18, 2026 21:53
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
Signed-off-by: Brad Seiler <seiler@squareup.com>
Co-authored-by: Honor <e0bf479eeebe47dde1e35705212a4df70616a7bc834d907ddfb18cf0405f8b1b@seiler-test.communities.public.builderlabstaging.xyz>
Signed-off-by: Brad Seiler <seiler@squareup.com>
Recheck the descriptor only for an exact disabled 404 or a 200 array. Keep legacy fallback when that recheck fails, rethrow caller cancellation, and expose refreshed capability for compatibility backoff.

Treat direct arrays as invalid, share canonical membership-type validation, and rely on streamed wire-size bounds instead of reserializing response envelopes.

Keep genuine HTTP 401/403 denials non-transient, broadcast compact-request community refusals including signed-out evidence failures, and bind queued compact reads to their own broker responses.

Co-authored-by: Harrington <91868d0cc0b8144564e350ce0a9e46447f654ad3fe93b23e39fe71314c911781>
Signed-off-by: Brad Seiler <seiler@squareup.com>
@bradseiler
bradseiler force-pushed the honor/buzz-615-client-membership branch from 706975f to 5961cda Compare November 18, 2026 23:17

@loganj loganj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Larry and Auto: an independent adversarial review of 5961cda970. Source review only; we did not run the tests or the app.

Our 11-11 approval stands; no must-fix. Commit 5961cda970 fixes what we and Star Lord raised at 2a4afc5659: the recheck now runs only for the exact disabled 404 or a 200 array and its result reaches MembershipUnsupported, the parser treats arrays as invalid, the envelope is no longer re-serialized to size it, the type guard is shared with the broker, real 401/403 keep their kind through httpReadError, the Rust host broadcasts community refusals, and the broker binds its queued callback with AsyncLocalStorage.bind. We resolved our own threads that are fixed.

The startup claim holds: nothing in production calls readMembershipSnapshot yet.

Still open for the startup slice (no change needed here): our two earlier advice threads (a NIP-11 read on every refresh, and fresh: true never coalescing) still apply. NIP-CL also asks the consumer for steps this slice does not cover: subscribe to 44100/44101 before dispatch, fence dirty generations, keep 39002 out of the viewer's own membership, cap repair at three attempts, and run the 15-minute backstop. Please carry these into that PR.

Three small notes inline (preference/advice).

Comment thread src-tauri/src/relay.rs
/// `membership_denial`), and the sign-in this device no longer has. Anything
/// else stays with its caller.
#[cfg(test)]
fn community_refusal(result: &Result<RelayResponse>) -> Option<&'static str> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 preference (simplicity): carrying one request identity added four generic seams (cancellable_result, community_refusal_with, observe_refusal_with, send_correlated). community_refusal is now a #[cfg(test)] wrapper, so its tests exercise the wrapper while production calls the generic version. Having send_authorized return the identity (existing callers drop it), with refusal observation taking &Result<&RelayResponse>, would mean fewer seams and keep the tests on the production function.

);
return {
binding: result,
response: new Response(result.body, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 advice: the host has already bounded this string body. It is wrapped in a Response here only so admitMembershipSnapshot can stream it back through membershipText. A side effect: a 204/205/304 status with a body makes new Response(...) throw an unclassified TypeError instead of a ReadError. That is an edge case. Admitting the host result directly, with no Response, would avoid it.

: "Select a community or configure BUZZ_RELAY_URL for unscoped requests",
});
const route = scoped ? `/api/relay/${parts[3]}` : url.pathname;
if (route === "/api/relay/membership-info" && req.method === "GET") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 preference: /membership-info repeats the NIP-11 fetch that /api/relay/info (line 1321) already does, and returns a different shape. One route could serve both.

@wpfleger96 wpfleger96 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.

🤖 Automated review of 5961cda970 against main at f7b1208ada: no blocking findings. Two independent source reviews, plus a headless test run of this exact head compared against the base.

Validation is complete and fallback is narrow. parseMembershipSnapshot verifies the signature and event ID through eventDto. It pins the signer to the NIP-11 self key and the descriptor pubkey, and binds the d tag and request_id to this attempt's own NIP-98 auth event, so an old signed response cannot be replayed. It also checks viewer, community_id, host including the port, the exact sorted types, complete, and sorted unique channels, and recomputes the content identity. Legacy fallback is selected only by an absent or newer descriptor, the exact disabled 404 body, or a 200 array. readApiFailure normalizes every other upstream body, so a lookalike cannot select fallback.

Shared paths are unchanged in behavior. send_authorized → send_correlated, cancellable → cancellable_result and community_refusal → community_refusal_with keep the same semantics; existing callers drop only the added identity. relay/membership.rs::snapshot repeats send's evidence → sign → observe-refusal sequence, including SIGNED_OUT. The broker branch signs exactly like the existing /query reads, uses the same admission lane, binds its queued callback with AsyncLocalStorage.bind, and keeps per-community inflight accounting balanced in finally. The three error-handling findings raised at 2a4afc5659 are fixed here: real 401/403 keep their kind, native refusals are broadcast, and queued broker refusals mark their own response.

Runtime check at this head. The changed TS and broker suites passed 251/251. cargo test -p Buzz --lib relay:: passed 246 with 2 ignored (base: 242 with 2 ignored), including the 4 new membership tests, and browser_permissions_tests:: passed. A loopback-TLS probe ran the same steps on the native and browser hosts at both head and base: a signed read, 8 cancellations with the upstream connection closed each time, then a successful recovery read. It passed on all four runs. Every auth event sent carried the right URL (including port), method, payload hash and a distinct request ID. These were test fixtures, not a real relay or the rendered app.

The path stays dark: nothing outside tests calls readMembershipSnapshot. The open advice on refresh cost and coalescing still applies to the startup slice.

@bradseiler

Copy link
Copy Markdown
Contributor Author

🤖 Superseded by #4157, which combines both membership changes in one pull request against main.

@bradseiler bradseiler closed this Nov 21, 2026
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.

4 participants