Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(FIX-2428): push hub teardown: no retry after the last close, refu…
…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
  • Loading branch information
claude committed Nov 3, 2026
commit c1bdd49076dec90af703f7aa3ec59cd50ce16930
25 changes: 21 additions & 4 deletions packages/client/src/subscribe/push-hub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ export function createPushHub(deps: {
let lapsed = false;
let failures = 0;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
/** The current socket's handshake deadline, cleared on open, end and stop. */
let handshakeTimer: ReturnType<typeof setTimeout> | undefined;
/** Bumped on each connect and teardown, so a stale answer is ignored. */
let generation = 0;

Expand Down Expand Up @@ -365,12 +367,15 @@ export function createPushHub(deps: {
* once, whichever comes first.
*/
const ended = (code: number | undefined): void => {
clearTimeout(handshakeTimer);
clearTimeout(deadline);
if (socket !== ws) return;
socket = undefined;
state = "idle";
crosses = false;
// Everything this connection learnt goes with it: the next connect asks
// for every topic again, refused ones included, as its first chunk does.
granted.clear();
refused.clear();
minting.clear();
unacknowledged = [];
generation += 1;
Expand All @@ -388,11 +393,14 @@ export function createPushHub(deps: {
// fails, the timer runs from then.
void connect();
};
// A handshake that never answers is a failed connect too.
const handshakeTimer = setTimeout(() => ended(undefined), HANDSHAKE_TIMEOUT_MS);
// A handshake that never answers is a failed connect too. Each socket
// holds its own deadline, so an older socket ending late never clears a
// newer one's; `stop()` clears the current one.
const deadline = setTimeout(() => ended(undefined), HANDSHAKE_TIMEOUT_MS);
handshakeTimer = deadline;
ws.addEventListener("open", () => {
if (socket !== ws) return;
clearTimeout(handshakeTimer);
clearTimeout(deadline);
opened = true;
state = "open";
lapsed = false;
Expand Down Expand Up @@ -452,10 +460,13 @@ export function createPushHub(deps: {
return;
}
mode = "checking";
const at = generation;
let push: FlowCapabilities["push"];
try {
push = (await deps.capabilities()).push;
} catch {
// Torn down meanwhile (the last subscription closed): nothing to retry for.
if (at !== generation || handles.size === 0) return;
// Unknown: try again later, reading on the timer meanwhile.
mode = "unknown";
lapsed = true;
Expand All @@ -464,6 +475,11 @@ export function createPushHub(deps: {
updateTimers();
return;
}
if (at !== generation || handles.size === 0) {
// Torn down meanwhile; keep what was learnt, start nothing.
mode = push == null ? "none" : "push";
return;
}
// An older server sends no `push`: the same as none (BP-030).
if (push == null) {
noPush();
Expand All @@ -476,6 +492,7 @@ export function createPushHub(deps: {
const stop = (): void => {
generation += 1;
clearTimeout(retryTimer);
clearTimeout(handshakeTimer);
const ws = socket;
socket = undefined;
state = "idle";
Expand Down
65 changes: 63 additions & 2 deletions packages/client/test/subscribe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* reconnect, a change of the crossing answer, or a poll.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PUSH_MINT_MAX_TOPICS } from "@flow-state-dev/contracts";
import { PUSH_MINT_MAX_TOPICS, wireTopicKey as wireKey } from "@flow-state-dev/contracts";
import { createClient, topic, type ClientFetch, type WireNotice, type WireTopic } from "../src";

/** A WebSocket double the test drives: open, deliver a frame, drop. */
Expand Down Expand Up @@ -75,14 +75,19 @@ function server(
mintBody?: string;
/** Hold a mint's answer until the promise this returns settles. */
holdMint?: (topics: WireTopic[]) => Promise<void> | undefined;
/** Fail `GET /capabilities` while this returns true. */
capabilitiesFail?: () => boolean;
} = {}
) {
const mints: MintCall[] = [];
const capabilityCalls = { count: 0 };
let ticket = 0;
const fetcher: ClientFetch = async (input, init) => {
const url = String(input);
const headers = new Headers(init?.headers);
if (url.endsWith("/capabilities")) {
capabilityCalls.count += 1;
if (options.capabilitiesFail?.() === true) return Response.json({ error: "down" }, { status: 503 });
const body = options.push === undefined ? { userStream: false } : { userStream: false, push: options.push };
return Response.json(body);
}
Expand All @@ -105,7 +110,7 @@ function server(
};
const wrapped: ClientFetch = (input, init) =>
fetcher(input, { ...init, headers: { ...(init?.headers as Record<string, string>), authorization: "Bearer secret" } });
return { fetcher: wrapped, mints };
return { fetcher: wrapped, mints, capabilityCalls };
}

function client(fetcher: ClientFetch) {
Expand Down Expand Up @@ -434,6 +439,62 @@ describe("client.subscribe on a host with push", () => {
expect(onChange).not.toHaveBeenCalled();
});

it("asks again on a reconnect for a topic past the first chunk that the last connection refused", async () => {
let allow = false;
const late = topic.session(`s${PUSH_MINT_MAX_TOPICS + 1}`);
const { fetcher, mints } = server({
push: { transport: "websocket" },
grant: (t) => allow || wireKey(t) !== wireKey(late)
});
const many = Array.from({ length: PUSH_MINT_MAX_TOPICS + 2 }, (_, i) => topic.session(`s${i}`));
const { socket } = await connected(client(fetcher), many, undefined, true);
await settle();
const before = mints.length;
allow = true;
socket.drop();
await settle();
FakeSocket.all.at(-1)!.open();
await settle();
const asked = mints.slice(before).flatMap((call) => call.topics.map(wireKey));
expect(asked).toContain(wireKey(late));
});

for (const [name, setup] of [
["the capabilities read keeps failing", { capabilitiesFail: () => true }],
["each connect fails", { mintStatus: () => 503 }]
] as const) {
it(`arms no timer once the last subscription closes, when ${name}`, async () => {
const { fetcher, capabilityCalls, mints } = server({ push: { transport: "websocket" }, ...setup });
const sub = client(fetcher).subscribe([S1], { onChange: () => {}, pollIntervalMs: 1000 });
await vi.advanceTimersByTimeAsync(3500);
sub.close();
await settle();
const probes = capabilityCalls.count + mints.length;
await vi.advanceTimersByTimeAsync(60_000);
expect(capabilityCalls.count + mints.length).toBe(probes);
expect(vi.getTimerCount()).toBe(0);
});
}

it("arms no retry when a capabilities read in flight fails after the last close", async () => {
let fail = false;
let release: (() => void) | undefined;
const held: ClientFetch = async (input, init) => {
if (String(input).endsWith("/capabilities")) {
await new Promise<void>((resolve) => (release = resolve));
if (fail) return Response.json({ error: "down" }, { status: 503 });
}
return server({ push: { transport: "websocket" } }).fetcher(input, init);
};
const sub = client(held).subscribe([S1], { onChange: () => {}, pollIntervalMs: 1000 });
await settle();
sub.close();
fail = true;
release!();
await settle();
expect(vi.getTimerCount()).toBe(0);
});

it("drops a frame that isn't one the server sends", async () => {
const { fetcher } = server({ push: { transport: "websocket" } });
const { onChange, socket } = await connected(client(fetcher), [S1], undefined, true);
Expand Down
Loading