Skip to content

feat(FIX-2428): WebSocket delivery: client.subscribe and useSubscription - #4597

Merged
jhoffner merged 9 commits into
mainfrom
fix/FIX-2428-subscribe
Nov 3, 2026
Merged

jhoffner merged 9 commits into
mainfrom
fix/FIX-2428-subscribe

Conversation

@jhoffner

@jhoffner jhoffner commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

A screen on the Node host that shows data other people change must read on a timer, or it goes stale. client.stream() exists, but the server answers it 501. Shift Manager and the labs poll every few seconds.

What this does. A screen calls one hook with its topics and the read it already makes. On the Node host, the read runs within about a second of a change, over one WebSocket per client. On a host with no push, the same hook reads on a timer. The server checks each topic with the read check of its scope, through the client's own fetcher, so a bearer token signs the socket in. A topic the caller may not read gets the same answer as a session that does not exist.

What changes. The client gains client.subscribe, which opens one socket per client and reads on a timer wherever push can miss a change, and useSubscription in react. The engine's user-stream route gains a POST that checks each topic and mints a ticket, and capabilities gains a push field. The Node host serves the socket on the user-stream route. Removed: client.stream and the 501 answer

The code follows the figure.

What is asked of you. Nothing. This implements the approved direction (D1 to D3 of the spec, and the amendments #4511, #4512 and #4513). The engineering calls are below the fold.

Parts worth reviewing closely (for the code reviewer):

  1. packages/client/src/subscribe/push-hub.ts, the timer rules. This is the state machine for when the timer runs: no push, a failed connect, before the first crosses: true frame, a refused topic. The goal check found one real defect here: Node's own WebSocket reports a failed handshake as an error with no close, so the first version stayed in "connecting" and never polled. The fix treats error as an end too, and adds a 10 s handshake timeout. This is my weakest spot: a browser can show a different event order that the fake socket in the tests does not show.
  2. packages/engine/src/push/push-delivery.ts, the mint (BP-031). Each session topic goes through authorizeManagementRoute as session_stream, on the mint's own request. User and org topics get their ids from the verified principal, never from the body. An anonymous caller in a mixed app gets no user or org topic. The user-route scoping table now probes the mint on its three axes.
  3. packages/node/src/serve.ts, the upgrade. It handles only <basePath>/users/:userId/stream. It leaves other paths to another upgrade listener (Vite's hot reload under fsdev dev) and refuses them only when it is the sole listener.

Fixes FIX-2428 · spec: specs/issues/FIX-2428/ (review #4443; amendments #4477, #4511, #4512, #4513) · epic FIX-2367 · bus FIX-2426 (#4594) · goal: pnpm tsx goals/realtime/websocket-delivery/run.mts, PASS (below)

How to review this

How to review this. This implements an approved spec — the approach and the numbered
decisions in its DECISIONS.md are already signed off by a human, so please review the
code against that direction, not the direction itself. The canonical set is retained
at specs/issues/<ISSUE-ID>/ on main; Linear links to it and the original merged spec
PR, which keeps review history. Follow-up amendment PRs explain later direction changes.
Current architecture docs remain the authority for shipped behavior (BP-037).

Most valuable here: correctness on the second path (the legacy shape, the null
boundary, the concurrent case, the cancel path), anything deriving an auth or routing
decision from caller-controllable input, and a behaviour the tests assert around
rather than on.

Already settled upstream: the approach and every decision in the spec's DECISIONS.md
(human-approved — if one is wrong, say so as a spec finding and it gets folded back; don't
re-argue it inline), and the conventions in docs/contributing/best-practices.md.

Engineering calls
  • onChange(null) on connect only for a subscription the connect covers. A subscription whose topics were all refused gets no connect call. That is what makes "C's handler never runs" true. If wrong: a screen with only refused topics does not do its first push read; its own first read and the timer still run.
  • The first crossing frame of a connection does not call onChange again. The connect already called it, so crosses: true right after the ticket is one read, not two. A later change of the answer calls it once. If wrong: one extra read per connect.
  • useSubscription gives a waiting read null when it stands for different notices. Coalescing keeps one read waiting; if that read stands for an items and a request notice, no single notice describes it, so it gets null (read everything). If wrong: a view that filters by kind reads a bit more often.
  • useSubscription does not read on mount. Each connect reads once, and a screen keeps its own first read. If wrong: a screen on a host with no push and no first read of its own shows nothing until the first tick.
  • Close codes. 4000 (age limit) reconnects at once; 4401, 4408 and 4400 count as a failed connect and back off (1 s doubling to 30 s), so a refused ticket on another process does not loop. The backoff resets only on the first crossing frame, which the server sends after it accepts the ticket, not on open.
  • A mint answer the client can't use means no push. No body, a page from a proxy, JSON with no ticket, or another transport: the client reads on its timer and never rejects. A failed call (network, non-2xx) is retried with backoff.
  • The mint rechecks the session after the guard with loadCheckedSession, as every session route does, so a session deleted and created again for someone else while the caller is signed in is dropped like a missing one.
  • One key per router. The router keeps its random default key once; every host that turns push on for it, and every socket, reads the router's current key. A plain drop reconnects at once, and the timer starts from the first failed reconnect. If wrong: a fast reconnect loop, or a stale screen for one backoff step.
  • A plain GET /users/:userId/stream answers 426. The socket is the host's upgrade, so the router never serves it. The scoping table pins it as upgradeOnly: 426, beside the mint's real entry. A POST on a host with no push answers 404.
  • resolveStores returns StoreRegistry & { bus }. It already returned withChangeBus(...); the type now says so, so the router hands its bus to the push state without a cast.
  • The mint caps one request at 100 topics, and serve() caps a socket frame at 64 KB.
  • createUserEventId stays exported (follow-up debt). It is a public export of @flow-state-dev/engine/streaming with no callers left; removing it is a breaking change the spec's debt list didn't name, so it waits for a follow-up.
  • The server acknowledges each ticket with a subscribed control frame once its topics are subscribed on the bus. The client reads on connect, and marks a topic covered, only on that acknowledgement, so a change between its read and the server's subscription is never missed. If wrong: a screen's connect read comes one round trip later.
  • createServerApp reports push only for the host that serves the socket (servesPush, set by serve()). Two hosts over one router each say what they serve. If wrong: none; a shared router can't leak push into a host that refuses its upgrades.
  • The lockfile. pnpm add ws also moved one transitive ws@8.19.0 to 8.21.3 (same major).
Everything else: verification, deviations, files

Goal check

flowchart LR
  A["Node serve · real WebSocket clients · polling off"] --> L1["leg a · a bus that crosses · tab 2 watches session S, tab 1 replies in S"]
  A --> L2["leg b · user C subscribes to S, then B is revoked and reconnects"]
  A --> L3["leg c · the same tab 2 code with no push, and on a second process on the in-memory bus"]
  L1 --> T["what each client's read returns"]
  L2 --> T
  L3 --> T
  T -->|"a within 1 s · b never hears · c within one poll"| P["PASS · goal met"]
  L1 -.->|"under no-socket"| F["must FAIL"]
  L2 -.->|"under skip-check"| F
  L3 -.->|"under ignore-crossing"| F
Loading

pnpm tsx goals/realtime/websocket-delivery/run.mts (model n/a):

PASS — a: 0 reads in 10 s idle, a reply in T included · a: replies shown 4, 3, 2 ms after saved · b: C's handler never ran; B read its reply 4 ms after saved · b: B heard nothing after revocation · c: no push, shown 1497 ms after saved · c: second process (crosses: false), shown 1431 ms after saved

Controls (each a scratch patch applied at load):

GOAL_CONTROL=no-socket        FAIL — a:no-read-between: tab 2 made 5 reads in 10 s · a:within-1s: 638, 1214, 1288 ms (bound 1000)
                              (also a:crossing, b:control, and CAN'T TELL on c:second-process frames: with no socket, nothing pushes)
GOAL_CONTROL=skip-check       FAIL — b:c-never-hears: C's handler ran 7 times for B's session (nothing else)
GOAL_CONTROL=ignore-crossing  FAIL — c:second-process: tab 2 never showed the reply from the first process (nothing else)

Today's main has no client.subscribe and answers the route 501, so no leg can run there; the controls stand in for its red state. No Not done if state holds: the read shows the change (a), a refused topic is not heard after a reconnect (b), the no-push hook reads again (c), the push host does not poll while the socket is up and crosses (a), a non-crossing socket keeps the timer (c), onChange gets the notice or null (client and react tests), and the guide says Vercel reads on its timer.

Tests, red then green

  • packages/engine/test/push-delivery.test.ts (25): red first on the missing module. Blast radius of the check: with the mint's refusal line removed, exactly the 3 refusal tests fail and the other 22 pass.
  • packages/engine/test/user-route-scoping.test.ts: the mint's entry. With the refusal removed, exactly the 3 foreign-row axes fail (another org, another tenant, anonymous in a mixed app).
  • packages/node/test/serve-push.test.ts (9): red first, 7 of 9 on push: null / 404 (the 2 that passed assert no push where there is none).
  • packages/client/test/subscribe.test.ts (21): red first on the missing export. With && crosses removed from covered, exactly the 2 crossing tests fail. The 2 handshake tests were added red after the goal check found the defect, then fixed.
  • packages/react/test/useSubscription.test.ts (9): red first on the missing hook.

Suites

  • engine pnpm test: 324 files, 4332 passed, 8 skipped
  • client 239 · react 503 · node 87 · contracts 97 · core 2613: all passed
  • pnpm packages:build and pnpm typecheck (root, every package): exit 0
  • node scripts/check-mechanism-anchors.mjs: 72 rows, every anchor exported

Deviations from the spec

  • The goal check drives client.subscribe with a one-in-flight read, not the React hook, because the goal runs in Node without a DOM. useSubscription is a coalesced read over client.subscribe, covered by its own tests.
  • Leg c's second process runs two serve() hosts over one PGlite Postgres in one Node process, each on its own in-memory bus, as FIX-2426's goal check does.
  • The docs prose was written in this session, not by the docs-writer and docs-editor agents: this worker could not dispatch sub-agents.
  • docs/architecture/authentication.md's user-route row also names list_interrupted_requests, which was already user-addressed.

Fix-up round (after 844a4f9)

  • CI (Test 3/3): an unhandled rejection in the client when the mint answered no body. Fixed; 4 new cases (no body, a non-JSON page, JSON with no ticket, null) failed first with the same TypeError, and the client suite now ends with no unhandled errors.
  • Codex r4450345464 (session recheck), r4450345470 (one key per router), r4450345475 (backoff reset): each reproduced by a test that failed first (Alice's mint granted Bob's replacement session; the first host's socket closed 4401; gaps [1000, 1000, 1000, 1000, 1000]), then fixed. The two-hosts node test fails again when the old key handling is put back.
  • Docs-editor round: the null list is one sentence everywhere; change bus, stores profile and crossing processes are introduced where first used; "within about a second" is gone, because no timer bounds it.

Second review round (after 7ac2f3f)

  • Codex r4453840539 (connect read before the server subscribes), r4453840560 (stale in-flight mint markers), r4453840568 (push: false host still advertised push): each reproduced by a test that failed first, then fixed.
  • Cursor: useSubscription keys topics with wireTopicKey; inbound socket frames are checked before fan-out; the session stream and subscribe share the 1 s to 30 s delay math (internal/backoff.ts) and keep their own success and stop rules.

Files

  • contracts: types/push-delivery.ts (new wire types); items/events.ts (user-stream types removed)
  • core: re-exports
  • engine: push/ticket.ts, push/socket-session.ts, push/push-delivery.ts (new); routes (user_stream_mint, capabilities push, 426)
  • node: serve.ts (upgrade, push, pushSecret); ws dependency
  • client: subscribe/push-hub.ts (new), client.ts (subscribe, stream removed), types
  • react: hooks/useSubscription.ts (new)
  • goal: goals/realtime/websocket-delivery/
  • docs: apps/docs/guides/realtime.md (new) and sidebar; client/overview.md, client/react.md, api/client.md, api/react.md, server/setup.md; client, react, node and engine READMEs; docs/architecture/authentication.md, server-and-client.md; docs/mechanisms/mechanisms.yaml (push-delivery)
  • .changeset/websocket-push.md (minor: client, react, node, engine, contracts, core)

Mechanism classifier: wireTopicKey (contracts, re-exported by core) belongs to the push-delivery row, as do the other new push exports.


Generated by Claude Code

…, the push mint

A screen on the Node host hears a change within a second over one WebSocket
per client, and reads on a timer wherever push can miss a change.

- engine: POST /users/:userId/stream mints a 30 s ticket after running each
  topic through its scope's read check on the real request (BP-031); a
  refused topic is absent, as a missing session is. The socket session
  accepts topics only from tickets, sends crossing frames, closes after an
  hour. capabilities reports push; GET answers 426 instead of 501.
- node: serve() takes the upgrade (ws), push and pushSecret options.
- client: client.subscribe with one shared socket, onChange(notice | null),
  pollIntervalMs fallback; client.stream() and the user-stream types removed.
- react: useSubscription over coalescedReads.
- contracts/core: push wire types; user-stream event types removed.
- goal: goals/realtime/websocket-delivery (PASS; three controls FAIL).
- docs: realtime guide, client/react/server pages, READMEs, mechanisms row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn
@vercel

vercel Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

4 Skipped Deployments
Project Deployment Actions Updated
flow-state-dev-docs Ignored Ignored Nov 3, 2026 12:01pm UTC
flow-state-dev-kitchen-sink Ignored Ignored Nov 3, 2026 12:01pm UTC
flow-state-dev-ui Ignored Ignored Preview Nov 3, 2026 12:01pm UTC
flow-state-dev-build-site Skipped Skipped Nov 3, 2026 12:01pm UTC

Request Review

@linear-code

linear-code Bot commented Nov 3, 2026

Copy link
Copy Markdown

FIX-2428

jhoffner commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

Where I'm least sure:

  1. Topic authorization (BP-031). Check that the mint and the socket decide which topics a caller may hear only from identity the server derives, never from the body, query or headers. Check also that a refused topic looks exactly like a hidden session, including after reconnects and when the ticket expires.
  2. Ticket and socket lifecycle (push/ticket.ts, socket-session.ts): replay of a ticket, the hourly close (code 4000), the backoff codes, and whether subscriptions are released when the socket drops without a clean close.
  3. The client's fallback timer (push-hub.ts): the timer has to stay on until a crossing frame says crosses: true, come back on when crossing turns false or the socket drops, and treat a handshake failure (an error with no close) as the end of the connection.

Generated by Claude Code

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Mechanism check (advisory, never blocks)

Rows from docs/mechanisms/mechanisms.yaml · labels: new-mechanism, mechanism-overlap

New export Package Mechanism
topic @flow-state-dev/client client
wireTopicKey @flow-state-dev/contracts none (nearest: contracts, item)
wireTopicKey @flow-state-dev/core none (nearest: block, sequencer-dsl, utility-block, flow, scope, resource, collection, resource-tools, capability, model, token-estimate, prompt, graph, manifest, suspension, wait-gate, dispatch, dispatcher, webhook, coding-harness, harness-steering)
enablePushDelivery @flow-state-dev/engine push-delivery
useSubscription @flow-state-dev/react react
  • Touches push-delivery and streaming, which the list marks as overlapping: streaming sends a request's or a session's items themselves; push delivery sends only that a topic changed, and the client reads.

If an export is a new mechanism, add a row. CI filled the mechanical fields; job, builtOn and overlaps are yours. If it belongs to an existing row, say which in the PR.

  - id: TODO
    job: TODO
    package: "@flow-state-dev/contracts"
    anchor: wireTopicKey
    file: packages/contracts/src/types/push-delivery.ts
    builtOn: []  # TODO
    overlaps: []  # TODO
    status: canonical
    doc: TODO
  - id: TODO
    job: TODO
    package: "@flow-state-dev/core"
    anchor: wireTopicKey
    file: packages/contracts/src/types/push-delivery.ts
    builtOn: []  # TODO
    overlaps: []  # TODO
    status: canonical
    doc: TODO

@github-actions github-actions Bot added mechanism-overlap Touches overlapping mechanisms, or a new name reads like an existing job (advisory) new-mechanism A new public export matches no row of docs/mechanisms/mechanisms.yaml (advisory) labels Nov 3, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T12:03:12.981083Z f3f48ed New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 844a4f9063

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +137 to +140
if (checked.session === undefined && (await loadTenantSession(ctx.stores.session, wire.id, ctx.tenantId)) === undefined) {
continue;
}
granted.push({ wire, bus: { scope: "session", id: wire.id, tenantId, ...resource } });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recheck the session record before granting its topic

If a session is deleted and recreated for another user while its asynchronous principal resolver runs, authorizeManagementRoute returns the old owner's checked record, but this branch grants the topic without comparing the current session. Reproducing that sequence allowed Alice's ticket to receive notices, including request IDs, from Bob's replacement session. Normal session routes prevent this race with loadCheckedSession; use that same comparison here and omit a changed record just like a missing session.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 7d98fce. Reproduced first: a test whose principal resolver deletes s1 and creates it again for bob while the session check signs alice in. Before the fix, alice's mint granted topic.session("s1"). The mint now runs loadCheckedSession(store, id, tenant, checked.session) after the guard, which is the comparison every session route uses. A changed record is dropped like a missing one, so the answer is the same as for a hidden session. Test: packages/engine/test/push-delivery.test.ts, "drops a session deleted and created again for another user while the caller is being signed in".

🤖 Generated with Claude Code


Generated by Claude Code

Comment on lines +82 to +87
const generated = given === undefined ? randomBytes(32).toString("base64url") : undefined;
const secret = (): string => (typeof given === "function" ? given() : given ?? generated!);
state.secret = secret;
return {
transport: "websocket",
openSocket: (userId, io) => openPushSocket({ bus: state.bus, secret, userId, io })

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve a consistent signing key across hosts sharing a router

When two serve() instances share one FlowState or router without an explicit pushSecret, the second call generates a new key and overwrites state.secret, which the mint reads. The first host's openSocket still captures its original key, so tickets minted through either host are subsequently refused by that host with 4401. This breaks push for a supported shared-runtime configuration. Reuse the router's existing default key, or make verification read the same current key as minting.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 7d98fce. The router's push state now makes its random default key once (state.generated ??=), so a second enablePushDelivery on the same router keeps it. Every socket checks tickets against the router's current key (state.secret()), which is the key the mint signs with, instead of a key captured when its host started. Tests: in the engine, two deliveries on one router both accept one mint's ticket; in node, two serve() hosts over one router with no pushSecret each accept tickets minted on either host. Both failed first with 4401, and the node test fails again when the old key handling is put back.

🤖 Generated with Claude Code


Generated by Claude Code

Comment on lines +309 to +312
opened = true;
state = "open";
lapsed = false;
failures = 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reset retry failures only after the ticket is accepted

When the WebSocket upgrade succeeds but the server repeatedly rejects the ticket with 4401—for example, when minting and socket hosts have different signing keys—every open resets failures before authentication completes. Consequently, scheduleRetry() always sees the first failure and retries every second indefinitely rather than backing off toward 30 seconds. Five consecutive refused connections reproduced delays of [1000, 1000, 1000, 1000, 1000]. Preserve the failure count until the server's first crossing frame confirms acceptance; the same problem affects repeated 4408 and 4400 closes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 7d98fce. failures now resets on the first crossing frame, which the server sends only after it accepts a ticket, not on open. A 4401, 4408 or 4400 close after open keeps backing off. Test: six sockets that open and then have their ticket refused. Before the fix the gaps were [1000, 1000, 1000, 1000, 1000]; now they are [1000, 2000, 4000, 8000, 16000] (packages/client/test/subscribe.test.ts).

🤖 Generated with Claude Code


Generated by Claude Code

…s pass

- client: a mint answer the client can't use (no body, a proxy page, no
  ticket, another transport) means no push: read on the timer, never reject.
  Fixes the unhandled rejection in CI (Test 3/3).
- engine: the mint rechecks the session with loadCheckedSession after the
  guard, so a session recreated for another user mid-sign-in is dropped
  (Codex r4450345464).
- engine: one default key per router; sockets read the router's current key,
  so two hosts on one router accept each other's tickets (Codex r4450345470).
- client: the backoff resets on the first crossing frame, not on open, so
  refused tickets back off 1, 2, 4, 8, 16 s (Codex r4450345475).
- docs: docs-editor round (one null list, change bus introduced, no "within
  a second" claim, listTasks_tasks), changeset migration note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn

jhoffner commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Kitchen-sink E2E (Playwright) failed at 7ac2f3f. The failures come from main, not this PR: the same three specs fail at the same lines on main, and the other 45 pass.

  • background-work.spec.ts:17
  • talk-from-page.spec.ts:403
  • workforce-shell.spec.ts:82

The cause is FIX-2506, a bad merge resolution in #4404. The fix is in #4596, which is green across the board, Kitchen-sink E2E included. I'm not copying it into this PR. Once #4596 merges, I'll merge main into this branch so CI re-runs.


Generated by Claude Code

@jhoffner
jhoffner marked this pull request as ready for review November 3, 2026 11:03

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Simplify / architecture review (FIX-2428)

Parallel read-only review of the diff (client hub, engine push, node ws, contracts, useSubscription, docs/tests).

Verdict: The split is the right product shape. Execution stays on session/request SSE; invalidation is mint + shared WebSocket + optional poll. User-SSE-only or poll-only would still need per-topic auth, dynamic subscribe/unsubscribe, and crossing honesty, so the problem size does not shrink much. Removing the never-enabled user SSE client path and scoping ws to node is clean.

Complexity concentrates in push-hub.ts (refcounts, mint generations, granted/refused, crossing, timers). Engine push and the React hook look proportionate. Generic reconnect libraries do not replace ticket remint, close codes, or topic refcounts.

Simplify follow-ups (not merge blockers):

  1. Shared 1s to 30s backoff with openSessionStream.
  2. Use wireTopicKey (or one helper) in useSubscription instead of JSON.stringify topicsKey.
  3. Mint: dedupe sessionId or parallelize auth/loadCheckedSession for many topics.
  4. Narrow runtime validation of inbound PushServerFrame before fan-out.
  5. Optional: extract PushConnection from hub if the module grows again.

Third-party: ws on host is appropriate; client stays native WebSocket. Ably types are fine as forward-looking serverless arm.

Performance: No merge blockers; mint sequential I/O and notice fan-out are scale notes only.

Approving; items above are good polish or follow-up PRs.

Open in Web View Automation 

Sent by Cursor Automation: Review For Best Approach

const HANDSHAKE_TIMEOUT_MS = 10_000;

/** Backoff between failed connects: 1 s, doubling, at most 30 s. */
const RETRY_BASE_MS = 1_000;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Simplify: Session SSE (openSessionStream) and push-hub both implement 1s base, 30s cap, exponential backoff. A shared helper in client would prevent drift.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 14122c5, but for the delay math only: internal/backoff.ts (backoffDelay, 1 s doubling to a 30 s cap) is now shared by openSessionStream and subscribe. Each keeps its own rules for success and for stopping. The session stream backs off on every drop and stops on 401/403/404/409/501. The hub reconnects immediately after a drop and resets its backoff on the first acknowledged ticket.

🤖 Generated with Claude Code


Generated by Claude Code

userId: string;
capabilities: () => Promise<FlowCapabilities>;
}): { subscribe(topics: readonly WireTopic[], options: SubscribeOptions): Subscription } {
const handles = new Set<Handle>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maintainability: many flags (mode, state, crosses, generation, granted, refused, minting) interact via guards across connect/ended/mintMore/updateTimers. If this grows, consider an explicit PushConnection state object; hub keeps refcounts and timer policy.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Deferred. Extracting a PushConnection would be a structural refactor of the code this round just changed in three places (acknowledgements, generation-scoped mints, per-host push). It is better done as its own change once the behaviour has settled under review, so that a reviewer can diff behaviour and structure separately.

🤖 Generated with Claude Code


Generated by Claude Code

if (socket !== ws) return;
let frame: PushServerFrame;
try {
frame = JSON.parse(String((event as MessageEvent).data)) as PushServerFrame;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

JSON.parse plus cast before dispatch. A narrow runtime guard on notice/topic shape before covers/call would fail closed like the server does for client frames.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 14122c5: readServerFrame checks each inbound frame before fan-out. It accepts only subscribed, crossing with a boolean crosses, and notice with a string kind and a well-formed wire topic, and drops anything else. Test: "drops a frame that isn't one the server sends", which failed first with a TypeError on a notice that had no topic.

🤖 Generated with Claude Code


Generated by Claude Code


const tenantId = ctx.tenantId ?? "";
const granted: GrantedTopic[] = [];
for (const wire of topics) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Mint loops session topics with sequential await (auth + loadCheckedSession). Deduping by sessionId helps when many wire topics share one session.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Deferred. A mint is one request per connect or per new topic, and a screen's topics rarely repeat a session (FIX-2429's boards use two topics on one session). Deduping or running the checks in parallel would save one guard read in that case. It would also add a second path through the security-relevant check, and I would rather keep that path single until a profile shows it costs something.

🤖 Generated with Claude Code


Generated by Claude Code

};

/** One key per distinct topic list, so an equal list keeps the subscription. */
function topicsKey(topics: readonly WireTopic[]): string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

topicsKey uses JSON.stringify; wire and hub use wireTopicKey. One canonical key helper reduces mismatch risk for memo and sameNotice.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 14122c5: useSubscription keys its topic list and compares notices with wireTopicKey, the same key the hub and the server use.

🤖 Generated with Claude Code


Generated by Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7ac2f3f33a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +368 to +370
// A change of the answer reads once, as a connect does. The first
// frame follows the connect's own read, so it adds none.
if (changed && !first) touched(new Set(granted));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Read again after the server accepts the subscription

When the connect-triggered read completes before the server processes the socket's subscribe frame, a write between those events is missed: the server has not installed its bus subscription yet, and this branch suppresses the read on the first acceptance frame. If that frame reports crosses: true, polling also stops, leaving the view stale until another change or reconnect. Reproducing this ordering produced only a read of the old value. Run the connect read after acceptance, or perform another read on the first crossing frame; additional topic subscriptions need equivalent ordering protection.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 14122c5. Each accepted ticket now gets a subscribed control frame from the server, sent only after the ticket's topics are subscribed on the bus. The client queues the topics of every ticket it sends, and on each acknowledgement it adds them to granted, which makes them covered, and only then calls onChange(null) once. So the connect read cannot run before the server hears the topic, and the timer keeps running until then. This applies both to the first ticket on a connect and to topics added to a live socket. The first crossing frame still adds no read, because it always follows the first acknowledgement.

Tests that failed first:

  • client: "reads on connect only once the server acknowledges the ticket, and keeps its timer until then" and "covers a topic added to a live socket only once the server acknowledges its ticket". Both had onChange called on open or on the mint answer.
  • engine: "acknowledges a ticket only after its topics are subscribed on the bus" checks the order bus:user, then subscribed, then crossing, then bus:org, then subscribed.

🤖 Generated with Claude Code


Generated by Claude Code

Comment on lines +210 to +212
const asking = keys.filter((key) => counts.has(key) && !granted.has(key) && !minting.has(key));
if (asking.length === 0) return;
for (const key of asking) minting.add(key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Scope in-flight topic mints to the connection generation

If all handles close while mintMore is pending, stop() leaves that topic in minting. Reopening the client with another topic and then subscribing to the pending topic makes this filter skip its new mint. When the old response arrives, it deletes the marker but returns because its generation is stale, without retrying the new subscription. Reproducing this sequence left the replacement socket subscribed only to the other topic; without polling, the skipped subscription receives nothing until reconnect. Reset or generation-scope the in-flight markers, ensuring stale completions cannot interfere with replacement mints.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 14122c5. minting is now a map from each topic to the connection generation that asked for it. A mint that completes deletes only its own markers, and stop() and a dropped socket clear the map. Test, failed first: "mints a topic again after a stop and reopen, though an older mint for it was still in flight". It holds an org mint, closes every handle, reopens with another topic, subscribes org again, and then releases the old mint. Before the fix, org was minted once and never subscribed on the new socket. Now it is minted twice, the new socket gets its ticket, and the subscription reads once.

🤖 Generated with Claude Code


Generated by Claude Code

Comment on lines +350 to +352
const delivery: Promise<PushDelivery | undefined> =
options.push === false
? Promise.resolve(undefined)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor push-disabled capabilities when reusing a router

When a router has already been served with push enabled, serving that same router with push: false disables only this host's socket delivery; the router's push state remains enabled. The disabled host therefore advertises WebSocket push and successfully mints tickets, but rejects every socket upgrade with 404. Clients repeatedly reconnect instead of taking the documented push: null fallback, and subscriptions without polling receive no changes. This also occurs when a push-enabled host closes without disposing the shared router and a push-disabled host subsequently reuses it. Make the host's advertised capabilities and mint behavior agree with its disabled socket delivery.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 14122c5. createServerApp takes servesPush, default false, and serve() sets it from its own push option. A host that does not serve the socket answers GET /capabilities with push: null and the mint with 404, even over a router that another host turned push on for. So what a host advertises and mints now matches its own socket delivery. Tests, failed first: two serve() hosts over one router, one with push and one with push: false, each report their own push, and the push-less host's mint is 404. Also, createServerApp alone over a router that another host serves push for reports push: null.

🤖 Generated with Claude Code


Generated by Claude Code

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Snob — already tight on 7ac2f3f33a5246780260461447709c5d351d0db7. No POC.

I read packages/client/src/subscribe/push-hub.ts, packages/react/src/hooks/useSubscription.ts, packages/engine/src/push/push-delivery.ts, packages/engine/src/push/socket-session.ts, packages/engine/src/push/ticket.ts, packages/node/src/serve.ts (servePush through socketUserId), packages/contracts/src/types/push-delivery.ts, the subscribe / push-delivery / serve-push / useSubscription tests, and goals/realtime/websocket-delivery/run.mts. I compared the hub's retry with openSessionStream in packages/client/src/stream-client/streams.ts.

A rewrite still has to keep the same branches:

  • The timer runs when pollIntervalMs is set and the handle is uncovered. Covered means the socket is open, crosses is true, and every key is granted. It stays off during the capabilities check and the handshake, and starts once a connect has failed. Backoff (1s, doubling, cap 30s) applies to a failed connect: ticket refused, ticket timeout, bad frame, or a handshake that errors with no close. It resets when the first crossing frame arrives. A drop, including the hour close, reconnects immediately. openSessionStream backs off on every drop and stops on 401, 403, 404, 409, and 501. Those two success rules stay either way.
  • useSubscription's topicsKey is the list form of wireTopicKey, used as the effect dependency and inside sameNotice. Calling wireTopicKey there removes the local field list. The hook, the coalesced read, and the null-on-mixed-notices rule stay.
  • The socket session keys subscriptions by the bus key (scope, tenant, id, resource) and stores the wire key for unsubscribe. The wire key is unique for one socket's granted topics, because the mint fills one tenant and the caller's own user or org id. Keying the map by the wire key deletes busKey. It also collapses two granted bus topics that share a wire form. That is a different match.
  • D1, D2, and D3 already settle the ticket, the hour cap, the timer, the crossing frame, the Ably arm of the mint union, one socket per client, and serve() only moving frames.

Two leftovers sit outside that contract. createUserEventId is still exported from @flow-state-dev/engine/streaming and has no caller now that the user-stream events are gone. packages/client/src/types/index.ts still has the comment "Handle returned by optional user-stream SSE connections." directly above RequestSSECallbacks. Deleting them does not shrink subscribe.

Open in Web View Automation 

Sent by Cursor Automation: Code Snob

…host

- engine/contracts: the socket acknowledges each accepted ticket with a
  `subscribed` control frame once its topics are on the bus. The client reads
  on connect, and covers a topic, only on that acknowledgement, so a change in
  the gap is never missed (Codex r4453840539).
- client: in-flight mint markers are scoped to the connection and cleared on
  stop and drop, so a stale mint can't skip a re-subscribed topic (Codex
  r4453840560).
- node: createServerApp reports push and answers the mint only for the host
  that serves the socket (`servesPush`, set by serve()), so a push:false host
  over a shared router reports push: null (Codex r4453840568).
- client: inbound frames are checked before fan-out; the session stream and
  subscribe share the 1 s to 30 s delay math. react: useSubscription keys
  topics with wireTopicKey. A stale user-stream comment is removed (Cursor).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 14122c50d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +318 to +322
const asked = allTopics();
updateTimers();
let answer: Awaited<ReturnType<typeof mint>>;
try {
answer = await mint(asked);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Batch topic mints within the server's limit

When one client watches more than 100 distinct topics, this connection path sends them all in one mint, but handleMintPush rejects more than MAX_MINT_TOPICS (100). Every retry submits the same oversized request, so push never connects; a previously working set of subscriptions also loses push on reconnect after growing beyond the limit. Reproducing 101 subscriptions produced consecutive mint sizes of [101, 101], both refused. Batch the initial and additional mints within the server's limit while retaining the shared socket.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 94d37c1. The limit now lives in one place, PUSH_MINT_MAX_TOPICS (100) in @flow-state-dev/contracts, which core re-exports. The engine's mint refuses anything longer using that constant. The client's connect ticket carries the first chunk, and once the socket is open mintMore mints the rest in chunks of that size over the same socket. Test (failed first, because the 205-topic mint was refused): "mints more topics than one mint takes in chunks, over the one socket". The fake server refuses more than the limit. The test checks one socket, three tickets, every topic minted, and the timer stopping.

🤖 Generated with Claude Code


Generated by Claude Code


function sameNotice(a: WireNotice | null, b: WireNotice | null): boolean {
if (a === null || b === null) return a === b;
return a.kind === b.kind && wireTopicKey(a.topic) === wireTopicKey(b.topic);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include request origins when comparing queued notices

When a read is pending and two subsequent notices share a topic and kind but have different origin.requestId values, this comparison treats them as identical. The follow-up read receives only the last request's notice instead of null, although it represents changes from both requests. Reproducing notices from r2 and r3 during an in-flight read delivered only r3; a callback that uses the exposed origin to refresh the affected request therefore leaves r2 stale. Compare origins too, so distinct queued notices trigger the documented full reread.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 94d37c1. sameNotice now also compares origin?.requestId, which is the only origin field WireNotice has. A waiting read for notices from different requests therefore gets null. Test (failed first): "gives a waiting read null when its notices came from different requests". It sends r1, r2 and r3, and the reads are now [r1, null].

🤖 Generated with Claude Code


Generated by Claude Code

read: (notice: WireNotice | null) => unknown,
options: UseSubscriptionOptions = {}
): void {
const client = useClient();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Share the push client across subscription hook instances

When multiple components call useSubscription under the same FlowProvider, each call obtains a separate client: useClient constructs createClient inside a per-hook useMemo, and the provider shares only configuration. Mounting two subscription hooks reproduced two WebSockets rather than multiplexed topics, with separate capability discovery, ticket mints and reconnect cycles. This defeats the documented provider-shared client behavior and makes connection overhead grow with every subscribed panel. Share the client or push hub across hooks using the same provider transport and identity.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 94d37c1. FlowProvider now owns a client cache, built through a useRef, so each provider has its own and there is no module-level cache. useClient returns the cached client for the same fetcher, userId, baseUrl and apiPath. Hooks under one provider therefore share one client and one socket. Outside any provider, a hook keeps its own client. I checked the other useClient callers: the client holds no per-hook state other than the push hub, and the whole react suite passes with sharing. Tests (the first failed first): "shares one client, and so one socket, across hooks under one provider" and "gives each provider its own clients".

🤖 Generated with Claude Code


Generated by Claude Code

…ovider

- react: useSubscription's waiting read gets null when its notices came from
  different requests: sameNotice compares origin.requestId (Codex 4454007227).
- client/engine/contracts: PUSH_MINT_MAX_TOPICS (100) lives in contracts; the
  engine refuses longer lists with it and the client mints in chunks of it
  over the one socket (Codex 4454007211).
- react: FlowProvider owns a client cache, so hooks with the same user and
  transport under one provider share one client and one push socket. Each
  provider has its own; no module-level cache (Codex 4454007237).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 94d37c121f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

updateTimers();
// Topics subscribed while this connect was in flight.
const asked2 = new Set(asked.map(wireTopicKey));
void mintMore([...counts.keys()].filter((key) => !asked2.has(key) && !refused.has(key)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retry refused overflow topics on reconnect

When a client watches more than 100 topics, a previously refused topic outside the first batch is never requested again on reconnect: refused survives socket teardown, the initial mint includes only the first 100 topics, and this filter excludes refused topics from the remaining batches. If access is subsequently granted or the missing session appears, subscriptions without polling still cannot receive its changes. Reproducing this with 101 topics produced mint sizes [100, 1, 100] across reconnect, leaving the previously refused last topic unrequested. Include those topics in reconnect batches or clear the previous connection's refusals.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in c1bdd49. Refusals belong to a connection now, and refused is cleared when the socket ends. That matches the first chunk, which already asks for every topic on a reconnect, so the topics after the first chunk follow the same rule. Test, which failed first: "asks again on a reconnect for a topic past the first chunk that the last connection refused". It refuses topic 101 once, drops the socket, and the reconnect's mints now include it.

🤖 Generated with Claude Code


Generated by Claude Code

Comment on lines +460 to +463
mode = "unknown";
lapsed = true;
clearTimeout(retryTimer);
retryTimer = setTimeout(() => void start(), BACKOFF_INITIAL_MS);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Ignore capability failures after all subscriptions close

If the last subscription closes while capability discovery is pending and that request subsequently rejects, this catch schedules another discovery despite there being no remaining handles. Continued failures then issue capability requests every second indefinitely after the component unmounts; stop() cannot cancel the retry because it is created after teardown. Reproducing this ordering confirmed another capabilities call after closing the only handle. Check the discovery generation or remaining handles before scheduling the retry.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in c1bdd49. start() now notes the connection generation before it reads capabilities. If stop() ran meanwhile, or no subscription is left, a failure arms no retry and a success connects nothing. Two new tests check this, ending with vi.getTimerCount() === 0. The first, "arms no retry when a capabilities read in flight fails after the last close", failed first with one timer left. The second, "arms no timer once the last subscription closes" (capabilities failing, and connects failing), passed before the fix: stop() already clears a retry that is pending, so it guards the pending case rather than reproducing this finding. Each socket also keeps its own handshake deadline now, and stop() clears the current one.

🤖 Generated with Claude Code


Generated by Claude Code

…sals per connection

- A capabilities read that fails or answers after the last subscription
  closed arms no retry and connects nothing (Codex 4454101939).
- `refused` is cleared with the connection, so a reconnect asks for every
  topic again, refused ones past the first chunk included, as the first
  chunk already does (Codex 4454101930).
- Each socket holds its own handshake deadline, and stop() clears the
  current one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: db23ca9b21

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +553 to +555
counts.delete(key);
refused.delete(key);
if (granted.delete(key)) gone.push(entry.topic);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Unsubscribe pending grants when their last handle closes

If a topic's last handle closes while its mint or ticket acknowledgement is pending, granted.delete(key) is false, so no unsubscribe is sent. The pending ticket can still subscribe the server to that topic, while acknowledged() simply skips its removed key. With another handle keeping the socket alive, the server subscription leaks until reconnect. Reproducing this with the engine's socket session left the closed topic subscribed; a subsequent handle whose mint refused that topic still received its notices through the leaked subscription. Track cancelled pending grants and unsubscribe their topics after acceptance, including when a ticket also contains topics that remain active.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in f3f48ed. The queue of pending tickets now holds every topic a ticket grants, not only the ones still wanted. When the server acknowledges a ticket, any of its topics that no subscription wants any more gets an unsubscribe, even when the same ticket also carries topics that are still active. For the mintMore chunks, a mint whose topics all lost their subscriptions while it was in flight now sends no ticket at all. As a guard for access, a notice also reaches a subscription only through a topic this socket was granted, so a subscription the mint refused never hears notices for that topic.

Tests, each failed first:

  • "unsubscribes a topic whose last subscription closed before its ticket was acknowledged": a ticket for org and user, the org handle closed and user still wanted. It now sends unsubscribe [org] and reads user once.
  • "sends no ticket for a mint whose topics all lost their subscriptions while it was in flight".
  • "passes a notice only to a subscription whose topic this socket was granted".

🤖 Generated with Claude Code


Generated by Claude Code

…oder-label test (FIX-2510)

FIX-2391 changed start() to take a readiness array and removed ACCOUNT;
FIX-2487 then added a test still using the old shape. Both merged, so
typecheck was red on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn
(cherry picked from commit 27c8abd)

jhoffner commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

The red Typecheck check comes from main, not from this PR. It fails at packages/shift-manager/test/harness-start.test.ts:176 (TS2304, ACCOUNT is not defined) because two shift-manager PRs collided on main. The fix is #4606 (FIX-2510), and I've copied it into this branch as c1acd914e so CI can go green here. Once #4606 merges, that commit becomes a no-op.


Generated by Claude Code

…r ticket was in flight

- The acknowledgement now accounts for every topic its ticket granted: one
  no subscription wants any more is unsubscribed, beside topics on the same
  ticket that are still wanted (Codex 4454225694).
- A mint whose topics all lost their subscriptions while it was in flight
  sends no ticket.
- A notice reaches a subscription only through a topic this socket was
  granted, so a refused subscription never hears another's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UNkLEJU1iqxFYoPadTRfn
@jhoffner
jhoffner added this pull request to the merge queue Nov 3, 2026
Merged via the queue into main with commit 9368ead Nov 3, 2026
20 checks passed
@jhoffner
jhoffner deleted the fix/FIX-2428-subscribe branch November 3, 2026 18:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Architect Approved mechanism-overlap Touches overlapping mechanisms, or a new name reads like an existing job (advisory) new-mechanism A new public export matches no row of docs/mechanisms/mechanisms.yaml (advisory)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants