diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 859adb734e..bda8197469 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -1239,7 +1239,7 @@ test.each([ ], ["/api/relay/archive", 4096, "bytes", "Archive request too large"], ["/api/relay/stream-presence", 256, "bytes", "Live control too large"], - ["/api/relay/stream", 300000, "bytes", "Live interests too large"], + ["/api/relay/stream", 64 * 1024 * 1024, "bytes", "Live interests too large"], ["/api/relay/query", 65536, "chars", "Filter body too large"], ["/api/relay/presence-snapshot", 20 * 1024, "bytes", "Filter body too large"], ])( diff --git a/browser-host/relay-broker-live.test.mjs b/browser-host/relay-broker-live.test.mjs index ea4ba9931f..71627813d1 100644 --- a/browser-host/relay-broker-live.test.mjs +++ b/browser-host/relay-broker-live.test.mjs @@ -74,13 +74,14 @@ async function harness( const filter = filters[0]; frames.push({ kind, id, at: performance.now(), socket }); if (kind === "AUTH" && !options.holdAuth) - queueMicrotask(() => this.receive(["OK", id.id, true])); + setImmediate(() => this.receive(["OK", id.id, true])); if (kind === "EVENT") publications.push({ event: id, socket }); if (kind !== "REQ") return; requests.push({ at: performance.now(), id, filter, filters, socket }); const refused = requests.length === refuseAt; + // WS replies arrive on an I/O turn, which also lets HTTP readers drain. if (!options.holdSetup) - queueMicrotask(() => + setImmediate(() => this.receive(refused ? ["CLOSED", id, reason] : ["EOSE", id]), ); }, @@ -94,7 +95,7 @@ async function harness( }, }; sockets.push(socket); - queueMicrotask(() => socket.receive(["AUTH", "fixture"])); + setImmediate(() => socket.receive(["AUTH", "fixture"])); return socket; }, }); @@ -125,7 +126,7 @@ async function harness( const response = await fetch(`${base}/api/relay/stream`, { method: "POST", headers: { Origin: origin, "Content-Type": "application/json" }, - body: JSON.stringify({ channels }), + body: JSON.stringify({ channels, statusDeltas: options.statusDeltas }), signal: controller.signal, }); return { response, abort: () => controller.abort() }; @@ -259,7 +260,7 @@ test("real HTTP accepts the 1022-channel body and rejects invalid/oversized/orig large.abort(); await until(() => h.sockets.every((s) => s.readyState === 3)); const count = h.sockets.length; - for (const invalid of [[""], Array(1025).fill("a"), ["x".repeat(150001)]]) { + for (const invalid of [[""], ["x".repeat(150001)]]) { const { response } = await h.post(invalid); expect([400, 413]).toContain(response.status); await response.text(); @@ -344,11 +345,11 @@ test.each([null, 1])( .filter((r) => r.status === "limited") .map((r) => r.channelId) .sort(), - ).toEqual(ids.slice(enabled ? 1021 : 1022)); - // Status retains every interest, but only 1024 routes may have a wire. + ).toEqual(ids.slice(enabled ? 1020 : 1021)); + // One wire stays free for the silence probe. All interests stay visible. expect( snapshot.routes.filter((r) => r.status !== "limited"), - ).toHaveLength(1024); + ).toHaveLength(1023); expect(snapshot.routes.some((r) => r.id === "observer")).toBe(enabled); sockets ??= h.sockets.length; posts ??= streamPosts(); @@ -1488,16 +1489,21 @@ test("joined batches survive the real HTTP boundary and retirement only rebuilds (_, i) => `c${String(i).padStart(3, "0")}`, ); traffic.update([...joined, "preview"], joined); - await until(() => established.mock.calls.length === 29); - expect(h.requests).toHaveLength(29); + await until( + () => established.mock.calls.length === 4 && h.requests.length === 30, + ); + expect(h.requests).toHaveLength(30); const batches = h.requests.filter( + (r) => r.filter["#h"] && r.filter.limit === 0, + ); + const replays = h.requests.filter( (r) => r.filter["#h"] && r.filters.length > 1, ); - expect(batches.map((r) => r.filters.length)).toEqual([ + expect(replays.map((r) => r.filters.length)).toEqual([ ...Array(25).fill(10), 6, ]); - for (const r of batches) + for (const r of replays) for (const f of r.filters) { expect(f["#h"]).toHaveLength(1); expect(f.limit).toBe(500); @@ -1506,7 +1512,7 @@ test("joined batches survive the real HTTP boundary and retirement only rebuilds established.mock.calls .filter(([ids]) => Array.isArray(ids)) .map(([ids]) => ids.length), - ).toEqual([...Array(25).fill(10), 6]); + ).toEqual([256]); // Globals carry their continuity across the host boundary. A first // connection has no cursor, so neither proves it missed nothing. expect( @@ -1533,16 +1539,17 @@ test("joined batches survive the real HTTP boundary and retirement only rebuilds }); expect(malformed.status).toBe(400); await malformed.text(); - expect(h.requests).toHaveLength(29); + expect(h.requests).toHaveLength(30); const retained = joined.slice(1); traffic.update([...retained, "preview"], retained); - await until(() => established.mock.calls.length === 30); - expect(h.requests).toHaveLength(30); - expect(h.frames.filter((f) => f.kind === "CLOSE").map((f) => f.id)).toEqual( - [old.id], - ); + await until(() => established.mock.calls.length === 5); + expect(established).toHaveBeenCalledTimes(5); + expect(h.requests).toHaveLength(31); + expect( + h.frames.filter((f) => f.kind === "CLOSE" && f.id === old.id), + ).toHaveLength(1); expect(h.requests.at(-1).filters.flatMap((f) => f["#h"])).toEqual( - joined.slice(1, 10), + joined.slice(1), ); const event = finalizeEvent( { @@ -1558,7 +1565,7 @@ test("joined batches survive the real HTTP boundary and retirement only rebuilds await until(() => receive.mock.calls.length === 1); expect(receive).toHaveBeenCalledExactlyOnceWith([event], { phase: "live", - sourceChannels: joined.slice(1, 10), + sourceChannels: joined.slice(1), }); expect(h.sockets).toHaveLength(1); } finally { @@ -1679,6 +1686,60 @@ test("startup response ABA retires an old wire before applying the latest intere } }); +test("a re-added pending route replaces its queued removal before drain", async () => { + let response; + let backpressured = false; + const deltas = []; + const h = await harness(0, undefined, { + holdSetup: true, + statusDeltas: true, + response(res) { + response = res; + Object.defineProperty(res, "writableNeedDrain", { + get: () => backpressured, + }); + const write = res.write.bind(res); + res.write = (chunk, ...args) => { + const text = String(chunk); + if (text.startsWith("event: state-delta\n")) + deltas.push(JSON.parse(text.split("data: ")[1])); + return write(chunk, ...args); + }; + }, + }); + try { + const opened = await h.post(["a"]); + await until(() => h.requests.some((r) => r.filter["#h"]?.includes("a"))); + const control = async (channels, interestRevision) => { + const result = await fetch(`${h.base}/api/relay/stream-interests`, { + method: "POST", + headers: { Origin: h.base, "Content-Type": "application/json" }, + body: JSON.stringify({ + streamId: opened.response.headers.get("x-buzz-live-id"), + channels, + interestRevision, + }), + }); + expect(result.status).toBe(200); + await result.text(); + }; + backpressured = true; + await control([], 1); + await control(["a"], 2); + const before = deltas.length; + backpressured = false; + response.emit("drain"); + const drained = deltas.slice(before); + expect(drained.flatMap((d) => d.removed)).not.toContain("channel:a"); + expect(drained.flatMap((d) => d.routes)).toContainEqual( + expect.objectContaining({ id: "channel:a", status: "pending" }), + ); + expect(drained.every((d) => d.interestRevision === 2)).toBe(true); + } finally { + await h.close(); + } +}); + test.each(["disconnect", "close"])( "backpressured route state drains latest revision and fences observer transitions and %s", async (ending) => { @@ -2027,6 +2088,169 @@ test("live streams request no agent telemetry without plugin demand", async () = } }); +test("real broker keeps 100,000 joined channels and delivers outside the first batch", async () => { + const h = await harness(); + const nativeFetch = globalThis.fetch; + let traffic; + try { + vi.stubGlobal("fetch", (input, init) => + nativeFetch(input, { + ...init, + headers: { + ...init?.headers, + ...(init?.method === "POST" ? { Origin: h.base } : {}), + }, + }), + ); + const transport = await connectBrokerTransport(h.base); + let snapshot; + const received = []; + const established = new Set(); + traffic = transport.subscribe({ + receive(events) { + received.push(...events); + }, + established(ids) { + for (const id of typeof ids === "string" ? [ids] : (ids ?? [])) + established.add(id); + }, + denied() {}, + state(value) { + snapshot = value; + }, + }); + const ids = Array.from( + { length: 100_000 }, + (_, i) => `${String(i).padStart(6, "0")}-${"c".repeat(121)}`, + ); + traffic.update(ids, ids); + await vi.waitFor( + () => { + expect( + established.size, + JSON.stringify({ + status: snapshot?.status, + error: snapshot?.error, + requests: h.requests.length, + sockets: h.sockets.length, + }), + ).toBe(100_000); + expect(snapshot?.status).toBe("connected"); + expect( + snapshot.routes.filter( + (route) => route.channelId && route.status === "live", + ), + ).toHaveLength(100_000); + }, + { timeout: 30_000 }, + ); + expect(h.sockets).toHaveLength(1); + expect( + h.requests.filter((r) => r.filters.some((f) => f["#h"] && f.limit === 0)), + ).toHaveLength(49); + const last = ids.at(-1); + const route = h.requests.find((request) => + request.filters.some((filter) => filter["#h"]?.includes(last)), + ); + expect(route).toBeDefined(); + const event = finalizeEvent( + { + kind: 9, + content: "last task input", + created_at: Math.floor(Date.now() / 1000), + tags: [["h", last]], + }, + h.key, + ); + await route.socket.receive(["EVENT", route.id, event]); + await vi.waitFor(() => + expect(received.map((item) => item.id)).toContain(event.id), + ); + const next = [...ids.slice(0, -1), "new-task"]; + traffic.update(next, next); + await vi.waitFor( + () => { + expect(established.has("new-task")).toBe(true); + expect(snapshot.routes.some((route) => route.channelId === last)).toBe( + false, + ); + }, + { timeout: 30_000 }, + ); + const active = new Set(); + for (const { kind, id } of h.frames) { + if (kind === "REQ") active.add(id); + if (kind === "CLOSE") active.delete(id); + expect(active.size).toBeLessThanOrEqual(1024); + } + } finally { + traffic?.dispose(); + vi.unstubAllGlobals(); + await h.close(); + } +}, 60_000); + +test("broker renewals retain establishment signals while channel status stays live", async () => { + const h = await harness(); + let traffic; + try { + browserFetch(h.base); + const transport = await connectBrokerTransport(h.base); + const established = vi.fn(); + const states = []; + traffic = transport.subscribe({ + ...callbacks, + established, + state: (state) => states.push(state), + }); + const ids = Array.from({ length: 20 }, (_, i) => `c${i}`); + traffic.update(ids, ids); + await until( + () => + established.mock.calls.filter(([value]) => Array.isArray(value)) + .length === 1, + ); + const membership = h.requests.find((request) => + request.filters.some((filter) => filter.kinds.includes(44100)), + ); + expect(membership).toBeDefined(); + const before = states.length; + const notice = finalizeEvent( + { + kind: 44100, + content: "", + created_at: Math.floor(Date.now() / 1000), + tags: [ + ["p", getPublicKey(h.key)], + ["h", ids[0]], + ], + }, + h.key, + ); + await membership.socket.receive(["EVENT", membership.id, notice]); + await until( + () => + established.mock.calls.filter(([value]) => Array.isArray(value)) + .length === 2, + ); + expect( + states + .slice(before) + .every((state) => + state.routes + .filter((route) => route.channelId) + .every((route) => route.status === "live"), + ), + ).toBe(true); + expect(established.mock.calls.at(-1)).toEqual([ids.sort()]); + expect(h.sockets).toHaveLength(1); + } finally { + traffic?.dispose(); + vi.unstubAllGlobals(); + await h.close(); + } +}); + test("a sync close that overtakes its open keeps the late open from taking a host slot", async () => { const h = await harness(); const post = (path, body) => diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index c66950b399..3c7e34e156 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -1676,14 +1676,16 @@ export function relayBrokerPlugin({ const prioritizing = route === "/api/relay/stream-priority"; const observing = route === "/api/relay/stream-observer"; const updating = route === "/api/relay/stream-interests"; - let raw = ""; + let raw = "", + bytes = 0; req.setEncoding("utf8"); for await (const part of req) { raw += part; + bytes += Buffer.byteLength(part); if ( - Buffer.byteLength(raw) > + bytes > (updating - ? 450000 + ? 64 * 1024 * 1024 : watchingPresence ? 20000 : prioritizing @@ -1779,9 +1781,10 @@ export function relayBrokerPlugin({ // Coalescing may hide a removal followed by re-add. Retire the old // wire before stamping the new revision; unchanged routes survive. if (removed.length) { + const removedIds = new Set(removed); stream.traffic.update( - stream.channels.filter((id) => !removed.includes(id)), - stream.joined.filter((id) => !removed.includes(id)), + stream.channels.filter((id) => !removedIds.has(id)), + stream.joined.filter((id) => !removedIds.has(id)), ); } stream.interestRevision = interestRevision; @@ -1796,11 +1799,13 @@ export function relayBrokerPlugin({ return json(res, 200, { accepted: true }); } if (route === "/api/relay/stream" && req.method === "POST") { - let raw = ""; + let raw = "", + bytes = 0; req.setEncoding("utf8"); for await (const part of req) { raw += part; - if (Buffer.byteLength(raw) > 300000) + bytes += Buffer.byteLength(part); + if (bytes > 64 * 1024 * 1024) return json(res, 413, { error: "Live interests too large" }); } let channels, @@ -1808,9 +1813,11 @@ export function relayBrokerPlugin({ priority, observer, interestRevision, - presenceAuthors; + presenceAuthors, + statusDeltas; try { const body = JSON.parse(raw); + statusDeltas = body.statusDeltas === true; channels = liveChannels(body.channels); joined = liveJoined(channels, body.joined ?? []); interestRevision = body.interestRevision ?? 0; @@ -1848,7 +1855,7 @@ export function relayBrokerPlugin({ // Bound slow-client buffering rather than retaining unbounded traffic. const write = (kind, value) => { if (res.destroyed) return; - if (res.writableLength > 2 * 1024 * 1024) { + if (res.writableLength > 8 * 1024 * 1024) { res.destroy(); return; } @@ -1863,12 +1870,12 @@ export function relayBrokerPlugin({ let lastStateStatus; let lastObserverStatus; let liveChannelIds = new Set(); - const flushState = () => { + const flushLegacyState = () => { const state = pendingState; pendingState = undefined; if (state) write("state", state); }; - const writeState = (state) => { + const writeLegacyState = (state) => { const observerStatus = state.routes.find( (route) => route.id === "observer", )?.status; @@ -1893,6 +1900,128 @@ export function relayBrokerPlugin({ if (replaceable && res.writableNeedDrain) pendingState = state; else write("state", state); }; + let knownRoutes = new Map(); + const dirtyRoutes = new Map(); + const pendingEstablished = new Map(); + let deltaHeader; + const sameRoute = (a, b) => + a?.status === b.status && + a?.replay === b.replay && + a?.error === b.error; + const flushDeltas = () => { + if (!deltaHeader) return; + while (dirtyRoutes.size && !res.destroyed) { + const routes = [], + removed = []; + for (const [id, route] of dirtyRoutes) { + dirtyRoutes.delete(id); + if (route) routes.push(route); + else removed.push(id); + if (routes.length + removed.length === 512) break; + } + write("state-delta", { ...deltaHeader, routes, removed }); + if (res.writableNeedDrain) return; + } + while (pendingEstablished.size && !res.destroyed) { + const [first, entry] = pendingEstablished + .entries() + .next().value; + const { interestRevision, singleton } = entry; + if (singleton) { + pendingEstablished.delete(first); + write("established", { channelId: first, interestRevision }); + } else { + const channels = []; + for (const [id, pending] of pendingEstablished) { + if ( + pending.interestRevision !== interestRevision || + pending.singleton + ) + continue; + pendingEstablished.delete(id); + channels.push(id); + if (channels.length === 512) break; + } + write("established", { channels, interestRevision }); + } + if (res.writableNeedDrain) return; + } + }; + const writeState = statusDeltas + ? (state) => { + const reset = + !deltaHeader || state.status !== deltaHeader.status; + if (reset) { + dirtyRoutes.clear(); + pendingEstablished.clear(); + knownRoutes.clear(); + write("state-delta", { + status: state.status, + ...(state.error ? { error: state.error } : {}), + interestRevision: state.interestRevision, + reset: true, + routes: [], + removed: [], + }); + } + deltaHeader = { + status: state.status, + ...(state.error ? { error: state.error } : {}), + interestRevision: state.interestRevision, + }; + const next = new Map(); + const urgent = []; + for (const route of state.routes) { + next.set(route.id, route); + const previous = knownRoutes.get(route.id); + // The browser already owns the IDs and can construct pending rows. + const implicit = + !previous && + route.channelId && + route.status === "pending" && + route.replay === "unknown" && + !route.error; + if ( + (!implicit || dirtyRoutes.get(route.id) === null) && + !sameRoute(previous, route) + ) { + dirtyRoutes.set(route.id, route); + if ( + (previous?.status === "live" && + route.status !== "live") || + route.id === "observer" + ) + urgent.push(route); + } + } + for (const id of knownRoutes.keys()) + if (!next.has(id)) { + dirtyRoutes.set(id, null); + if (id.startsWith("channel:")) + pendingEstablished.delete(id.slice(8)); + } + for (let offset = 0; offset < urgent.length; offset += 512) { + const routes = urgent.slice(offset, offset + 512); + for (const route of routes) dirtyRoutes.delete(route.id); + write("state-delta", { + ...deltaHeader, + routes, + removed: [], + }); + } + if (knownRoutes.has("observer") && !next.has("observer")) { + dirtyRoutes.delete("observer"); + write("state-delta", { + ...deltaHeader, + routes: [], + removed: ["observer"], + }); + } + knownRoutes = next; + if (!res.writableNeedDrain) flushDeltas(); + } + : writeLegacyState; + const flushState = statusDeltas ? flushDeltas : flushLegacyState; res.on("drain", flushState); const stream = { relay, @@ -1935,14 +2064,25 @@ export function relayBrokerPlugin({ ...state, interestRevision: stream.interestRevision, }), - established: (channelId, global) => - write("established", { - ...(Array.isArray(channelId) - ? { channels: channelId } - : { channelId }), - ...(global ? { global } : {}), - interestRevision: stream.interestRevision, - }), + established: (channelId, global) => { + if (statusDeltas && channelId !== undefined) { + for (const id of typeof channelId === "string" + ? [channelId] + : channelId) + pendingEstablished.set(id, { + interestRevision: stream.interestRevision, + singleton: typeof channelId === "string", + }); + if (!res.writableNeedDrain) flushDeltas(); + } else + write("established", { + ...(Array.isArray(channelId) + ? { channels: channelId } + : { channelId }), + ...(global ? { global } : {}), + interestRevision: stream.interestRevision, + }); + }, recover: () => write("recover", {}), denied: (channelId, reason) => write("denied", { @@ -1971,6 +2111,9 @@ export function relayBrokerPlugin({ closed = true; principal.streams--; pendingState = undefined; + dirtyRoutes.clear(); + pendingEstablished.clear(); + knownRoutes.clear(); res.off("drain", flushState); traffic.dispose(); clearInterval(keepAlive); diff --git a/docs/relay-queries.md b/docs/relay-queries.md index 9f45879522..806956beef 100644 --- a/docs/relay-queries.md +++ b/docs/relay-queries.md @@ -873,20 +873,29 @@ for outstanding work. These manual fixtures are not part of `pnpm test`; see The session's `live` capability exposes connection/route state independently from finite-read readiness. A connected socket is not proof that every route is live. Global profile and self-scoped membership-hint routes are separate from channel -traffic. The logical interest capacity remains 1,022 channels plus those two globals -(one fewer channel while agent observation is enabled); omitted routes and partial -roster coverage remain visible. Joined background channels share stable wires of -at most 10 channels. Initial replay uses singleton channel filters, matching the -relay's per-REQ filter cap; live-only replacements use one equivalent filter. -Public previews and foreground interests admitted as singletons remain separate; -navigation prioritizes pending work without rebuilding healthy wires. Joined -versus preview classification travels atomically with interests. - -Initial replay is opportunistic and capped at 500 events **per channel filter**, -preserving the previous singleton replay allowance. A busy channel cannot consume -another channel's sample. This reduces REQ frames and route-state publications, -not historical database queries. Aggregate replay status stays conservative: -500 received events can mark a batch limited but never prove any channel complete. +traffic. Joined channels share stable wires of up to 2,048 IDs, the relay's +explicit channel bound. There is no fixed roster count limit. New members fill +empty slots in existing batches. Initial live setup takes priority over renewal +and replay. Priority changes setup order and preserves healthy wires. +Preview channels use separate wires. Admission reserves room for global routes, +observer and presence, replay requests, artifact syncs, the silence probe, and +replacement wires within the relay's limit of 1,024 subscriptions. Omitted channels stay visible as limited routes. +Joined versus preview classification travels with the interest snapshot. + +The 100,000-channel scale case uses 49 persistent channel wires. Replay uses a +separate queue with at most 10 singleton filters per request. Each filter requests +up to 500 recent events. At most four setup requests run at once. A busy channel +cannot consume another channel's replay allowance. A failed replay is visible to +recovery and Retry. A local failure does not stop other queued channels. Shared +quota failures pause admission. Replay stays quiet; one later live copy can emit +one incoming-message signal. + +The broker accepts interest records up to 64 MiB. Status deltas and establishment +notices contain at most 512 channel changes per frame and obey backpressure. +Frames and the write buffer retain their 8 MiB bound. Channel IDs have at most +128 characters. Discovery retains up to 256 MiB of signed records. The startup +cache retains its 8 MiB bound. Larger rosters require fresh discovery on restart. +Replay status stays conservative and never proves a channel complete. EOSE establishes streaming, **not complete historical replay**. A first connect replays the last five minutes. After a drop, a route that had reached EOSE on that connection resumes sixteen minutes (960 s) before the connection last heard the @@ -937,26 +946,30 @@ proportional to it. Removing a batch member rebuilds only that batch's survivor scope. One established source overlaps its zero-replay replacement until EOSE; another removal supersedes the pending replacement, not that established source. Removed IDs are fenced -immediately, including after re-addition. Original source scopes stay immutable; +immediately, including after re-addition. A batch with new members requests a +fresh replay sample only for those members. Survivor filters request no replay. +Their events stay live before EOSE. The old wire can deliver only for survivors. +Original source scopes stay immutable; ambiguous auxiliary events never gain invented alert attribution. Replacements -use fresh wire IDs, preserve `since`, and request `limit: 0`, so their events are +without added members use fresh wire IDs, preserve `since`, and request `limit: 0`. Their events are live even before EOSE. Pending setup alone does not prove continuity. Narrowed-scope failure, denial and disposal release both sources. An undecodable event is dropped -and logged; its route stays. For an -unchanged scope, a renewal timeout or transient relay error retires only the -replacement and retains the established source, with the error visible until +and logged; its route stays. A temporary failure retains the established source +when its full scope stays allowed. This also applies when a replacement adds +members. The error stays visible until fresh EOSE. The existing minute timer retries that renewal; quota failures retain the same source but obey the existing cooldown and three-retry limit. Exhausted or unsupported quota retries require manual Retry, not a reset each minute. -One 60-second recovery timer renews established joined batches and hints the -existing roster and unread owners to repair finite evidence. The roster hint -starts a full channel-list read only when the last one is still owed or failed, -or when no full read, from any trigger, has completed for 15 minutes -(`ROSTER_BACKSTOP_INTERVAL`). Membership notices carry joins and removals live; -the read backs up the changes the relay sends no notice for: a channel delete, -a moderation kick or DM, and a dropped fan-out frame. It does not renew -singleton previews or add per-channel background history reads. When the socket +Signed grant notices renew joined batches that contain the affected channel. +One 60-second recovery timer checks for batches whose last REQ is at least +15 minutes old. It also hints the roster and unread owners to repair finite +evidence. The roster hint starts a full channel-list read only when the last +one is still owed or failed, or when no full read has completed for 15 minutes +(`ROSTER_BACKSTOP_INTERVAL`). Membership notices carry joins and removals live. +The read also covers changes with no notice: a channel delete, a moderation +kick or DM, and a dropped frame. It does not renew singleton previews or add +per-channel background history reads. When the socket delivered no frame for a whole interval, the timer also sends one empty probe REQ; if no frame arrives within the setup timeout, the socket is replaced through the ordinary reconnect, with its backoff and replay. An open socket can stop diff --git a/scripts/live-setup-probe.mjs b/scripts/live-setup-probe.mjs index 74d3c5bf10..e860d53ef3 100644 --- a/scripts/live-setup-probe.mjs +++ b/scripts/live-setup-probe.mjs @@ -12,6 +12,7 @@ import { percentile } from "../src/features/developer/client-metrics.ts"; import { CHANNEL_KINDS, LIVE_REPLAY_LIMIT, + LIVE_BATCH_SIZE, SETUP_CONCURRENCY, subscribeRelayTraffic, } from "../src/features/relay/live.ts"; @@ -99,6 +100,7 @@ export function runStrategy({ failures: {}, }; const requests = new Map(); // wire id → { sent, channels } + const liveOnlyChannels = new Set(); const coverage = new Map( strategy.kind === "idle" ? [] : channels.map((id) => [id, "pending"]), ); @@ -174,12 +176,22 @@ export function runStrategy({ if (frame[0] === "CLOSE") requests.delete(frame[1]); if (frame[0] !== "REQ" || frame[1] === CANARY) return; result.reqs++; - const ids = frame - .slice(2) + const filters = frame.slice(2); + const ids = filters .flatMap((filter) => filter["#h"] ?? []) .filter((id) => coverage.has(id)); - for (const id of ids) coverage.set(id, "pending"); - requests.set(frame[1], { sent: now(), channels: ids }); + const replay = + strategy.kind === "client" && + ids.length > 0 && + filters.every((filter) => filter.limit > 0) && + ids.every((id) => liveOnlyChannels.has(id)); + if (strategy.kind === "client") + for (const filter of filters) + if (filter.limit === 0) + for (const id of filter["#h"] ?? []) liveOnlyChannels.add(id); + const pending = replay ? [] : ids; + for (const id of pending) coverage.set(id, "pending"); + requests.set(frame[1], { sent: now(), channels: pending }); }, received(data) { result.bytes += data.length; @@ -270,7 +282,9 @@ export function runStrategy({ }, connect, undefined, - strategy.size === Number.POSITIVE_INFINITY ? 1024 : strategy.size, + strategy.size === Number.POSITIVE_INFINITY + ? Math.ceil(channels.length / LIVE_BATCH_SIZE) + 2 + : strategy.size, ); // This roster represents joined channels, matching the app's batchable scope. owner.update(channels, channels); diff --git a/scripts/live-setup-probe.test.mjs b/scripts/live-setup-probe.test.mjs index bc13f983ee..030d7640a2 100644 --- a/scripts/live-setup-probe.test.mjs +++ b/scripts/live-setup-probe.test.mjs @@ -71,8 +71,8 @@ it("measures coverage for the app's subscriber and for raw batch shapes", async const four = await run("client:4", channels); const packed = await run("filters:10", channels); const single = await run("multi-h:all", channels); - // Two ten-channel batches, plus the app's profile and membership routes. - expect([one.reqs, four.reqs, packed.reqs, single.reqs]).toEqual([4, 4, 2, 1]); + // One live batch and two global routes. The client can also start replay. + expect([one.reqs, four.reqs, packed.reqs, single.reqs]).toEqual([4, 5, 2, 1]); for (const result of [one, four, packed, single]) expect(result).toMatchObject({ channels: 20, @@ -81,13 +81,37 @@ it("measures coverage for the app's subscriber and for raw batch shapes", async canaryMs: expect.any(Number), sockets: 1, }); - // Four serial wire setups at K=1; all four fit in one round trip at K=4. - expect(one.coverageMs).toBe(4 * 40); + // Three serial live setups at K=1; all three fit in one round trip at K=4. + expect(one.coverageMs).toBe(3 * 40); expect(four.coverageMs).toBe(40); expect(packed.coverageMs).toBe(40); expect(single.reqMs).toEqual([40]); }); +it("keeps live coverage when the separate replay sample fails", async () => { + vi.useFakeTimers(); + let first = true; + const result = await run( + "client:4", + channels, + (id) => { + if (first) { + first = false; + return ["EOSE", id]; + } + return ["CLOSED", id, "error: replay unavailable"]; + }, + { delay: (id) => (id === "probe-canary" ? 1000 : 40) }, + ); + expect(result).toMatchObject({ + channels: 20, + failed: 0, + coverageMs: 40, + canaryMs: 1000, + failures: { "error: replay unavailable": 2 }, + }); +}); + it("reports relay refusals and an idle baseline canary", async () => { vi.useFakeTimers(); const refused = await run("filters:11", channels); @@ -208,9 +232,10 @@ it("times channel coverage by channel EOSE only", async () => { it("keeps a timed-out batch failed when its EOSE arrives after CLOSE", async () => { vi.useFakeTimers(); let first = true; - // The first batch answers 30 ms after its 10 s deadline, before the second - // batch completes 40 ms after that deadline. Late EOSE must not erase failure. - const result = await run("client:1", channels, undefined, { + // The first full batch answers 30 ms after its deadline. The second + // batch keeps the socket open until 40 ms after that deadline. + const batchChannels = Array.from({ length: 2058 }, (_, i) => `channel-${i}`); + const result = await run("client:1", batchChannels, undefined, { delay: (_id, channel) => { if (!channel) return 40; const late = first; @@ -218,7 +243,7 @@ it("keeps a timed-out batch failed when its EOSE arrives after CLOSE", async () return late ? 10030 : 40; }, }); - expect(result).toMatchObject({ reqs: 4, failed: 10 }); + expect(result).toMatchObject({ reqs: 5, failed: 2048 }); expect(result.coverageMs).toBeUndefined(); expect(result.error).toBeUndefined(); }); diff --git a/src/bundled/reminders/index.test.ts b/src/bundled/reminders/index.test.ts index fdaa360b4b..eca81adf62 100644 --- a/src/bundled/reminders/index.test.ts +++ b/src/bundled/reminders/index.test.ts @@ -403,8 +403,8 @@ it("notifies a reminder only a later history page holds, saving only after the l }); // Roster pages per launch shape: "two" puts the channel on page two of 501, -// "capped" overflows discovery's retained cap on the third page. -const ROSTERS = { one: 1, empty: 1, two: 2, capped: 3 } as const; +// "capped" exhausts the discovery byte budget on page two. +const ROSTERS = { one: 1, empty: 1, two: 2, capped: 2 } as const; type Launch = Readonly<{ /** Which loads first at startup: reminder history or the channel list. */ @@ -505,7 +505,11 @@ async function launch(options: Launch) { }, }, }, - { prepared: true, warm: false }, + { + prepared: true, + warm: false, + ...(options.roster === "capped" ? { maxDiscoveryBytes: 240_000 } : {}), + }, ); // The live subscription is established on launch, before any test step. if (options.offline) live?.state({ status: "retrying", routes: [] }); @@ -585,7 +589,7 @@ async function launch(options: Launch) { : shape === "capped" ? page === 0 ? [room(2e6), ...filler(0, 499)] - : filler(page, page === 1 ? 500 : 25) + : filler(page, 500) : [room(1e6)]; let served = 0; return { @@ -721,6 +725,8 @@ it.each<[string, Launch["first"], Launch["banners"], Partial]>([ }; app.seed(); at(5_000); + // Polling advances timers without changing this case's checkpoint time. + const clock = vi.spyOn(Date, "now").mockReturnValue(5_000_000); try { if (first === "history") { await app.start(); @@ -759,9 +765,11 @@ it.each<[string, Launch["first"], Launch["banners"], Partial]>([ await app.refresh(); expect(app.show).toHaveBeenCalledTimes(banners); } finally { + clock.mockRestore(); await app.close(); } }, + 60_000, ); it("does not replay a caught-up reminder after closing and reopening", async () => { diff --git a/src/features/huddle/lifecycle.test.ts b/src/features/huddle/lifecycle.test.ts index 60e631e1e1..0108eb4d4f 100644 --- a/src/features/huddle/lifecycle.test.ts +++ b/src/features/huddle/lifecycle.test.ts @@ -600,3 +600,70 @@ it("limits advisory creation proof to streams in the background and keeps writer owner.dispose(); } }); + +it("keeps completed creation reads for retained channels while retrying aborted proof work", async () => { + const wire = scriptedTransport(author.pubkey, relay.pubkey); + let live!: LiveCallbacks; + const owner = createRelaySession({ + ...wire.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }); + const ids = Array.from({ length: 5 }, (_, i) => `proof-${i}`); + const records = ids.map((id) => + metadata(relay, id, id, 30, [ + ["t", "stream"], + ["P", author.pubkey], + ["private"], + ]), + ); + const proof = async () => { + await vi.waitFor(() => + expect( + wire.pending.some((r) => r.filters[0]?.kinds?.includes(9007)), + ).toBe(true), + ); + const index = wire.pending.findIndex((r) => + r.filters[0]?.kinds?.includes(9007), + ); + const request = wire.pending.splice(index, 1)[0]; + if (!request) throw new Error("Missing proof read"); + return request; + }; + try { + live.receive([ + ...ids.map((id) => roster(relay, id, [author.pubkey], 20)), + ...records, + ]); + const complete = await proof(); + expect(complete.filters).toHaveLength(4); + complete.respond([]); + const pending = await proof(); + expect(pending.filters[0]?.["#h"]).toEqual(["proof-4"]); + live.receive([roster(relay, "proof-0", [], 40)]); + await flush(); + expect(owner.session.channels.get?.("proof-0")).toBeUndefined(); + expect(pending.signal?.aborted).toBe(true); + live.receive(records.slice(1)); + const retry = await proof(); + expect(retry.filters.map((f) => f["#h"])).toEqual([["proof-4"]]); + retry.respond([]); + await flush(); + live.receive(records.slice(1)); + await flush(); + expect( + wire.pending.filter((r) => r.filters[0]?.kinds?.includes(9007)), + ).toHaveLength(0); + live.receive([ + roster(relay, "proof-0", [author.pubkey], 41), + ...records.slice(0, 1), + ]); + const rejoined = await proof(); + expect(rejoined.filters.map((f) => f["#h"])).toEqual([["proof-0"]]); + rejoined.respond([]); + } finally { + owner.dispose(); + } +}); diff --git a/src/features/relay/broker-live.test.ts b/src/features/relay/broker-live.test.ts index 6aaaa89f6e..ce4bd69491 100644 --- a/src/features/relay/broker-live.test.ts +++ b/src/features/relay/broker-live.test.ts @@ -116,7 +116,7 @@ function fixture() { }, }; } -it("rejects status snapshots beyond channel interests plus both globals and observer", async () => { +it("rejects status deltas beyond the bounded frame size", async () => { vi.useFakeTimers(); const f = fixture(); const t = await connectBrokerTransport(); @@ -124,9 +124,11 @@ it("rejects status snapshots beyond channel interests plus both globals and obse try { f.accept(0); await tick(); - f.publish(0, { + f.frame("state-delta", { status: "connected", - routes: Array.from({ length: 1028 }, (_, i) => ({ + removed: [], + interestRevision: 0, + routes: Array.from({ length: 513 }, (_, i) => ({ id: `route-${i}`, status: "pending", replay: "unknown", @@ -136,7 +138,7 @@ it("rejects status snapshots beyond channel interests plus both globals and obse expect(f.snapshots.at(-1)).toEqual({ status: "retrying", routes: [], - error: "Invalid live broker status", + error: "Invalid live status delta", }); } finally { owner.dispose(); @@ -550,6 +552,85 @@ it("in-place channel interests preserve an outstanding presence publication", as owner.dispose(); } }); + +it("keeps current status when old delta frames follow a removed and re-added channel", async () => { + vi.useFakeTimers(); + const f = fixture(); + const t = await connectBrokerTransport(); + const established = vi.fn(); + const owner = required(t.subscribe)({ ...f.callbacks, established }); + const row = { + id: "channel:a", + channelId: "a", + status: "live", + replay: "unknown", + }; + const delta = (revision: number, routes: unknown[], removed: string[] = []) => + f.frame("state-delta", { + status: "connected", + routes, + removed, + interestRevision: revision, + }); + try { + owner.update(["a"], ["a"]); + f.accept(0); + await tick(); + delta(1, [row]); + f.frame("established", { channels: ["a"], interestRevision: 1 }); + await tick(); + expect(established).toHaveBeenCalledExactlyOnceWith(["a"]); + owner.update([]); + owner.update(["a"], ["a"]); + delta(1, [row]); + await tick(); + expect(f.snapshots.at(-1)).toMatchObject({ + routes: [expect.objectContaining({ channelId: "a", status: "pending" })], + }); + delta(3, [row]); + f.frame("established", { channels: ["a"], interestRevision: 3 }); + await tick(); + delta(1, [], ["channel:a"]); + await tick(); + expect(f.snapshots.at(-1)).toMatchObject({ + routes: [expect.objectContaining({ channelId: "a", status: "live" })], + }); + expect(established).toHaveBeenCalledTimes(2); + } finally { + owner.dispose(); + } +}); + +it.each([ + { id: "unknown", status: "live", replay: "unknown" }, + { id: "fake-channel:a", channelId: "a", status: "live", replay: "unknown" }, +])( + "rejects a delta key outside the current route namespace: $id", + async (route) => { + vi.useFakeTimers(); + const f = fixture(); + const t = await connectBrokerTransport(); + const owner = required(t.subscribe)(f.callbacks); + try { + f.accept(0); + await tick(); + f.frame("state-delta", { + status: "connected", + interestRevision: 0, + removed: [], + routes: [route], + }); + await tick(); + expect(f.snapshots.at(-1)).toMatchObject({ + status: "retrying", + error: "Invalid live status delta", + }); + } finally { + owner.dispose(); + } + }, +); + it("keeps the reconnect backoff growing for streams that drop right after their first frame", async () => { vi.useFakeTimers(); const f = fixture(); diff --git a/src/features/relay/broker-live.ts b/src/features/relay/broker-live.ts index 7a2e527cd2..b23d64ebba 100644 --- a/src/features/relay/broker-live.ts +++ b/src/features/relay/broker-live.ts @@ -15,10 +15,11 @@ import { liveGlobal, type LiveCallbacks, type LiveSnapshot, + type LiveRoute, type LiveSubscription, } from "./live"; -const MAX_FRAME = 1024 * 1024; +const MAX_FRAME = 8 * 1024 * 1024; const MAX_RETRY_MS = 30_000; /** A generation owns its stream, parser, retry and heartbeat. Interest changes * use the same host owner so they cannot interrupt pending publications. */ @@ -35,7 +36,7 @@ export function subscribeBrokerTraffic( let channels: string[] = []; let joined: string[] = []; let sentChannels: string[] = []; - // Only IDs in the last dispatched snapshot can have a host wire (at most 1024). + // Only IDs in the last dispatched snapshot can have a host wire. const removed = new Set(); let interestRevision = 0; const addedAt = new Map(); @@ -60,6 +61,7 @@ export function subscribeBrokerTraffic( let streamId: string | undefined; let controlPending = false; let receiving = false; + const routeState = new Map(); let latest: LiveSnapshot = { status: "connecting", routes: [] }; const publish = (snapshot: LiveSnapshot) => { latest = snapshot; @@ -165,6 +167,7 @@ export function subscribeBrokerTraffic( controller = owned; const valid = () => !closed && current === generation && !owned.signal.aborted; + routeState.clear(); state("connecting"); const pulse = () => { clearTimeout(heartbeat); @@ -194,6 +197,7 @@ export function subscribeBrokerTraffic( observer, presenceAuthors, interestRevision, + statusDeltas: true, }), signal: owned.signal, }); @@ -309,6 +313,65 @@ export function subscribeBrokerTraffic( }; if (observer !== null && record.generation === observer) callbacks.observer?.(observerFrame(record.frame), observer); + } else if (kind === "state-delta") { + const snapshot = liveSnapshot(data); + const delta = data as { + interestRevision?: unknown; + reset?: unknown; + removed?: unknown; + }; + if ( + !Number.isSafeInteger(delta.interestRevision) || + (delta.interestRevision as number) < 0 || + (delta.interestRevision as number) > interestRevision || + snapshot.routes.some((route) => + route.channelId + ? route.id !== `channel:${route.channelId}` + : ![ + "profiles", + "membership", + "observer", + "presence", + ].includes(route.id), + ) || + snapshot.routes.length > 512 || + !Array.isArray(delta.removed) || + delta.removed.length + snapshot.routes.length > 512 || + delta.removed.some((id) => typeof id !== "string") + ) + throw new Error("Invalid live status delta"); + if (delta.reset === true) { + routeState.clear(); + for (const channelId of channels) + routeState.set( + `channel:${channelId}`, + Object.freeze({ + id: `channel:${channelId}`, + channelId, + status: "pending", + replay: "unknown", + }), + ); + } + for (const id of delta.removed as string[]) { + const route = routeState.get(id); + if ( + !route?.channelId || + currentChannel(route.channelId, delta.interestRevision) + ) + routeState.delete(id); + } + for (const route of snapshot.routes) + if ( + !route.channelId || + currentChannel(route.channelId, delta.interestRevision) + ) { + routeState.set(route.id, route); + } + for (const [id, route] of routeState) + if (route.channelId && !addedAt.has(route.channelId)) + routeState.delete(id); + publish({ ...snapshot, routes: [...routeState.values()] }); } else if (kind === "state") { const snapshot = liveSnapshot(data); const revision = (data as { interestRevision?: unknown }) @@ -601,16 +664,29 @@ export function subscribeBrokerTraffic( ) return; interestRevision++; + const nextSet = new Set(next), + joinedSet = new Set(joined), + nextJoinedSet = new Set(nextJoined), + sentSet = new Set(sentChannels); for (const id of channels) - if ( - !next.includes(id) || - joined.includes(id) !== nextJoined.includes(id) - ) { + if (!nextSet.has(id) || joinedSet.has(id) !== nextJoinedSet.has(id)) { addedAt.delete(id); - if (sentChannels.includes(id)) removed.add(id); + routeState.delete(`channel:${id}`); + if (sentSet.has(id)) removed.add(id); } for (const id of next) - if (!addedAt.has(id)) addedAt.set(id, interestRevision); + if (!addedAt.has(id)) { + addedAt.set(id, interestRevision); + routeState.set( + `channel:${id}`, + Object.freeze({ + id: `channel:${id}`, + channelId: id, + status: "pending", + replay: "unknown", + }), + ); + } channels = next; joined = nextJoined; sendInterests(); @@ -682,8 +758,6 @@ function liveSnapshot(value: unknown): LiveSnapshot { snapshot.status, ) || !Array.isArray(snapshot.routes) || - // Keep limited channels visible alongside both globals and the optional observer. - snapshot.routes.length > 1027 || (snapshot.error !== undefined && typeof snapshot.error !== "string") ) throw new Error("Invalid live broker status"); diff --git a/src/features/relay/discovery-budget.test.ts b/src/features/relay/discovery-budget.test.ts new file mode 100644 index 0000000000..e85b3efe8d --- /dev/null +++ b/src/features/relay/discovery-budget.test.ts @@ -0,0 +1,102 @@ +import { expect, it } from "vitest"; +import { byteSize } from "./budget"; +import { DiscoveryState } from "./discovery"; +import { keypair, metadata, roster } from "./testing"; + +it("retains evidence by bytes and reclaims the space of replaced and cleared records", () => { + const viewer = keypair(), + relay = keypair(); + const first = roster(relay, "a", [viewer.pubkey]); + const next = roster(relay, "a", [viewer.pubkey], first.created_at + 1); + const other = roster(relay, "b", [viewer.pubkey]); + const state = new DiscoveryState( + viewer.pubkey, + relay.pubkey, + byteSize(first) + byteSize(other), + ); + expect(state.accept(first, true)).toBe(true); + expect(state.accept(next, true)).toBe(true); + expect(state.accept(other, true)).toBe(true); + expect(state.accept(roster(relay, "c", [viewer.pubkey]))).toBe(false); + state.clearCached(); + expect(state.accept(first)).toBe(true); + expect(state.accept(other)).toBe(true); + expect(state.canParticipate("a")).toBe(true); +}); + +it("fails closed when a larger signed roster cannot fit and cannot regrant with its old version", () => { + const viewer = keypair(), + relay = keypair(); + const first = roster(relay, "a", [viewer.pubkey]); + const state = new DiscoveryState( + viewer.pubkey, + relay.pubkey, + byteSize(first), + ); + state.accept(first); + const intermediate = roster( + relay, + "a", + [viewer.pubkey], + first.created_at + 1, + ); + const replacement = roster( + relay, + "a", + Array.from({ length: 10 }, () => relay.pubkey), + first.created_at + 2, + ); + expect(state.accept(replacement)).toBe(false); + expect(state.canAccess("a")).toBe(false); + expect(state.accept(first)).toBe(false); + expect(state.accept(intermediate)).toBe(false); + expect(state.canParticipate("a")).toBe(false); + expect(state.overflowRevision).toBe(1); +}); + +it("fails closed when a public metadata change exceeds the retained byte budget", () => { + const viewer = keypair(), + relay = keypair(); + const first = metadata(relay, "a", "A", 1, [["public"]]); + const state = new DiscoveryState( + viewer.pubkey, + relay.pubkey, + byteSize(first), + ); + state.accept(first); + expect(state.canAccess("a")).toBe(true); + expect( + state.accept( + metadata(relay, "a", "A longer private name", 2, [["private"]]), + ), + ).toBe(false); + expect(state.canAccess("a")).toBe(false); +}); + +it("keeps stale public resolution behind rejected private metadata and permits fresh public recovery", () => { + const viewer = keypair(), + relay = keypair(); + const first = metadata(relay, "a", "A", 1, [["public"]]); + const state = new DiscoveryState( + viewer.pubkey, + relay.pubkey, + byteSize(first), + ); + state.accept(first); + expect( + state.accept( + metadata(relay, "a", "A longer private name", 2, [["private"]]), + ), + ).toBe(false); + expect(state.resume("a", first)).toBe(false); + expect(state.accept(first)).toBe(false); + expect(state.canAccess("a")).toBe(false); + expect(state.get("a")).toBeUndefined(); + const current = metadata(relay, "a", "A", 3, [["public"]]); + expect(state.resume("a", current)).toBe(true); + expect(state.accept(current)).toBe(true); + expect(state.get("a")).toMatchObject({ readOnly: true }); + state.deny("a"); + expect(state.resume("a", current)).toBe(true); + expect(state.get("a")).toMatchObject({ readOnly: true }); +}); diff --git a/src/features/relay/discovery.ts b/src/features/relay/discovery.ts index d02be1b8c8..0adb5961b5 100644 --- a/src/features/relay/discovery.ts +++ b/src/features/relay/discovery.ts @@ -1,3 +1,4 @@ +import { byteSize } from "./budget"; import { channelJoinRole, channelTtl, @@ -61,11 +62,45 @@ export class DiscoveryState { * both arrived. Local display and intent only: never saved, never proof. * It stands in for access only until a signed roster decides it. */ private starting = new Map(); + private retainedBytes = 0; + private rejectedVersions = new Map< + string, + Pick + >(); constructor( readonly viewer: string, readonly relayAuthor: string, - readonly capacity = 1024, - ) {} + readonly maxBytes = 256 * 1024 * 1024, + ) { + if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) + throw new Error("Invalid discovery byte budget"); + } + private store( + map: Map, + id: string, + event: RelayEvent, + ): boolean { + const previous = map.get(id); + const bytes = + this.retainedBytes + + byteSize(event) - + (previous ? byteSize(previous) : 0); + if (bytes > this.maxBytes) { + this.overflowRevision++; + return false; + } + map.set(id, event); + this.retainedBytes = bytes; + return true; + } + private olderThanRejected(event: RelayEvent, id: string): boolean { + const rejected = this.rejectedVersions.get(`${event.kind}:${id}`); + return ( + !!rejected && + (event.created_at < rejected.created_at || + (event.created_at === rejected.created_at && event.id > rejected.id)) + ); + } /** Returns whether visible state changed. Events from other authors are ignored, not trusted. */ accept(event: RelayEvent, cached = false): boolean { if (event.kind === 9007) { @@ -73,8 +108,7 @@ export class DiscoveryState { const metadata = id && this.metadata.get(id); if (!id || !metadata || !huddleCreation(event, metadata)) return false; if (this.creations.get(id)?.id === event.id) return false; - this.creations.set(id, event); - return true; + return this.store(this.creations, id, event); } if ( event.pubkey !== this.relayAuthor || @@ -84,12 +118,26 @@ export class DiscoveryState { const id = tag(event, "d"); if (!id) return false; const map = event.kind === 39002 ? this.rosters : this.metadata; - if (!map.has(id) && map.size >= this.capacity) { - this.overflowRevision++; - return false; - } const previous = map.get(id); + const coordinate = `${event.kind}:${id}`; + if (this.olderThanRejected(event, id)) return false; const next = newer(previous, event); + const accessible = this.canAccess(id); + if (next !== previous && !this.store(map, id, next)) { + // Keep the version when its full body cannot fit. Older evidence cannot regrant access. + if (previous) + this.rejectedVersions.set(coordinate, { + id: event.id, + created_at: event.created_at, + }); + if ( + previous && + (event.kind === 39002 || (!this.authorized(id) && !openMetadata(event))) + ) + this.deny(id); + return false; + } + if (next !== previous) this.rejectedVersions.delete(coordinate); // Only this version or a newer one confirms saved membership. An older // response must not promote a newer disk roster into write authority. const confirmed = @@ -98,8 +146,6 @@ export class DiscoveryState { (next !== previous || event.id === previous?.id) && this.cached.delete(id); if (next === previous) return confirmed; - const accessible = this.canAccess(id); - map.set(id, next); if (event.kind === 39000 && !this.open(id)) this.confirmedPreviews.delete(id); if (event.kind === 39002) { @@ -145,12 +191,6 @@ export class DiscoveryState { // A relay denial outranks an omission that a later read could undo. this.absent.delete(id); if (!this.canAccess(id) && !this.suspended.has(id)) return; - // Never evict denial evidence back into "unknown". Bound adversarial IDs by - // failing closed until fresh signed membership is available. - if (this.denied.size >= this.capacity) { - this.denyAll(); - return; - } this.accessRevision++; this.suspended.delete(id); this.confirmedPreviews.delete(id); @@ -173,6 +213,7 @@ export class DiscoveryState { metadata?.kind === 39000 && metadata.pubkey === this.relayAuthor && tag(metadata, "d") === id && + !this.olderThanRejected(metadata, id) && openMetadata(metadata) && newer(this.metadata.get(id), metadata)?.id === metadata.id ) { @@ -281,9 +322,8 @@ export class DiscoveryState { named(id: string): boolean { return this.metadata.has(id); } - /** Metadata slots still free: `accept` drops a new channel's 39000 without one. */ - headroom(): number { - return this.capacity - this.metadata.size; + byteHeadroom(): number { + return this.maxBytes - this.retainedBytes; } name(id: string): string { const event = this.metadata.get(id); @@ -405,9 +445,11 @@ export class DiscoveryState { for (const id of this.cached) { this.deny(id); // Clearing must allow a fresh identical signed roster to regrant access. - this.rosters.delete(id); - this.metadata.delete(id); - this.creations.delete(id); + for (const map of [this.rosters, this.metadata, this.creations]) { + const event = map.get(id); + if (event) this.retainedBytes -= byteSize(event); + map.delete(id); + } } this.cached.clear(); } diff --git a/src/features/relay/global-search.test.ts b/src/features/relay/global-search.test.ts index 6ac5b41000..0895839603 100644 --- a/src/features/relay/global-search.test.ts +++ b/src/features/relay/global-search.test.ts @@ -1,5 +1,6 @@ import { expect, it, vi } from "vitest"; import { createRelaySession } from "./session"; +import { byteSize } from "./budget"; import { DiscoveryState } from "./discovery"; import { ReadError } from "./errors"; import { @@ -411,7 +412,11 @@ it("fails closed on the returned-channel cap and metadata capacity without evict ), ).rejects.toThrow("Too many"); expect(wire.pending).toHaveLength(0); - const state = new DiscoveryState(viewer.pubkey, relay.pubkey, 1); + const state = new DiscoveryState( + viewer.pubkey, + relay.pubkey, + byteSize(publicMetadata(relay, "one")), + ); state.retain(new Set(), new Map()); state.accept(publicMetadata(relay, "one")); state.deny("one"); @@ -632,3 +637,50 @@ it.each([false, true])( } }, ); + +it("does not restore a public preview from stale exact metadata after private byte overflow", async () => { + const viewer = keypair(), + relay = keypair(); + const first = publicMetadata(relay, "open", [], 1700000000); + const wire = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + const owner = createRelaySession( + { + ...wire.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { maxDiscoveryBytes: byteSize(first) }, + ); + try { + live.receive([first]); + expect(owner.session.channels.get?.("open")).toMatchObject({ + readOnly: true, + }); + live.receive([ + publicMetadata( + relay, + "open", + [["private"], ["name", "A larger private name"]], + 1700000001, + ), + ]); + expect(owner.session.channels.get?.("open")).toBeUndefined(); + const lookup = owner.session.channels.resolve?.(["open"]); + await flush(); + wire.next().respond([first]); + await lookup; + expect(owner.session.channels.get?.("open")).toBeUndefined(); + const fresh = owner.session.channels.resolve?.(["open"]); + await flush(); + wire.next().respond([publicMetadata(relay, "open", [], 1700000002)]); + await fresh; + expect(owner.session.channels.get?.("open")).toMatchObject({ + readOnly: true, + }); + } finally { + owner.dispose(); + } +}); diff --git a/src/features/relay/live.test.ts b/src/features/relay/live.test.ts index 630adbbf65..167810cf0a 100644 --- a/src/features/relay/live.test.ts +++ b/src/features/relay/live.test.ts @@ -22,6 +22,7 @@ import { createRelaySession } from "./session"; import { liveRecoveryStatus } from "./live-recovery"; import { createPresence } from "../presence/presence"; import { matchesEvent } from "./projection"; +import { verifiedProfileFilter } from "./verified-profile"; type WireFilter = { kinds: number[]; "#h"?: string[]; @@ -97,6 +98,7 @@ it("keeps the browser authentication deadline measured from construction", async function setup( channels = ["a", "b"], admission = createLiveAdmission(), + batchSize = 10, random?: () => number, ) { const key = keypair(), @@ -121,6 +123,7 @@ function setup( admission, undefined, undefined, + batchSize, random, ); owner.update(channels); @@ -303,9 +306,11 @@ it("batches joined background interests without rebalance and fences retired bat for (let i = 0; i < h.first.requests().length; i++) await h.first.receive(["EOSE", h.first.requests()[i]?.[1]]); const requests = h.first.requests(); - expect(requests).toHaveLength(38); + expect(requests).toHaveLength(37); const batches = requests.filter((r) => scopeOf(r).length > 1); - expect(batches.map((r) => scopeOf(r).length)).toEqual(Array(33).fill(10)); + expect(batches.map((r) => scopeOf(r).length).sort((a, b) => a - b)).toEqual( + [2, ...Array(33).fill(10)], + ); for (const r of requests) { expect(filtersOf(r).length).toBeLessThanOrEqual(10); for (const f of filtersOf(r)) @@ -316,10 +321,10 @@ it("batches joined background interests without rebalance and fences retired bat } expect( requests.filter((r) => scopeOf(r).length === 1).map(scopeOf), - ).toEqual([["c331"], ["preview"], ["c330"]]); - expect(h.callbacks.established).toHaveBeenCalledTimes(38); + ).toEqual([["preview"]]); + expect(h.callbacks.established).toHaveBeenCalledTimes(37); expect(h.callbacks.state.mock.lastCall?.[0].routes).toHaveLength(335); - const batch = batches[0]; + const batch = batches.find((request) => scopeOf(request).includes("c000")); assert.exists(batch); const first = message(h.key, "c000", "first", 1700000000); await h.first.receive(["EVENT", batch[1], first]); @@ -342,11 +347,11 @@ it("batches joined background interests without rebalance and fences retired bat channelId: "c001", }); h.owner.prioritize?.(["c001"]); - expect(h.first.requests()).toHaveLength(38); + expect(h.first.requests()).toHaveLength(37); const retained = joined.filter((id) => id !== "c000"); h.owner.update([...retained, "preview"], retained); // Healthy survivors keep one scope and overlap the old wire until EOSE. - expect(h.first.requests()).toHaveLength(39); + expect(h.first.requests()).toHaveLength(38); const replacement = h.first.requests().at(-1); assert.exists(replacement); expect(replacement[2].limit).toBe(0); @@ -616,7 +621,9 @@ it.each(["single", "chained"])( message(author, "a", "old lifetime", 1700000005), ]); expect(h.callbacks.receive).not.toHaveBeenCalled(); - await h.first.receive(["EOSE", replacement[1]]); + const latest = h.first.requests().at(-1); + assert.exists(latest); + await h.first.receive(["EOSE", latest[1]]); expect(h.first.sent).toContainEqual(["CLOSE", initial[1]]); } finally { owner.dispose(); @@ -895,7 +902,7 @@ it.each(["timeout", "error: temporarily unavailable"])( h.callbacks.state.mock.lastCall?.[0].routes.find( (r) => r.channelId === "b", ), - ).toMatchObject({ status: "pending", error: expect.any(String) }); + ).toMatchObject({ status: "live", error: expect.any(String) }); await h.first.receive(["EOSE", retry[1]]); expect(h.first.sent).toContainEqual(["CLOSE", initial[1]]); const state = h.callbacks.state.mock.lastCall?.[0].routes.find( @@ -1156,7 +1163,7 @@ function captureLog() { it("verifies a reconnect's replayed events once and still rejects a changed copy", async () => { vi.useFakeTimers(); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); const log = captureLog(); try { await h.first.auth(); @@ -1565,7 +1572,7 @@ const sinceOf = (socket: Socket, match: (r: WireRequest) => boolean) => it("resumes a rebuilt route sixteen minutes before its connection last heard the relay, and only if it reached EOSE", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a", "b"], undefined, () => 0.5); + const h = setup(["a", "b"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -1607,7 +1614,7 @@ it("resumes a rebuilt route sixteen minutes before its connection last heard the it("never resumes from before the session's first window", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { await h.first.auth(); await vi.advanceTimersByTimeAsync(750); @@ -1629,7 +1636,7 @@ it("never resumes from before the session's first window", async () => { it("takes a batch's resume point from its earliest channel", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup([], undefined, () => 0.5); + const h = setup([], undefined, undefined, () => 0.5); try { age(); h.owner.update(["a", "b"], ["a", "b"]); @@ -1659,7 +1666,7 @@ it("takes a batch's resume point from its earliest channel", async () => { it("resumes from when a silent socket last answered, not from when it was replaced", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -1712,9 +1719,48 @@ async function rebuilt(h: ReturnType) { return next; } +it("resumes large live batches and their separate replay from the established cursor", async () => { + vi.useFakeTimers({ now: 1_700_000_000_000 }); + const h = setup([], undefined, 2048, () => 0.5); + try { + age(); + const ids = Array.from({ length: 11 }, (_, i) => `channel-${i}`); + h.owner.update(ids, ids); + await h.first.auth(); + await vi.advanceTimersByTimeAsync(750); + for (let i = 0; i < h.first.requests().length; i++) { + const request = h.first.requests()[i]; + assert.exists(request); + await h.first.receive(["EOSE", request[1]]); + } + const heard = Math.floor(Date.now() / 1000); + h.first.close(); + const next = await rebuilt(h); + for (let i = 0; i < next.requests().length; i++) { + const request = next.requests()[i]; + assert.exists(request); + await next.receive(["EOSE", request[1]]); + } + const requests = next + .requests() + .filter((r) => scopeOf(r).includes("channel-0")); + expect(requests).toHaveLength(2); + expect( + requests.flatMap(filtersOf).filter((f) => f["#h"]?.includes("channel-0")), + ).toEqual( + expect.arrayContaining([ + expect.objectContaining({ since: heard - 960, limit: 0 }), + expect.objectContaining({ since: heard - 960, limit: 500 }), + ]), + ); + } finally { + h.owner.dispose(); + } +}); + it("resumes a joined batch closed during its renewal from the source it kept", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup([], undefined, () => 0.5); + const h = setup([], undefined, undefined, () => 0.5); try { const { heard } = await renewing(h); h.first.close(); @@ -1729,7 +1775,7 @@ it("resumes a joined batch closed during its renewal from the source it kept", a it("resumes a joined batch whose renewal failed but kept its source", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup([], undefined, () => 0.5); + const h = setup([], undefined, undefined, () => 0.5); try { const { heard, renewal } = await renewing(h); // After one tick, a frame proves the relay only as far as the AUTH. @@ -1746,7 +1792,7 @@ it("resumes a joined batch whose renewal failed but kept its source", async () = it("resumes a silent joined batch from its last frame, though its renewal never answered", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup([], undefined, () => 0.5); + const h = setup([], undefined, undefined, () => 0.5); try { age(); h.owner.update(["a", "b"], ["a", "b"]); @@ -1777,7 +1823,7 @@ it("resumes a silent joined batch from its last frame, though its renewal never it("gives a renewal's kept source no cursor for a channel the renewal dropped", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup([], undefined, () => 0.5); + const h = setup([], undefined, undefined, () => 0.5); try { age(); h.owner.update(["a", "b"], ["a", "b"]); @@ -1804,7 +1850,7 @@ it("gives a renewal's kept source no cursor for a channel the renewal dropped", it("resumes a batch rebuilt before its EOSE from the cursor, not the last five minutes", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup([], undefined, () => 0.5); + const h = setup([], undefined, undefined, () => 0.5); try { age(); h.owner.update(["a", "b", "c"], ["a", "b", "c"]); @@ -1835,7 +1881,7 @@ it("resumes a batch rebuilt before its EOSE from the cursor, not the last five m it("does not move the cursor to the wake time for a frame that waited through a sleep", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -1868,7 +1914,7 @@ it.each([ "a frame handled after a short sleep proves the relay only up to the tick before the latest, whether %s is handled first", async (_, tickFirst) => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -1909,7 +1955,7 @@ it.each([ it("keeps a route's cursor through a connection that never established it", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -1940,7 +1986,7 @@ it("keeps a route's cursor through a connection that never established it", asyn it("reports a global route continuous only when it resumed from a cursor and its replay stayed under the limit", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup([], undefined, () => 0.5); + const h = setup([], undefined, undefined, () => 0.5); const globals = () => h.callbacks.established.mock.calls.flatMap(([channels, global]) => channels === undefined ? [global] : [], @@ -1990,7 +2036,7 @@ it("reports a global route continuous only when it resumed from a cursor and its it("forgets the cursor of a channel that left the interests before a rebuild", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a", "b"], undefined, () => 0.5); + const h = setup(["a", "b"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -2037,7 +2083,7 @@ it.each([ "stamps the last relay frame, not the wake-up, when waking finds %s", async (_name, drop) => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -2066,7 +2112,7 @@ it.each([ it("does not take a late EOSE for a superseded REQ as the replacement's catch-up", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -2098,7 +2144,7 @@ it("does not take a late EOSE for a superseded REQ as the replacement's catch-up it("keeps an earlier cursor when the replacement REQ on the same socket has not caught up", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -2134,7 +2180,7 @@ it("keeps an earlier cursor when the replacement REQ on the same socket has not it("keeps the earlier cursor when a channel is unsubscribed and subscribed again before its late EOSE", async () => { vi.useFakeTimers({ now: 1_700_000_000_000 }); - const h = setup(["a"], undefined, () => 0.5); + const h = setup(["a"], undefined, undefined, () => 0.5); try { age(); await h.first.auth(); @@ -2188,7 +2234,7 @@ it.each([ "waits for the jitter its close code calls for before reconnecting (code %s)", async (code, delay) => { vi.useFakeTimers(); - const h = setup(["a"], undefined, () => 0.9); + const h = setup(["a"], undefined, undefined, () => 0.9); try { await h.first.auth(); h.first.close(code); @@ -2205,7 +2251,7 @@ it.each([ it("reconnects at once when the spread draws zero, then backs off normally after a plain failure", async () => { vi.useFakeTimers(); const draws = [0, 0.5]; - const h = setup(["a"], undefined, () => draws.shift() ?? 0.5); + const h = setup(["a"], undefined, undefined, () => draws.shift() ?? 0.5); try { await h.first.auth(); h.first.close(1012); @@ -2324,20 +2370,22 @@ it("bounds interests and exposes every omitted ID without exceeding 1024 subscri await h.first.auth(); await vi.advanceTimersByTimeAsync(750); let index = 0; - while (index < 1024) { + while (index < 1023) { if (index >= h.first.requests().length) await vi.advanceTimersByTimeAsync(250); const request = h.first.requests()[index++]; assert.exists(request); await h.first.receive(["EOSE", request[1]]); } - expect(h.first.requests()).toHaveLength(1024); + expect(h.first.requests()).toHaveLength(1023); expect( h.callbacks.state.mock.lastCall?.[0].routes .filter((r) => r.status === "limited") .map((r) => r.channelId), - ).toEqual(ids.slice(1022)); - expect(() => liveChannels([...ids, "excess"])).toThrow(); + ).toEqual(ids.slice(1021)); + expect( + liveChannels(Array.from({ length: 100_001 }, (_, i) => `c${i}`)), + ).toHaveLength(100_001); for (const invalid of [[""], ["a b"], ["x".repeat(129)], [9], {}]) expect(() => liveChannels(invalid)).toThrow(); h.owner.dispose(); @@ -2397,6 +2445,8 @@ it.each([false, true])( () => socket as unknown as WebSocket, undefined, 16, + undefined, + 10, ); const channels = Array.from({ length: 170 }, (_, i) => `channel-${i}`); owner.update(channels, joined ? channels : []); @@ -3763,6 +3813,725 @@ it("carries verified workflow attribution from live admission to notification ca h.owner.dispose(); } }); + +it("keeps 10,000 joined channels live through membership changes, reconnect and restart", async () => { + vi.useFakeTimers(); + const ids = Array.from( + { length: 10_000 }, + (_, i) => `task-${String(i).padStart(5, "0")}`, + ); + const previews = Array.from( + { length: 64 }, + (_, i) => `preview-${String(i).padStart(2, "0")}`, + ); + const h = setup([]); + let latest: Parameters[0] | undefined; + h.callbacks.state.mockImplementation((state) => { + latest = state; + }); + const settle = async (socket: Socket, start = 0) => { + for (let i = start; i < socket.requests().length; i++) { + await socket.receive(["EOSE", socket.requests()[i]?.[1]]); + h.callbacks.state.mockClear(); + } + }; + const assertBounds = (socket: Socket) => { + const active = new Set(); + for (const [kind, id] of socket.sent) { + if (kind === "REQ") active.add(id); + if (kind === "CLOSE") active.delete(id); + expect(active.size).toBeLessThanOrEqual(1024); + } + return active; + }; + try { + h.owner.prioritize?.(ids.slice(-64)); + h.owner.observe?.(1); + h.owner.watchPresence?.([h.key.pubkey]); + h.owner.update(ids); + h.owner.update([...ids, ...previews], ids); + await h.first.auth(); + await settle(h.first); + expect(h.first.requests()).toHaveLength(1019); + expect( + latest?.routes.filter( + (route) => route.channelId && route.status === "live", + ), + ).toHaveLength(10_015); + expect( + latest?.routes.filter((route) => route.status === "limited"), + ).toHaveLength(49); + expect(new Set(h.first.requests().flatMap(scopeOf))).toEqual( + new Set([...ids, ...previews.slice(0, 15)]), + ); + assertBounds(h.first); + const route = h.first + .requests() + .find((request) => scopeOf(request).includes("task-09999")); + assert.exists(route); + const event = message( + h.key, + "task-09999", + "input on the last task", + 1700000001, + ); + await h.first.receive(["EVENT", route[1], event]); + expect(h.callbacks.receive).toHaveBeenLastCalledWith([event], { + phase: "live", + channelId: ids[9999], + }); + + // Churn across every batch must reuse space, rather than grow one route per join. + const retained = ids.filter((_, i) => i % 10 !== 0); + const added = Array.from({ length: 1000 }, (_, i) => `replacement-${i}`); + const next = [...retained, ...added]; + let start = h.first.requests().length; + h.owner.update([...retained, ...previews], retained); + h.owner.update([...next, ...previews], next); + await settle(h.first, start); + expect( + latest?.routes.filter( + (route) => route.channelId && route.status === "live", + ), + ).toHaveLength(10_015); + expect(assertBounds(h.first).size).toBe(1019); + + start = h.first.requests().length; + await vi.advanceTimersByTimeAsync(60_000); + await settle(h.first, start); + expect(assertBounds(h.first).size).toBe(1019); + h.first.close(); + await vi.advanceTimersByTimeAsync(500); + const reconnect = h.sockets.at(-1); + assert.exists(reconnect); + expect(reconnect).not.toBe(h.first); + await reconnect.auth(); + await settle(reconnect); + expect(new Set(reconnect.requests().flatMap(scopeOf))).toEqual( + new Set([...next, ...previews.slice(0, 15)]), + ); + expect(latest?.status).toBe("connected"); + assertBounds(reconnect); + + h.owner.dispose(); + const restarted = setup([]); + try { + restarted.callbacks.state.mockImplementation(() => + restarted.callbacks.state.mockClear(), + ); + restarted.owner.update(next, next); + await restarted.first.auth(); + await settle(restarted.first); + expect(new Set(restarted.first.requests().flatMap(scopeOf))).toEqual( + new Set(next), + ); + assertBounds(restarted.first); + } finally { + restarted.owner.dispose(); + } + } finally { + h.owner.dispose(); + } + expect(vi.getTimerCount()).toBe(0); +}, 60_000); + +it("passes the full session roster and delivers input and artifacts on task 10,000", async () => { + vi.useFakeTimers({ now: 1_700_000_100_000 }); + const h = setup([], createLiveAdmission(), 2048), + relay = keypair(), + author = keypair(); + const wire = scriptedTransport(h.key.pubkey, relay.pubkey); + let latest: Parameters[0] | undefined; + const owner = createRelaySession({ + ...wire.transport, + subscribe(callbacks) { + h.callbacks.receive.mockImplementation(callbacks.receive); + h.callbacks.state.mockImplementation((state) => { + latest = state; + callbacks.state(state); + }); + h.callbacks.established.mockImplementation(callbacks.established); + return h.owner; + }, + }); + try { + const ids = Array.from( + { length: 10_000 }, + (_, i) => `task-${String(i).padStart(5, "0")}`, + ); + h.callbacks.receive(ids.map((id) => roster(relay, id, [h.key.pubkey]))); + expect(owner.session.channels.list().channels).toHaveLength(10_000); + const live = vi.fn(), + input = vi.fn(); + owner.session.subscribeLive(live, { replay: true }); + owner.session.subscribeIncoming(input); + await h.first.auth(); + for (let i = 0; i < h.first.requests().length; i++) { + await h.first.receive(["EOSE", h.first.requests()[i]?.[1]]); + h.callbacks.state.mockClear(); + } + expect(latest?.status).toBe("connected"); + expect( + latest?.routes.filter( + (route) => route.channelId && route.status === "live", + ), + ).toHaveLength(10_000); + const route = h.first + .requests() + .find((request) => scopeOf(request).includes("task-09999")); + assert.exists(route); + const messageEvent = message( + author, + "task-09999", + "run this task", + 1_700_000_101, + ); + const artifactEvent = signed(author, { + kind: 45010, + created_at: 1_700_000_102, + content: '{"text":"Result"}', + tags: [ + ["h", "task-09999"], + ["ar", "1"], + ["d", "result"], + ["type", "example.note"], + ["op", "create"], + ], + }); + await h.first.receive(["EVENT", route[1], messageEvent]); + await h.first.receive(["EVENT", route[1], artifactEvent]); + expect(input).toHaveBeenCalledWith([ + expect.objectContaining({ + channelId: "task-09999", + messageId: messageEvent.id, + }), + ]); + expect(live).toHaveBeenCalledWith({ + channelId: "task-09999", + events: [artifactEvent], + }); + h.first.close(); + await vi.advanceTimersByTimeAsync(500); + const reconnect = h.sockets.at(-1); + assert.exists(reconnect); + await reconnect.auth(); + let cursor = 0; + while ( + !reconnect + .requests() + .some( + (request) => + scopeOf(request).includes("task-00000") && request[2].limit === 500, + ) + ) { + const request: WireRequest | undefined = reconnect.requests()[cursor++]; + assert.exists(request); + await reconnect.receive(["EOSE", request[1]]); + } + const replayRoute = reconnect + .requests() + .find( + (request) => + scopeOf(request).includes("task-00000") && request[2].limit === 500, + ); + assert.exists(replayRoute); + const missed = message(author, "task-00000", "missed input", 1_700_000_103); + await reconnect.receive(["EVENT", replayRoute[1], missed]); + expect(live).toHaveBeenCalledWith({ + channelId: "task-00000", + events: [missed], + replay: true, + }); + } finally { + owner.dispose(); + } +}, 120_000); + +it("finishes initial channel setup before renewing established batches", async () => { + vi.useFakeTimers(); + const h = setup([]); + try { + const ids = Array.from( + { length: 400 }, + (_, i) => `c${String(i).padStart(3, "0")}`, + ); + h.owner.update(ids, ids); + await h.first.auth(); + for (const request of h.first + .requests() + .filter((request) => !scopeOf(request).length)) + await h.first.receive(["EOSE", request[1]]); + let cursor = 2; + for (let round = 0; round < 7; round++) { + await vi.advanceTimersByTimeAsync(8000); + const pending = h.first.requests().slice(cursor); + cursor = h.first.requests().length; + for (const request of pending) + await h.first.receive(["EOSE", request[1]]); + } + const pending = h.first.requests().slice(cursor); + await vi.advanceTimersByTimeAsync(4000); + assert.exists(pending[0]); + const before = h.first.requests().length; + await h.first.receive(["EOSE", pending[0][1]]); + expect(h.first.requests()).toHaveLength(before + 1); + expect(h.first.requests().at(-1)?.[2].limit).toBe(500); + } finally { + h.owner.dispose(); + } +}); + +it.each(["replacement", "source"])( + "keeps survivor alerts when %s delivers first during batch expansion", + async (first) => { + vi.useFakeTimers({ now: 1_700_000_100_000 }); + const h = setup([]), + relay = keypair(), + author = keypair(); + const wire = scriptedTransport(h.key.pubkey, relay.pubkey); + const owner = createRelaySession({ + ...wire.transport, + subscribe(callbacks) { + h.callbacks.receive.mockImplementation(callbacks.receive); + h.callbacks.state.mockImplementation(callbacks.state); + return h.owner; + }, + }); + try { + h.callbacks.receive([roster(relay, "a", [h.key.pubkey])]); + await h.first.auth(); + for (const request of h.first.requests()) + await h.first.receive(["EOSE", request[1]]); + const source = h.first + .requests() + .find((request) => scopeOf(request).includes("a")); + assert.exists(source); + const incoming = vi.fn(); + owner.session.subscribeIncoming(incoming); + h.callbacks.receive([roster(relay, "b", [h.key.pubkey])]); + const replacement = h.first.requests().at(-1); + assert.exists(replacement); + expect(scopeOf(replacement)).toEqual(["a", "b"]); + const event = message(author, "a", "fresh survivor", 1_700_000_101); + const sources = + first === "replacement" ? [replacement, source] : [source, replacement]; + for (const request of sources) + await h.first.receive(["EVENT", request[1], event]); + expect(incoming).toHaveBeenCalledTimes(1); + expect(filtersOf(replacement).map((filter) => filter.limit)).toEqual([ + 0, 500, + ]); + } finally { + owner.dispose(); + } + }, +); + +it.each(["transient failure", "removal"])( + "keeps the live survivor source after %s in an expanding batch", + async (outcome) => { + vi.useFakeTimers(); + const h = setup([]); + try { + h.owner.update(["a", "b"], ["a", "b"]); + await h.first.auth(); + for (const request of h.first.requests()) + await h.first.receive(["EOSE", request[1]]); + const source = h.first + .requests() + .find((request) => scopeOf(request).includes("b")); + assert.exists(source); + h.owner.update(["a", "b", "c"], ["a", "b", "c"]); + const replacement = h.first.requests().at(-1); + assert.exists(replacement); + if (outcome === "transient failure") + await h.first.receive([ + "CLOSED", + replacement[1], + "error: internal server error", + ]); + else h.owner.update(["b", "c"], ["b", "c"]); + expect(h.first.sent).not.toContainEqual(["CLOSE", source[1]]); + const event = message(h.key, "b", "survivor remains live", 1_700_000_101); + await h.first.receive(["EVENT", source[1], event]); + expect(h.callbacks.receive).toHaveBeenLastCalledWith([event], { + phase: "live", + channelId: "b", + }); + if (outcome === "transient failure") h.owner.retry(); + const retry = h.first.requests().at(-1); + assert.exists(retry); + expect( + filtersOf(retry).find((filter) => filter["#h"]?.includes("c"))?.limit, + ).toBe(500); + } finally { + h.owner.dispose(); + } + }, +); + +it("prioritizes a growing initial batch over healthy renewals", async () => { + vi.useFakeTimers(); + const h = setup([]); + try { + const ids = Array.from( + { length: 320 }, + (_, i) => `c${String(i).padStart(3, "0")}`, + ); + h.owner.update(ids, ids); + await h.first.auth(); + for (let i = 0; i < h.first.requests().length; i++) + await h.first.receive(["EOSE", h.first.requests()[i]?.[1]]); + const start = h.first.requests().length; + await vi.advanceTimersByTimeAsync(60_000); + h.owner.update([...ids, "new-a"], [...ids, "new-a"]); + const renewal = h.first.requests()[start]; + assert.exists(renewal); + await h.first.receive(["EOSE", renewal[1]]); + const initial = h.first.requests().at(-1); + assert.exists(initial); + expect(scopeOf(initial)).toEqual(["new-a"]); + h.owner.update([...ids, "new-a", "new-b"], [...ids, "new-a", "new-b"]); + const expanded = h.first.requests().at(-1); + assert.exists(expanded); + expect(scopeOf(expanded)).toEqual(["new-a", "new-b"]); + } finally { + h.owner.dispose(); + } +}); + +it("covers 100,000 channels with protocol-sized live batches and a bounded replay queue", async () => { + vi.useFakeTimers(); + const ids = Array.from( + { length: 100_000 }, + (_, i) => `task-${String(i).padStart(6, "0")}`, + ); + const h = setup([], createLiveAdmission(), 2048); + let latest: Parameters[0] | undefined; + h.callbacks.state.mockImplementation((state) => { + latest = state; + h.callbacks.state.mockClear(); + }); + const live = new Map(); + let replayed = 0; + const active = new Set(); + const drain = async (start = 0) => { + for (let i = start; i < h.first.sent.length; i++) { + const frame = h.first.sent[i] as WireRequest; + if (frame[0] === "CLOSE") active.delete(frame[1]); + if (frame[0] !== "REQ") continue; + active.add(frame[1]); + expect(active.size).toBeLessThanOrEqual(1024); + const filters = filtersOf(frame); + expect(filters.length).toBeLessThanOrEqual(10); + expect(scopeOf(frame).length).toBeLessThanOrEqual(2048); + if (scopeOf(frame).length && filters[0]?.limit === 0) { + for (const id of scopeOf(frame)) live.set(id, frame); + } else if (scopeOf(frame).length) { + expect( + filters.every((f) => f["#h"]?.length === 1 && f.limit === 500), + ).toBe(true); + replayed += filters.length; + } + await h.first.receive(["EOSE", frame[1]]); + } + }; + try { + h.owner.update(ids, ids); + await h.first.auth(); + await drain(); + expect(live.size).toBe(100_000); + expect(replayed).toBe(100_000); + expect(active.size).toBe(51); + expect( + latest?.routes.filter((r) => r.channelId && r.status === "live"), + ).toHaveLength(100_000); + const last = ids.at(-1); + assert.exists(last); + const source = live.get(last); + assert.exists(source); + const event = message(h.key, last, "last channel input", 1700000001); + await h.first.receive(["EVENT", source[1], event]); + expect(h.callbacks.receive).toHaveBeenLastCalledWith([event], { + channelId: last, + phase: "live", + }); + const start = h.first.sent.length; + h.owner.update( + [...ids.slice(0, -1), "replacement"], + [...ids.slice(0, -1), "replacement"], + ); + await drain(start); + h.callbacks.receive.mockClear(); + await h.first.receive(["EVENT", source[1], event]); + expect(h.callbacks.receive).not.toHaveBeenCalled(); + expect( + latest?.routes.some( + (r) => r.channelId === "replacement" && r.status === "live", + ), + ).toBe(true); + expect(latest?.routes.some((r) => r.channelId === last)).toBe(false); + } finally { + h.owner.dispose(); + } + expect(vi.getTimerCount()).toBe(0); +}, 60_000); + +it("reports a replay failure to recovery, continues other channels, and exposes its retry", async () => { + vi.useFakeTimers(); + const ids = Array.from( + { length: 80 }, + (_, i) => `c${String(i).padStart(3, "0")}`, + ); + const h = setup([], createLiveAdmission(), 2048); + try { + h.owner.update(ids, ids); + await h.first.auth(); + for (const request of [...h.first.requests()]) + await h.first.receive(["EOSE", request[1]]); + const replay = h.first + .requests() + .find((request) => scopeOf(request).length && request[2].limit === 500); + assert.exists(replay); + const id = scopeOf(replay)[0]; + assert.exists(id); + const before = h.first.requests().length; + await h.first.receive(["CLOSED", replay[1], "error: replay unavailable"]); + expect(h.first.requests()).toHaveLength(before + 1); + const snapshot = h.callbacks.state.mock.lastCall?.[0]; + assert.exists(snapshot); + expect( + snapshot.routes.find((route) => route.channelId === id), + ).toMatchObject({ status: "error", error: "error: replay unavailable" }); + expect( + liveRecoveryStatus({ + ...snapshot, + roster: { state: "verified" }, + heads: [], + }), + ).toBe("failed"); + h.owner.retry(); + expect( + h.callbacks.state.mock.lastCall?.[0].routes.find( + (route) => route.channelId === id, + ), + ).toMatchObject({ status: "pending" }); + let retry: WireRequest | undefined; + for (let i = before; i < h.first.requests().length; i++) { + const request = h.first.requests()[i]; + assert.exists(request); + if (scopeOf(request).includes(id)) { + retry = request; + break; + } + await h.first.receive(["EOSE", request[1]]); + } + assert.exists(retry); + await h.first.receive(["EOSE", retry[1]]); + expect( + h.callbacks.state.mock.lastCall?.[0].routes.find( + (route) => route.channelId === id, + ), + ).toMatchObject({ status: "live" }); + expect( + h.callbacks.state.mock.lastCall?.[0].routes.find( + (route) => route.channelId === id, + )?.error, + ).toBeUndefined(); + } finally { + h.owner.dispose(); + } +}); + +it.each([ + "replay-first", + "live-first", + "known-history", + "replay-finite-live", + "finite-first", +])( + "keeps incoming alerts correct across duplicate sources: %s", + async (order) => { + vi.useFakeTimers({ now: 1_700_000_100_000 }); + const h = setup([], createLiveAdmission(), 2048); + const relay = keypair(), + author = keypair(); + const wire = scriptedTransport(h.key.pubkey, relay.pubkey); + const owner = createRelaySession({ + ...wire.transport, + subscribe(callbacks) { + h.callbacks.receive.mockImplementation(callbacks.receive); + h.callbacks.state.mockImplementation(callbacks.state); + return h.owner; + }, + }); + try { + const ids = Array.from( + { length: 11 }, + (_, i) => `c${String(i).padStart(2, "0")}`, + ); + h.callbacks.receive(ids.map((id) => roster(relay, id, [h.key.pubkey]))); + await h.first.auth(); + for (const request of [...h.first.requests()]) + await h.first.receive(["EOSE", request[1]]); + const source = h.first + .requests() + .find((r) => scopeOf(r).includes("c00") && r[2].limit === 0); + const replay = h.first + .requests() + .find((r) => scopeOf(r).includes("c00") && r[2].limit === 500); + assert.exists(source); + assert.exists(replay); + const incoming = vi.fn(); + owner.session.subscribeIncoming(incoming); + const event = message(author, "c00", "fresh input", 1_700_000_100); + const finite = async () => { + const read = owner.session.readRemote([ + { kinds: [9], "#h": ["c00"], limit: 10 }, + ]); + wire.next().respond([event]); + await read; + }; + if (order === "known-history") h.callbacks.receive([event]); + if (order === "finite-first") await finite(); + if (order === "live-first") + await h.first.receive(["EVENT", source[1], event]); + await h.first.receive(["EVENT", replay[1], event]); + await h.first.receive(["EVENT", replay[1], event]); + expect(incoming).toHaveBeenCalledTimes(order === "live-first" ? 1 : 0); + if (order === "replay-finite-live") await finite(); + await h.first.receive(["EVENT", source[1], event]); + const count = + order === "known-history" || order === "finite-first" ? 0 : 1; + expect(incoming).toHaveBeenCalledTimes(count); + await h.first.receive(["EVENT", replay[1], event]); + await h.first.receive(["EVENT", source[1], event]); + expect(incoming).toHaveBeenCalledTimes(count); + } finally { + owner.dispose(); + } + }, +); + +it("shares the wire budget with artifact syncs and the silence probe", async () => { + vi.useFakeTimers(); + const ids = Array.from({ length: 1024 }, (_, i) => `c${i}`); + const h = setup(ids); + const release: (() => void)[] = []; + try { + await h.first.auth(); + assert.exists(h.owner.syncArtifacts); + for (let i = 0; i < 32; i++) + release.push( + h.owner.syncArtifacts( + { + artifact: "current", + "#h": ["11111111-1111-4111-8111-111111111111"], + }, + { event() {}, eose() {}, closed() {} }, + ), + ); + const refused = vi.fn(); + h.owner.syncArtifacts( + { artifact: "current", "#h": ["11111111-1111-4111-8111-111111111111"] }, + { event() {}, eose() {}, closed: refused }, + ); + await Promise.resolve(); + expect(refused).toHaveBeenCalledExactlyOnceWith( + "error: artifact sync capacity reached", + ); + for (let i = 0; i < h.first.requests().length; i++) { + await h.first.receive(["EOSE", h.first.requests()[i]?.[1]]); + h.callbacks.state.mockClear(); + } + await vi.advanceTimersByTimeAsync(120_000); + const active = new Set(); + for (const [kind, id] of h.first.sent) { + if (kind === "REQ") active.add(id); + if (kind === "CLOSE") active.delete(id); + expect(active.size).toBeLessThanOrEqual(1024); + } + expect( + h.first.requests().filter((request) => request[1].startsWith("sync-")), + ).toHaveLength(32); + expect(h.first.probes()).toHaveLength(1); + } finally { + for (const close of release) close(); + h.owner.dispose(); + } +}); +it("reserves the silence probe when a profile sync starts at channel capacity", async () => { + vi.useFakeTimers(); + const h = setup(Array.from({ length: 1021 }, (_, index) => `c${index}`)); + let release: (() => void) | undefined; + try { + await h.first.auth(); + for (let i = 0; i < h.first.requests().length; i++) + await h.first.receive(["EOSE", h.first.requests()[i]?.[1]]); + assert.exists(h.owner.syncVerifiedProfiles); + release = h.owner.syncVerifiedProfiles( + verifiedProfileFilter("a".repeat(64), ["b".repeat(64)]), + { event() {}, eose() {}, closed() {} }, + ); + await Promise.resolve(); + await vi.advanceTimersByTimeAsync(120_000); + expect(h.first.probes()).toHaveLength(1); + release(); + release = undefined; + for (let i = 0; i < h.first.requests().length; i++) + await h.first.receive(["EOSE", h.first.requests()[i]?.[1]]); + const active = new Set(); + for (const [kind, id] of h.first.sent) { + if (kind === "REQ") active.add(id); + if (kind === "CLOSE") active.delete(id); + expect(active.size).toBeLessThanOrEqual(1024); + } + expect( + h.callbacks.state.mock.lastCall?.[0].routes.some( + (route) => route.status === "limited", + ), + ).toBe(false); + } finally { + release?.(); + h.owner.dispose(); + } +}); +it("bounds profile syncs even without channel routes", async () => { + vi.useFakeTimers(); + const h = setup([]); + const release: (() => void)[] = []; + try { + await h.first.auth(); + assert.exists(h.owner.syncVerifiedProfiles); + const filter = verifiedProfileFilter("a".repeat(64), ["b".repeat(64)]); + for (let i = 0; i < 32; i++) + release.push( + h.owner.syncVerifiedProfiles(filter, { + event() {}, + eose() {}, + closed() {}, + }), + ); + const refused = vi.fn(); + release.push( + h.owner.syncVerifiedProfiles(filter, { + event() {}, + eose() {}, + closed: refused, + }), + ); + await Promise.resolve(); + expect(refused).toHaveBeenCalledExactlyOnceWith( + "error: profile sync capacity reached", + ); + expect( + h.first.requests().filter((request) => request[1].startsWith("sync-")), + ).toHaveLength(32); + } finally { + for (const close of release) close(); + h.owner.dispose(); + } +}); describe("policy close (1008) recovery", () => { const deny = async (socket: Socket) => { await socket.receive(["NOTICE", "auth-required: authorization denied"]); @@ -3979,6 +4748,49 @@ it("keeps a planned renewal connected and skips catch-up for carried routes", as } expect(vi.getTimerCount()).toBe(0); }); +it("catches up a live-only batch after a planned renewal", async () => { + vi.useFakeTimers(); + const h = setup([], undefined, 2048); + const ids = Array.from({ length: 11 }, (_, index) => `room-${index}`); + try { + h.owner.update(ids, ids); + await establish(h.first); + for (let i = 0; i < h.first.requests().length; i++) + await h.first.receive(["EOSE", h.first.requests()[i]?.[1]]); + h.callbacks.established.mockClear(); + h.callbacks.state.mockClear(); + renew(h.first); + const second = h.sockets[1]; + assert.exists(second); + await second.auth(); + await vi.advanceTimersByTimeAsync(750); + const batch = second + .requests() + .find((request) => + filtersOf(request).some( + (filter) => filter.limit === 0 && filter["#h"]?.length === 11, + ), + ); + assert.exists(batch); + for (const request of second.requests()) + if (request[1] !== batch[1]) await second.receive(["EOSE", request[1]]); + expect(h.callbacks.established).not.toHaveBeenCalled(); + h.callbacks.state.mockClear(); + await second.receive(["EOSE", batch[1]]); + expect(h.callbacks.state.mock.calls.map(([state]) => state.status)).toEqual( + ["connected", "connecting", "connected"], + ); + expect(h.callbacks.established).toHaveBeenCalledWith( + expect.arrayContaining(ids), + ); + expect(h.callbacks.established).toHaveBeenCalledTimes(3); + for (let i = 0; i < second.requests().length; i++) + await second.receive(["EOSE", second.requests()[i]?.[1]]); + } finally { + h.owner.dispose(); + } + expect(vi.getTimerCount()).toBe(0); +}); it("recovers like an outage after a renewal whose replay hit the limit", async () => { vi.useFakeTimers(); const h = setup(["a", "b"]); diff --git a/src/features/relay/live.ts b/src/features/relay/live.ts index 1926a61d29..5be0447f11 100644 --- a/src/features/relay/live.ts +++ b/src/features/relay/live.ts @@ -18,13 +18,15 @@ import { import type { EventTemplate, VerifiedEvent } from "nostr-tools"; import { createEventVerifier, eventDto } from "./events.ts"; import { EMOJI_SET } from "./emoji.ts"; -import type { - ArtifactSyncFilter, - ArtifactSyncSink, +import { + ARTIFACT_SYNC_MAX_VIEWS, + type ArtifactSyncFilter, + type ArtifactSyncSink, } from "./artifact-sync-filter.ts"; export const LIVE_CHANNEL_CAPACITY = 1022; -export const LIVE_BATCH_SIZE = 10; // Relay's per-REQ filter cap; replay stays per channel. +export const LIVE_BATCH_SIZE = 2048; // Relay limit for explicit channel IDs per REQ. +const REPLAY_BATCH_SIZE = 10; // Relay limit for filters per REQ. export const LIVE_REPLAY_LIMIT = 500; export const LIVE_RECOVERY_INTERVAL = 60_000; /** A live batch is re-sent after this long even with no grant, in case a @@ -267,14 +269,11 @@ export function livePresenceAuthors(input: unknown): string[] { export function liveChannels(input: unknown): string[] { if ( !Array.isArray(input) || - input.length > 1024 || input.some( (id) => typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(id), ) ) - throw new Error( - "Invalid live channel interests (maximum 1024 bounded IDs)", - ); + throw new Error("Invalid live channel interests"); return [...new Set(input as string[])].sort(); } @@ -284,7 +283,8 @@ export function liveJoined( input: unknown, ): string[] { const joined = liveChannels(input); - if (joined.some((id) => !channels.includes(id))) + const interests = new Set(channels); + if (joined.some((id) => !interests.has(id))) throw new Error("Joined scope outside live interests"); return joined; } @@ -293,6 +293,7 @@ type Route = { id: string; channelId?: string; channelIds?: readonly string[]; + history?: boolean; status: LiveRoute["status"]; replay: LiveRoute["replay"]; error?: string; @@ -300,7 +301,9 @@ type Route = { count: number; since: number; liveOnly?: boolean; + replayChannels?: readonly string[]; previous?: Route; + previousChannels?: readonly string[]; retryRenewal?: boolean; /** Live on the socket a planned renewal replaced, over the same scope. Its * replay resumes from the cursor, so its EOSE needs no catch-up. */ @@ -345,8 +348,17 @@ export function subscribeRelayTraffic( admission: LiveAdmission = createLiveAdmission(), setupConcurrency = SETUP_CONCURRENCY, setupTimeoutMs = SETUP_TIMEOUT_MS, + channelBatchSize = LIVE_BATCH_SIZE, random: () => number = Math.random, ): LiveSubscription { + if ( + !Number.isInteger(channelBatchSize) || + channelBatchSize < 1 || + channelBatchSize > LIVE_BATCH_SIZE + ) + throw new Error("Invalid channel batch size"); + const replaySlots = + channelBatchSize > REPLAY_BATCH_SIZE ? setupConcurrency : 0; const log = getLogger("relay-ws"); const peer = relayLabel(url); let closed = false; @@ -392,6 +404,7 @@ export function subscribeRelayTraffic( // individual lifetimes without admitting a replacement mid-denial. let denying: Set | undefined; let priority: string[] = []; + let priorityRanks = new WeakMap(); let observer: number | null = null; let presenceAuthors: readonly string[] = []; let presenceReceipt: @@ -432,33 +445,74 @@ export function subscribeRelayTraffic( if (!syncs.delete(sync)) return; if (sync.wire) syncWires.delete(sync.wire); sync.sink.closed(reason); + syncInterests(); } - const notify = () => { + const replayQueue = new Map(); + let routeSnapshots = new Map(); + let replayStopped = false; + const setupState = () => { admission.setup( routes, !closed && connection !== "error" && - [...routes.values()].some((route) => route.status === "pending"), + ((!replayStopped && replayQueue.size > 0) || + [...routes.values()].some((route) => route.status === "pending")), ); + }; + const notify = () => { + setupState(); if (closed) return; + const replayFailures = new Map( + [...routes.values()] + .filter((route) => route.history && route.error !== undefined) + .flatMap((route) => scope(route).map((id) => [id, route] as const)), + ); + const next = new Map(); + for (const route of routes.values()) { + if (route.history) continue; + const retained = + route.status === "pending" && route.previous?.status === "live" + ? new Set(route.previousChannels) + : undefined; + for (const channelId of route.channelIds ?? [route.channelId]) { + const id = channelId ? `channel:${channelId}` : route.id; + const replayFailure = channelId + ? replayFailures.get(channelId) + : undefined; + const sourceStatus = + (route.carried && route.status === "pending") || + (channelId !== undefined && retained?.has(channelId)) + ? "live" + : route.status; + const status = + sourceStatus === "live" && replayFailure + ? replayFailure.status + : sourceStatus; + const error = route.error ?? replayFailure?.error; + const previous = routeSnapshots.get(id); + next.set( + id, + previous && + previous.status === status && + previous.replay === route.replay && + previous.error === error + ? previous + : Object.freeze({ + id, + ...(channelId ? { channelId } : {}), + status, + replay: route.replay, + ...(error ? { error } : {}), + }), + ); + } + } + routeSnapshots = next; callbacks.state( Object.freeze({ status: renewing && connection === "connecting" ? "connected" : connection, - routes: Object.freeze( - [...routes.values()].flatMap( - ({ id, channelId, channelIds, status, replay, error, carried }) => - (channelIds ?? [channelId]).map((channelId) => - Object.freeze({ - id: channelId ? `channel:${channelId}` : id, - ...(channelId ? { channelId } : {}), - status: carried && status === "pending" ? "live" : status, - replay, - ...(error ? { error } : {}), - }), - ), - ), - ), + routes: Object.freeze([...next.values()]), ...(connectionError ? { error: connectionError } : {}), }), ); @@ -492,6 +546,16 @@ export function subscribeRelayTraffic( // A sent replacement is not yet established. Keep the established source // through repeated removals; retire the pending intermediate, not a survivor. const previous = route.previous ?? (route.wire ? route : undefined); + const previousChannels = previous + ? (previous === route + ? scope(route) + : (route.previousChannels ?? scope(previous)) + ).filter((id) => ids.includes(id)) + : []; + const replayChannels = + route.status !== "live" + ? route.replayChannels?.filter((id) => ids.includes(id)) + : undefined; delete route.previous; if (previous !== route) closeWire(route); // Never retain a third wire. clearTimeout(route.deadline); @@ -499,11 +563,13 @@ export function subscribeRelayTraffic( ...route, ...(route.channelIds ? { channelIds: ids } : {}), status: "pending", - liveOnly: true, + liveOnly: !replayChannels?.length, count: 0, quotaRetries: 0, - ...(previous ? { previous } : {}), + ...(previous ? { previous, previousChannels } : {}), }; + delete next.replayChannels; + if (replayChannels?.length) next.replayChannels = replayChannels; delete next.wire; delete next.deadline; delete next.retryRenewal; @@ -564,6 +630,7 @@ export function subscribeRelayTraffic( // re-sent here too. for (const route of routes.values()) { if ( + !route.history && route.channelIds && route.status === "live" && !route.previous && @@ -600,22 +667,49 @@ export function subscribeRelayTraffic( if (!closed && authenticated && generation === current) recoveryTimer = setTimeout(recover, LIVE_RECOVERY_INTERVAL); } - function sync() { + function syncInterests() { if (denying || closed) return; + const interested = new Set(interests); + const members = new Set(joined); + for (const id of replayQueue.keys()) + if (!interested.has(id) || !members.has(id)) replayQueue.delete(id); const ranked = [ ...new Set([ - ...priority.filter((id) => interests.includes(id)), + ...priority.filter((id) => interested.has(id)), ...interests, ]), ]; - const admitted = new Set( - ranked.slice( - 0, - LIVE_CHANNEL_CAPACITY - - (observer !== null ? 1 : 0) - - (presenceAuthors.length ? 1 : 0), - ), + const retainedBatches = [...routes.values()].filter( + (route) => + !route.history && route.channelIds?.some((id) => members.has(id)), + ).length; + const batchCount = Math.max( + retainedBatches, + Math.ceil(joined.length / channelBatchSize), + ); + const previewCapacity = Math.max( + 0, + LIVE_CHANNEL_CAPACITY - + batchCount - + syncs.size - + 1 - // Keep one wire for the silence probe. + (joined.length ? setupConcurrency + replaySlots : 0) - + (observer !== null ? 1 : 0) - + (presenceAuthors.length ? 1 : 0), + ); + const joinedSlots = Math.max( + 0, + LIVE_CHANNEL_CAPACITY - + syncs.size - + 1 - + (setupConcurrency + replaySlots) - + (observer !== null ? 1 : 0) - + (presenceAuthors.length ? 1 : 0), ); + const admitted = new Set([ + ...joined.slice(0, joinedSlots * channelBatchSize), + ...ranked.filter((id) => !members.has(id)).slice(0, previewCapacity), + ]); const remaining = new Set(interests); const globals = new Set([ "profiles", @@ -627,23 +721,35 @@ export function subscribeRelayTraffic( // navigation is scheduling, never a reason to rebalance healthy subscriptions. for (const route of routes.values()) { const ids = scope(route); + if (route.history) { + if (ids.some((id) => !interested.has(id) || !members.has(id))) { + remove(route); + for (const id of ids) + if (interested.has(id) && members.has(id)) + replayQueue.set(id, route.since); + } + continue; + } if ( ids.length ? ids.some( (id) => !remaining.has(id) || (route.status === "limited") === admitted.has(id) || - (!!route.channelIds && !joined.includes(id)), + (!!route.channelIds && !members.has(id)) || + (!route.channelIds && members.has(id)), ) : !globals.has(route.id) ) { const survivors = ids.filter( - (id) => remaining.has(id) && admitted.has(id) && joined.includes(id), + (id) => remaining.has(id) && admitted.has(id) && members.has(id), ); if ( route.channelIds && survivors.length && - (route.status === "live" || route.liveOnly) + (route.status === "live" || + route.liveOnly || + route.previous?.status === "live") ) { replace(route, survivors); for (const id of survivors) remaining.delete(id); @@ -664,6 +770,10 @@ export function subscribeRelayTraffic( since: Math.floor(Date.now() / 1000) - 300, }; route.since = resumeSince(route); + if (ids.length > REPLAY_BATCH_SIZE) { + route.liveOnly = true; + for (const id of ids) replayQueue.set(id, route.since); + } route.resumed = cursorKeys(route).every((key) => cursors.has(key)); // Presence and observer feeds establish nothing, so carry no obligation. if ( @@ -687,12 +797,45 @@ export function subscribeRelayTraffic( route.status = "limited"; route.error = "Live channel capacity reached; finite reads remain available"; - } else if (!joined.includes(id) || priority.includes(id)) - add(`channel:${id}`, [id]); + } else if (!members.has(id)) add(`channel:${id}`, [id]); else batch.push(id); } - for (let i = 0; i < batch.length; i += LIVE_BATCH_SIZE) - add(`batch:${++serial}`, batch.slice(i, i + LIVE_BATCH_SIZE), true); + let offset = 0; + for (const route of routes.values()) { + if ( + route.history || + !route.channelIds || + route.channelIds.length >= channelBatchSize || + offset === batch.length + ) + continue; + const added = batch.slice( + offset, + offset + channelBatchSize - route.channelIds.length, + ); + offset += added.length; + const expanded = [...route.channelIds, ...added]; + const next = replace(route, expanded); + next.replayChannels = expanded.filter( + (id) => + !( + next.previous?.status === "live" && + next.previousChannels?.includes(id) + ), + ); + next.liveOnly = !next.replayChannels.length; + next.since = resumeSince({ + ...next, + since: Math.floor(Date.now() / 1000) - 300, + }); + if (expanded.length > REPLAY_BATCH_SIZE) { + for (const id of next.replayChannels) replayQueue.set(id, next.since); + delete next.replayChannels; + next.liveOnly = true; + } + } + for (let i = offset; i < batch.length; i += channelBatchSize) + add(`batch:${++serial}`, batch.slice(i, i + channelBatchSize), true); pump(); notify(); settle(); @@ -708,14 +851,14 @@ export function subscribeRelayTraffic( function fail(route: Route, reason: string, transient = false) { const denial = reason === "restricted: not a channel member"; const previous = route.previous; - // Only an established, unchanged scope may outlive a failed renewal. Never - // restore a retired channel lifetime or bypass denial cleanup. + // A failure can retain the old source only while its full scope remains allowed. const retain = transient && previous?.status === "live" && previous.wire && wires.get(previous.wire) === previous && - JSON.stringify(scope(previous)) === JSON.stringify(scope(route)); + JSON.stringify(scope(previous)) === + JSON.stringify(route.previousChannels ?? scope(route)); if (retain) delete route.previous; closeWire(route); if (route.carried) broken = true; @@ -741,6 +884,7 @@ export function subscribeRelayTraffic( ); const seconds = hint ? Number(hint[1]) : 5; if (!Number.isSafeInteger(seconds) || seconds > 60) { + replayStopped = true; for (const queued of routes.values()) if (queued.status === "pending" && !queued.wire) stop(queued, "Unsupported live cooldown; automatic setup stopped"); @@ -752,6 +896,7 @@ export function subscribeRelayTraffic( admission.pause(seconds); if (++route.quotaRetries <= MAX_QUOTA_RETRIES) route.status = "pending"; else { + replayStopped = true; // Stop the unsent queue too: rejection must never drain it into an exhausted budget. for (const queued of routes.values()) if (queued.status === "pending" && !queued.wire) @@ -774,7 +919,7 @@ export function subscribeRelayTraffic( } } finally { denying = undefined; - sync(); + syncInterests(); } } else notify(); pump(); @@ -824,6 +969,7 @@ export function subscribeRelayTraffic( } } function pump() { + setupState(); clearTimeout(dispatchTimer); if (closed || denying || !authenticated || socket?.readyState !== 1) return; for (let request = requests.next(); request; request = requests.next()) { @@ -836,6 +982,7 @@ export function subscribeRelayTraffic( } for (const sync of syncs) { if (sync.wire) continue; + if (wires.size + syncWires.size + (probe ? 1 : 0) >= 1024) break; const delay = admission.delay(); if (delay > 0) { dispatchTimer = setTimeout(pump, delay); @@ -848,20 +995,70 @@ export function subscribeRelayTraffic( let active = [...routes.values()].filter( (route) => route.wire && route.status === "pending", ).length; - const rank = (route: Route) => - !scope(route).length + // Persistent streams get their setup slots first. Replay retains only IDs + // in the queue, and each request keeps a separate allowance per channel. + if ( + !replayStopped && + ![...routes.values()].some( + (route) => + route.status === "pending" && (!route.history || !route.wire), + ) + ) { + const iterator = replayQueue.entries(); + for ( + let slot = active; + slot < setupConcurrency && + wires.size + syncWires.size + (probe ? 1 : 0) + (slot - active) < 1024; + slot++ + ) { + const ids: string[] = []; + let since = Infinity; + for (let i = 0; i < REPLAY_BATCH_SIZE; i++) { + const entry = iterator.next(); + if (entry.done) break; + const [id, time] = entry.value; + replayQueue.delete(id); + ids.push(id); + since = Math.min(since, time); + } + if (!ids.length) break; + const id = `replay:${++serial}`; + routes.set(id, { + id, + channelIds: ids, + history: true, + status: "pending", + replay: "limited", + count: 0, + quotaRetries: 0, + since, + }); + } + } + const rank = (route: Route) => { + const known = priorityRanks.get(route); + if (known !== undefined) return known; + const value = !scope(route).length ? -2 - : Math.min( - priority.length, - ...scope(route).map((id) => - priority.includes(id) ? priority.indexOf(id) : priority.length, - ), - ); + : !priority.length + ? 0 + : Math.min( + priority.length, + ...scope(route).map((id) => + priority.includes(id) ? priority.indexOf(id) : priority.length, + ), + ); + priorityRanks.set(route, value); + return value; + }; for (const route of [...routes.values()].sort( - (a, b) => rank(a) - rank(b), + (a, b) => + Number(a.previous?.status === "live") - + Number(b.previous?.status === "live") || rank(a) - rank(b), )) { if (active >= setupConcurrency) break; if (route.status !== "pending" || route.wire) continue; + if (wires.size + syncWires.size + (probe ? 1 : 0) >= 1024) break; const delay = admission.delay(); if (delay > 0) { dispatchTimer = setTimeout(pump, delay); @@ -905,12 +1102,21 @@ export function subscribeRelayTraffic( wire, ...filters.map((filter) => ({ ...filter, - // Each channel retains its original replay allowance. Replacements - // are live-only on every actual dispatch, including cooldown retries. + // Survivor filters stay live-only so replay cannot suppress a fresh alert. since: route.since, ...(route.id === "observer" ? {} - : { limit: route.liveOnly ? 0 : LIVE_REPLAY_LIMIT }), + : { + limit: + route.liveOnly || + (route.replayChannels && + "#h" in filter && + !filter["#h"].some((id) => + route.replayChannels?.includes(id), + )) + ? 0 + : LIVE_REPLAY_LIMIT, + }), })), ...(route.id === "membership" ? [ @@ -979,6 +1185,8 @@ export function subscribeRelayTraffic( clearTimeout(recoveryTimer); clearTimeout(deadline); for (const route of routes.values()) clearTimeout(route.deadline); + replayQueue.clear(); + replayStopped = false; wires.clear(); requests.clear(); // A sync has no resume: every sent one ends; unsent ones wait for the next socket. @@ -1012,7 +1220,7 @@ export function subscribeRelayTraffic( connectionError = undefined; carrying = carried; try { - sync(); + syncInterests(); } finally { carrying = undefined; } @@ -1271,7 +1479,7 @@ export function subscribeRelayTraffic( ) return; if (previous) { - const retained = scope(currentRoute); + const retained = currentRoute.previousChannels ?? scope(currentRoute); // Untagged auxiliary events cannot inherit a narrowed scope. Preserve // the original source fence; the replacement can deliver fresh copies. if ( @@ -1283,7 +1491,13 @@ export function subscribeRelayTraffic( } // The session still verifies access and auxiliary target evidence. if (incoming.kind === 20002 && !channelId) return; - if (route.status === "pending" && !route.liveOnly) route.count++; + const replaying = + route.status === "pending" && + !route.liveOnly && + (!route.replayChannels || + !channelId || + route.replayChannels.includes(channelId)); + if (replaying) route.count++; if (route.id === "presence") { if ( incoming.kind === 20001 && @@ -1301,8 +1515,7 @@ export function subscribeRelayTraffic( callbacks.receive( [incoming], Object.freeze({ - phase: - route.liveOnly || route.status === "live" ? "live" : "replay", + phase: replaying ? "replay" : "live", ...(channelId ? { channelId } : ids.length @@ -1319,13 +1532,24 @@ export function subscribeRelayTraffic( grant(destination); } } else if (data[0] === "EOSE" && route.status === "pending") { + if (route.history) { + const failed = route.error !== undefined; + remove(route); + if (failed) notify(); + pump(); + return; + } clearTimeout(route.deadline); if (route.previous) closeWire(route.previous); delete route.previous; route.status = "live"; delete route.error; delete route.refusals; - route.replay = route.count >= LIVE_REPLAY_LIMIT ? "limited" : "unknown"; + route.replay = + route.count >= LIVE_REPLAY_LIMIT || + (route.liveOnly && scope(route).length > REPLAY_BATCH_SIZE) + ? "limited" + : "unknown"; // A carried route's replay covered the renewal unless the limit cut it. const caughtUp = route.carried && route.replay !== "limited"; if (route.carried && !caughtUp) broken = true; @@ -1402,14 +1626,21 @@ export function subscribeRelayTraffic( ); return () => {}; } + if (syncs.size >= ARTIFACT_SYNC_MAX_VIEWS) { + queueMicrotask(() => + sink.closed("error: artifact sync capacity reached"), + ); + return () => {}; + } syncs.add(sync); - queueMicrotask(pump); + syncInterests(); return () => { if (!syncs.delete(sync)) return; if (sync.wire) { syncWires.delete(sync.wire); send(["CLOSE", sync.wire]); } + syncInterests(); }; }, syncVerifiedProfiles(filter, sink) { @@ -1421,14 +1652,21 @@ export function subscribeRelayTraffic( ); return () => {}; } + if (syncs.size >= ARTIFACT_SYNC_MAX_VIEWS) { + queueMicrotask(() => + sink.closed("error: profile sync capacity reached"), + ); + return () => {}; + } syncs.add(sync); - queueMicrotask(pump); + syncInterests(); return () => { if (!syncs.delete(sync)) return; if (sync.wire) { syncWires.delete(sync.wire); send(["CLOSE", sync.wire]); } + syncInterests(); }; }, watchPresence(authors) { @@ -1441,7 +1679,7 @@ export function subscribeRelayTraffic( if (next.length) replace(route); else remove(route); } - sync(); + syncInterests(); }, async publishPresence(status, signal) { if ( @@ -1527,12 +1765,13 @@ export function subscribeRelayTraffic( observer = next; const route = routes.get("observer"); if (route) remove(route); // Fence the old wire before enabling a new generation. - sync(); + syncInterests(); }, prioritize(input) { liveChannels(input); // Same bounded ID validation, but preserve demand order. priority = [...new Set(input)].slice(0, 64); - if (!closed) sync(); + priorityRanks = new WeakMap(); + if (!closed) syncInterests(); }, update(input, batchable = []) { const next = liveChannels(input); @@ -1543,21 +1782,24 @@ export function subscribeRelayTraffic( JSON.stringify(nextJoined) === JSON.stringify(joined)) ) return; - for (const id of denying ?? []) - if ( - !next.includes(id) || - joined.includes(id) !== nextJoined.includes(id) - ) - denying?.delete(id); + if (denying) { + const nextIds = new Set(next), + oldMembers = new Set(joined), + nextMembers = new Set(nextJoined); + for (const id of denying) + if (!nextIds.has(id) || oldMembers.has(id) !== nextMembers.has(id)) + denying.delete(id); + } interests = next; joined = nextJoined; - sync(); + syncInterests(); }, retry() { if (closed) return; clearTimeout(retryTimer); reconnectDelay = BASE_RECONNECT_DELAY; if (authenticated) { + replayStopped = false; for (const route of routes.values()) { if (route.status !== "error") continue; route.status = "pending"; @@ -1576,6 +1818,7 @@ export function subscribeRelayTraffic( syncs.clear(); clearSocket(); routes.clear(); + routeSnapshots.clear(); for (const sync of ending) sync.sink.closed("unsupported: relay session disposed"); }, diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index 838f9e5655..62048c7c84 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -254,10 +254,11 @@ export function createRelaySession( channels.queries.list().channels.some((channel) => channel.id === id), notify, ); - const recent = new ByteLru<{ event: RelayEvent; revision: number }>( - 4096, - 8 * 1024 * 1024, - ); + const recent = new ByteLru<{ + event: RelayEvent; + revision: number; + incoming?: "replay" | "live"; + }>(4096, 8 * 1024 * 1024); const observations = new Set<(events: readonly RelayEvent[]) => void>(); const incomingListeners = new Set(); const liveEventListeners = new Set(); @@ -796,6 +797,7 @@ export function createRelaySession( raw: readonly RelayEvent[], ) => void, signal?: AbortSignal, + incomingPhase?: "replay" | "live", ): readonly RelayEvent[] { if (closed) return []; // Authority precedes every projection, even in a batch containing both a @@ -828,8 +830,25 @@ export function createRelaySession( "events.reconcile", events[0]?.id ?? "empty", () => { - for (const event of visible) - recent.set(event.id, { event, revision: ++revision }); + for (const event of visible) { + const previous = recent.peek(event.id); + // Replay can precede a fresh live copy. Keep alert receipt separate from content receipt. + const incoming = [9, 40002, 40008].includes(event.kind) + ? incomingPhase === "live" || previous?.incoming === "live" + ? "live" + : previous?.incoming === "replay" || + (incomingPhase === "replay" && + !previous && + !unread.event(event.id)) + ? "replay" + : undefined + : undefined; + recent.set(event.id, { + event, + revision: ++revision, + ...(incoming ? { incoming } : {}), + }); + } activity.messagesChanged(visible); if (closed || epoch !== accessEpoch) return; reads.accept(visible); @@ -3254,8 +3273,8 @@ export function createRelaySession( event.pubkey !== transport.viewer && destinations.length === 1 && destinations[0]?.[1] === provenance.channelId && - !recent.peek(event.id) && - !unread.event(event.id) && + (recent.peek(event.id)?.incoming === "replay" || + (!recent.peek(event.id) && !unread.event(event.id))) && !rawLocal().some((item) => item.event.id === event.id) ); }) @@ -3276,7 +3295,13 @@ export function createRelaySession( ); const epoch = accessEpoch; const generation = liveGeneration; - const visible = accept(events); + const visible = accept( + events, + true, + undefined, + undefined, + provenance?.channelId ? provenance.phase : undefined, + ); // Completion subscribers can synchronously clear, revoke or retire this // live delivery. Do not admit its remaining pulses into the new lifetime. if ( diff --git a/src/features/relay/startup.test.ts b/src/features/relay/startup.test.ts index 74dd997577..38218f00bf 100644 --- a/src/features/relay/startup.test.ts +++ b/src/features/relay/startup.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { createRelaySession } from "./session"; import { createSidebarPreferencesStore } from "./sidebar-preferences-store"; +import { byteSize } from "./budget"; import { DiscoveryState } from "./discovery"; import { ReadError } from "./errors"; import type { HeadPersistence, SavedHead, SavedStartup } from "./persistence"; @@ -83,6 +84,7 @@ function setup( cachedOnly = false, initialChannelId?: string, readIntent = false, + maxDiscoveryBytes?: number, ) { let journal: ReadJournal | undefined; const membership = deferred(); @@ -115,6 +117,7 @@ function setup( : {}), }, { + ...(maxDiscoveryBytes ? { maxDiscoveryBytes } : {}), persistence: storage, prepared: true, cachedOnly, @@ -149,11 +152,27 @@ describe("device-local startup", () => { roster(relay, `channel-${index}`, [viewer.pubkey]), ).sort((a, b) => a.id.localeCompare(b.id)), ]; - // Cached alpha plus these rosters exceeds the 1,024-entry retention cap. - capacityRosters = Array.from({ length: 1024 }, (_, i) => + // Large signed snapshot for restore and byte-budget checks. + capacityRosters = Array.from({ length: 10_000 }, (_, i) => roster(relay, `other-${i}`, [viewer.pubkey]), ).sort((a, b) => a.id.localeCompare(b.id)); - }); + }, 60_000); + + it("restores 10,000 signed rosters as cached membership after restart", async () => { + const { owner, channels, storage } = setup(); + await storage.writeStartup?.({ + discovery: { + savedAt: Date.now(), + relayAuthor: relay.pubkey, + events: [...capacityRosters], + }, + }); + await owner.restore(); + expect(channels.list().channels).toHaveLength(10_000); + expect(channels.list().channels.every((channel) => channel.cached)).toBe( + true, + ); + }, 60_000); it.each(["roster failure", "roster cancellation", "metadata failure"])( "retries restored metadata after %s clears cached membership", @@ -594,9 +613,18 @@ describe("device-local startup", () => { expect(channels.window("beta").rows).toEqual([]); }); it.each(["confirm", "omit", "deny"])( - "revalidates demanded cached membership omitted by capacity-limited discovery: %s", + "revalidates demanded cached membership omitted by byte-limited discovery: %s", async (outcome) => { - const { owner, channels, query, membership, storage } = setup(); + const maxBytes = capacityRosters + .slice(0, 500) + .reduce((bytes, event) => bytes + byteSize(event), 0); + const { owner, channels, query, membership, storage } = setup( + disk(), + false, + undefined, + false, + maxBytes, + ); await owner.restore(); channels.ensureList(); await vi.waitFor(() => expect(query).toHaveBeenCalledTimes(1)); diff --git a/src/features/relay/store-discovery.test.ts b/src/features/relay/store-discovery.test.ts index fbefcd8f83..6658be65f6 100644 --- a/src/features/relay/store-discovery.test.ts +++ b/src/features/relay/store-discovery.test.ts @@ -3,6 +3,7 @@ import { WORKFLOW_CHANNEL_BATCH, WORKFLOW_DEFINITION_LIMIT, } from "../workflows/queries"; +import { byteSize } from "./budget"; import { tag, type RelayEvent } from "./events"; import { createRelaySession } from "./session"; import type { ChannelSummary } from "./contracts"; @@ -31,12 +32,12 @@ function named(id: string) { } // Preserve real page/capacity boundaries; sign metadata lazily when requested. beforeAll(() => { - memberships = Array.from({ length: 1025 }, (_, i) => { + memberships = Array.from({ length: 10_001 }, (_, i) => { const id = `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`; names.set(id, { name: `Channel ${i}` }); return roster(relay, id, [viewer.pubkey]); }).sort((a, b) => a.id.localeCompare(b.id)); -}); +}, 60_000); afterEach(() => { for (const owner of owners.splice(0)) owner.dispose(); }); @@ -77,8 +78,12 @@ function setup( next, settled, emit: (events: readonly RelayEvent[]) => receive(events), - async rosters(count: number) { - for (let offset = 0; offset <= count; offset += 500) { + async rosters(count: number, exhaust = true) { + for ( + let offset = 0; + offset < count || (exhaust && offset === count); + offset += 500 + ) { const request = await next(39002); const previous = memberships[offset - 1]; expect(request.filters).toEqual([ @@ -482,44 +487,52 @@ it("keeps membership and earlier names when a later metadata batch fails, then r ).toBe(true); }); -it.each([1024, 1025])( +it.each([10_000, 10_001])( "reports retention coverage truthfully for %i memberships", async (count) => { const h = setup(); h.channels.ensureList(); await h.rosters(count); - await h.metadata(1024); - expect(h.channels.list().channels).toHaveLength(1024); - expect(h.channels.list().coverage).toBe( - count > 1024 ? "partial" : undefined, - ); + await h.metadata(count); + expect(h.channels.list().channels).toHaveLength(count); + expect(h.channels.list().coverage).toBeUndefined(); expect(h.pending).toHaveLength(0); }, + 60_000, ); -it("does not revoke omitted channels when retained rosters exhaust capacity", async () => { - const h = setup(); - h.emit([roster(relay, "omitted", [viewer.pubkey])]); +it("does not revoke omitted channels when retained bytes exhaust the budget", async () => { + const omitted = roster(relay, "omitted", [viewer.pubkey]); + const maxDiscoveryBytes = + byteSize(omitted) + + memberships + .slice(0, 499) + .reduce((bytes, event) => bytes + byteSize(event), 0); + const h = setup({ maxDiscoveryBytes }); + h.emit([omitted]); h.channels.ensureList(); - await h.rosters(1024); - await h.metadata(1023); + await h.rosters(500, false); + await h.metadata(499); expect(h.channels.list().coverage).toBe("partial"); - expect(h.channels.list().channels).toHaveLength(1024); + expect(h.channels.list().channels).toHaveLength(500); expect( h.channels.list().channels.some((channel) => channel.id === "omitted"), ).toBe(true); }); it("keeps coverage partial when exact discovery overflows during omission confirmation", async () => { - const h = setup(); - h.emit(memberships.slice(0, 1024)); - expect(h.channels.list().channels).toHaveLength(1024); + const maxDiscoveryBytes = memberships + .slice(0, 1000) + .reduce((bytes, event) => bytes + byteSize(event), 0); + const h = setup({ maxDiscoveryBytes }); + h.emit(memberships.slice(0, 1000)); + expect(h.channels.list().channels).toHaveLength(1000); h.channels.ensureList(); - await h.rosters(1000); + await h.rosters(976); const confirmation = await h.next(39002); const omitted = memberships - .slice(1000, 1024) + .slice(976, 1000) .flatMap((event) => tag(event, "d") ?? []); const confirmationIds = confirmation.filters[0]?.["#d"] ?? []; expect(confirmation.filters[0]).toMatchObject({ @@ -552,7 +565,7 @@ it("keeps coverage partial when exact discovery overflows during omission confir expect(h.channels.list().coverage).toBe("partial"); confirmation.respond([]); - await h.metadata(1000); + await h.metadata(976); expect(h.session.live.snapshot().roster.state).toBe("verified"); expect(h.channels.list().coverage).toBe("partial"); expect( @@ -562,13 +575,18 @@ it("keeps coverage partial when exact discovery overflows during omission confir expect(h.pending).toHaveLength(0); }); -it("marks metadata retention overflow as partial without discarding membership", async () => { - const h = setup(); - const member = memberships[1024]; +it("marks metadata byte overflow as partial without discarding membership", async () => { + const initial = [...names.keys()].slice(0, 500).map(named); + const retained = new Set(initial.map((event) => tag(event, "d"))); + const member = memberships.find((event) => !retained.has(tag(event, "d"))); assert.exists(member); const id = tag(member, "d"); assert.exists(id); - h.emit([...names.keys()].filter((channelId) => channelId !== id).map(named)); + const maxDiscoveryBytes = + byteSize(member) + + initial.reduce((bytes, event) => bytes + byteSize(event), 0); + const h = setup({ maxDiscoveryBytes }); + h.emit(initial); h.channels.ensureList(); (await h.next(39002)).respond([member]); (await h.next(39000)).respond([named(id)]); @@ -1628,8 +1646,16 @@ it("reports landed public pages' matches while the read goes on, to a search tha expect(h.pending).toHaveLength(0); }); +function retainedDiscoveryBytes(count: number) { + return memberships.slice(0, count).reduce((bytes, event) => { + const id = tag(event, "d"); + assert.exists(id); + return bytes + byteSize(event) + byteSize(named(id)); + }, 0); +} + it("leaves a nearly full discovery room for the final public search answer", async () => { - const h = setup(); + const h = setup({ maxDiscoveryBytes: retainedDiscoveryBytes(1023) + 512 }); h.channels.ensureList(); await h.rosters(1023); await h.metadata(1023); @@ -1640,8 +1666,8 @@ it("leaves a nearly full discovery room for the final public search answer", asy progress: (found) => typed.push(names(found)), }); assert.exists(done); - // The one free slot is kept for the final answer: a page in flight would - // spend it on a match the better one on the next page then cannot replace. + // The remaining bytes fit one final metadata record. Provisional records + // cannot consume the budget for a better match on the next page. (await take()).respond(first); await vi.waitFor(() => expect(typed).toEqual([[]])); (await take()).respond(second); @@ -1653,14 +1679,14 @@ it("leaves a nearly full discovery room for the final public search answer", asy }); it("leaves room for the final answers of public searches that run side by side", async () => { - const h = setup(); + const h = setup({ maxDiscoveryBytes: retainedDiscoveryBytes(1022) + 1024 }); h.channels.ensureList(); await h.rosters(1022); await h.metadata(1022); const { id, first, second, take, resolves, names } = openDirectory(h); const typed: string[][] = []; // Cmd-K's `in:recent-1 nsec-backup`: an exact lookup and a substring search - // share the read, and each final answer needs one of the two free slots. + // share the read, and each final answer needs its metadata byte budget. const found = h.channels.searchPublic?.("nsec-backup", { limit: 1, progress: (found) => typed.push(names(found)), @@ -1671,8 +1697,7 @@ it("leaves room for the final answers of public searches that run side by side", }); assert.exists(found); assert.exists(scoped); - // A page in flight would spend a slot on a match the substring search's - // final answer replaces, leaving the exact lookup none. + // Provisional metadata cannot consume the bytes for either final answer. (await take()).respond(first); await vi.waitFor(() => expect(typed).toEqual([[]])); (await take()).respond(second); @@ -1686,7 +1711,7 @@ it("leaves room for the final answers of public searches that run side by side", }); it("leaves room for the final answer of a public search that joins after a page lands", async () => { - const h = setup(); + const h = setup({ maxDiscoveryBytes: retainedDiscoveryBytes(1022) + 1024 }); h.channels.ensureList(); await h.rosters(1022); await h.metadata(1022); @@ -1697,8 +1722,8 @@ it("leaves room for the final answer of a public search that joins after a page progress: (found) => typed.push(names(found)), }); assert.exists(found); - // Alone on the read, a page in flight would still spend a slot the final - // answers of this search and of an `in:` lookup joining later both need. + // The byte budget stays available for this final answer and for an + // exact lookup that can join the read later. (await take()).respond(first); await vi.waitFor(() => expect(typed).toEqual([[]])); // Editing `nsec-backup` to `in:recent-1 nsec-backup` starts only the lookup. diff --git a/src/features/relay/store.ts b/src/features/relay/store.ts index a59ecb2c8d..bd4125ccba 100644 --- a/src/features/relay/store.ts +++ b/src/features/relay/store.ts @@ -95,6 +95,7 @@ export type ChannelStoreOptions = { /** Warm every roster channel's head in the background before it is opened. */ warm?: boolean; persistence?: HeadPersistence; + maxDiscoveryBytes?: number; maxHeadBytes?: number; maxHeads?: number; maxHistoryRows?: number; @@ -113,6 +114,8 @@ const DISCOVERY_LIMIT = 500; // Public channel metadata for name search, read a page at a time up to a // bound; matches resolve exactly. const PUBLIC_CHANNEL_PAGE = 500; +// One exact resolution can consume the reader's full response byte budget. +const PUBLIC_CHANNEL_RESERVE_BYTES = 8 * 1024 * 1024; const PUBLIC_CHANNEL_DIRECTORY = 20_000; /** One creator's channels with one label: a small answer, within one `resolve`. */ const LABELED_CHANNEL_PAGE = 100; @@ -251,7 +254,11 @@ export function createChannelStore( let allowed: Set | undefined; let coverage: "partial" | undefined; const discovery = transport - ? new DiscoveryState(transport.viewer, transport.relayAuthor) + ? new DiscoveryState( + transport.viewer, + transport.relayAuthor, + options.maxDiscoveryBytes, + ) : null; // Restored metadata needs confirmation independently of roster progress/retries. const pendingMetadata = new Set(); @@ -1114,7 +1121,6 @@ export function createChannelStore( saved.savedAt > now() || now() - saved.savedAt > 86_400_000 || !Array.isArray(saved.events) || - saved.events.length > 3072 || byteSize(saved) > 8 * 1024 * 1024 ) return; @@ -1158,12 +1164,14 @@ export function createChannelStore( } } // Background reads deduplicate metadata versions; strong resolution revisits proof. - const creationReads = new Map(); + type CreationRead = { version: string; complete: boolean }; + const creationReads = new Map(); async function readCreations( events: readonly RelayEvent[], settings?: ChannelReadOptions, ) { if (!transport || !discovery || options.cachedOnly) return; + const pending = new Map(); const filters = events.flatMap((event) => { const id = tag(event, "d"); const identity = channelIdentity(event); @@ -1176,10 +1184,12 @@ export function createChannelStore( discovery.get(id)?.parentChannelId || !identity.creator || (settings?.consistency !== "strong" && - creationReads.get(id) === event.id) + creationReads.get(id)?.version === event.id) ) return []; - creationReads.set(id, event.id); + const read = { version: event.id, complete: false }; + creationReads.set(id, read); + pending.set(id, read); return [ { kinds: [9007], @@ -1212,17 +1222,21 @@ export function createChannelStore( settings?.signal?.throwIfAborted(); if (disposed || generation !== epoch || controller.signal.aborted) throw new DOMException("Stale creation resolution", "AbortError"); + for (const filter of filters.slice(offset, offset + 4)) { + const id = filter["#h"][0]; + const read = id && pending.get(id); + if (id && read && creationReads.get(id) === read) + read.complete = true; + } applyDiscovery(receipts.filter((event) => event.kind === 9007)); } })() .catch((error) => { // Unavailable proof leaves an ordinary channel. A later metadata refresh // may retry; never turn a failed proof read into loss of channel access. - for (const event of events) { - const id = tag(event, "d"); - if (id && creationReads.get(id) === event.id) + for (const [id, read] of pending) + if (!read.complete && creationReads.get(id) === read) creationReads.delete(id); - } throw error; }) .finally(() => controllers.delete(controller)); @@ -1439,6 +1453,7 @@ export function createChannelStore( let outcome: RosterRefresh = { state: "deferred" }; try { const ids = new Set(); + let scannedBytes = 0; const named = new Set(); let cursor: RelayEvent | undefined; let complete: Set | undefined; @@ -1452,8 +1467,8 @@ export function createChannelStore( let system: RelayEvent[] = []; if (transport.channelIdentity) { let systemCursor: RelayEvent | undefined; - for (let page = 0; ; page++) { - if (page > discovery.capacity / DISCOVERY_LIMIT) + for (;;) { + if (scannedBytes >= discovery.maxBytes) throw new ReadError( "invalid-response", "System channel discovery exceeded its read budget", @@ -1477,6 +1492,7 @@ export function createChannelStore( { signal: controller.signal }, ); if (disposed || generation !== epoch) return; + scannedBytes += listByteSize(rosters); const members = rosters .filter( (event) => @@ -1516,9 +1532,8 @@ export function createChannelStore( paged = true; } } - // At most the retained roster budget plus its final exhaustion read. - // This also bounds a relay returning repeated coordinates with new versions. - for (let page = 0; page <= discovery.capacity / DISCOVERY_LIMIT; page++) { + // Bound scanned bytes as well as retained evidence, including repeated versions. + for (;;) { const rosters = await transport.read( [ { @@ -1534,6 +1549,7 @@ export function createChannelStore( { signal: controller.signal }, ); if (disposed || generation !== epoch) return; + scannedBytes += listByteSize(rosters); const members = rosters .filter( (event) => @@ -1586,7 +1602,7 @@ export function createChannelStore( retainedComplete = !paged; break; } - if (overflowed) break; + if (overflowed || scannedBytes >= discovery.maxBytes) break; cursor = last; paged = true; } @@ -2141,7 +2157,7 @@ export function createChannelStore( // before granting a preview. The final answer re-reads every match; pages // in flight resolve at most `limit` channels in all and leave every // search in flight, and one that joins later (`in:team data` runs two), - // `limit` free discovery slots for its final answer, so a long read + // one response byte budget for its final answer, so a long read // cannot fill discovery or crowd out a better match on a later page. const answer = async (final: boolean, readSignal?: AbortSignal) => { // Saved names are candidates only: each match still resolves freshly. @@ -2179,13 +2195,10 @@ export function createChannelStore( .filter((id) => !resolved.has(id)) .slice( 0, - Math.max( - 0, - Math.min( - limit - resolved.size, - discovery.headroom() - publicSearchReserve - limit, - ), - ), + discovery.byteHeadroom() - publicSearchReserve >= + PUBLIC_CHANNEL_RESERVE_BYTES * 2 + ? Math.max(0, limit - resolved.size) + : 0, ); if (unresolved.length) { await resolve( @@ -2255,7 +2268,7 @@ export function createChannelStore( entry.events.length || entry.previous?.size ? Promise.resolve() : entry.page; - publicSearchReserve += limit; + publicSearchReserve += PUBLIC_CHANNEL_RESERVE_BYTES; try { for (;;) { const result = await Promise.race([ @@ -2315,7 +2328,7 @@ export function createChannelStore( } throw error; } finally { - publicSearchReserve -= limit; + publicSearchReserve -= PUBLIC_CHANNEL_RESERVE_BYTES; } } /** NIP-CL lookup: the channels `creator` made with `label`, oldest first. @@ -3205,7 +3218,8 @@ export function createChannelStore( ) { const hadHydration = hydration !== undefined; epoch++; - creationReads.clear(); + for (const [id, read] of creationReads) + if (!read.complete || !authorized(id)) creationReads.delete(id); revokedEpoch = epoch; hydration = undefined; revealHydration?.(); diff --git a/tests/browser/policy-relay.mjs b/tests/browser/policy-relay.mjs index 736c0428d8..52e679c277 100644 --- a/tests/browser/policy-relay.mjs +++ b/tests/browser/policy-relay.mjs @@ -656,7 +656,7 @@ export function policyRelay({ if ( filter.kinds.includes(9) && (!channel || - filter["#h"].length > 10 || + filter["#h"].length > 2048 || (filter.limit !== 0 && filter["#h"].length !== 1)) ) { queueMicrotask(() =>