Skip to content

Commit 613308d

Browse files
fix(client-runtime): reconnect retries follow the session, not the supervisor counter
The supervisor's generation starts over when the registry installs a new supervisor (re-pairing, route edits), so a first session at an old generation fired nothing. Count established sessions by their object instead. The ordering test now starts from a held failure and refreshes, as callers do. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 95b839a commit 613308d

3 files changed

Lines changed: 110 additions & 57 deletions

File tree

‎packages/client-runtime/src/state/connections.test.ts‎

Lines changed: 71 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -28,62 +28,94 @@ const connectionState = (
2828
...overrides,
2929
});
3030

31+
const makeCatalogHarness = Effect.fn("TestCatalog.makeHarness")(function* () {
32+
const state = yield* SubscriptionRef.make(
33+
connectionState({ phase: "connected", attempt: 1, generation: 1 }),
34+
);
35+
const session = yield* SubscriptionRef.make(Option.some({} as RpcSession.RpcSession));
36+
const supervisor = {
37+
state,
38+
session,
39+
} as unknown as EnvironmentSupervisor.EnvironmentSupervisor["Service"];
40+
const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
41+
_environmentId,
42+
stream,
43+
) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
44+
const registry = EnvironmentRegistry.EnvironmentRegistry.of({
45+
followStream,
46+
} as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
47+
const catalog = createEnvironmentCatalogAtoms(
48+
Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry)),
49+
);
50+
const atom = catalog.sessionGenerationAtom(ENVIRONMENT_ID);
51+
const atoms = AtomRegistry.make();
52+
const unmount = atoms.mount(atom);
53+
yield* Effect.addFinalizer(() =>
54+
Effect.sync(() => {
55+
unmount();
56+
atoms.dispose();
57+
}),
58+
);
59+
yield* Effect.yieldNow;
60+
/** Moves the supervisor to `next`, with a new session object when one is established. */
61+
const generationAfter = (
62+
next: SupervisorConnectionState,
63+
nextSession: Option.Option<RpcSession.RpcSession> = Option.none(),
64+
) =>
65+
SubscriptionRef.set(session, nextSession).pipe(
66+
Effect.andThen(SubscriptionRef.set(state, next)),
67+
Effect.andThen(Effect.yieldNow),
68+
Effect.map(() => atoms.get(atom)),
69+
);
70+
return { generation: () => atoms.get(atom), generationAfter };
71+
});
72+
73+
const lastFailure = new ConnectionTransientError({ reason: "transport", detail: "Down." });
74+
const newSession = () => Option.some({} as RpcSession.RpcSession);
75+
3176
describe("environment catalog atoms", () => {
3277
it.effect("changes the session generation only when a new session comes up", () =>
3378
Effect.scoped(
3479
Effect.gen(function* () {
35-
const state = yield* SubscriptionRef.make(
36-
connectionState({ phase: "connected", attempt: 1, generation: 1 }),
37-
);
38-
const session = yield* SubscriptionRef.make(Option.some({} as RpcSession.RpcSession));
39-
const supervisor = {
40-
state,
41-
session,
42-
} as unknown as EnvironmentSupervisor.EnvironmentSupervisor["Service"];
43-
const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
44-
_environmentId,
45-
stream,
46-
) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
47-
const registry = EnvironmentRegistry.EnvironmentRegistry.of({
48-
followStream,
49-
} as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
50-
const catalog = createEnvironmentCatalogAtoms(
51-
Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry)),
52-
);
53-
const atom = catalog.sessionGenerationAtom(ENVIRONMENT_ID);
54-
const atoms = AtomRegistry.make();
55-
const unmount = atoms.mount(atom);
56-
yield* Effect.addFinalizer(() =>
57-
Effect.sync(() => {
58-
unmount();
59-
atoms.dispose();
60-
}),
61-
);
62-
const lastFailure = new ConnectionTransientError({ reason: "transport", detail: "Down." });
63-
const generationAfter = (next: SupervisorConnectionState) =>
64-
SubscriptionRef.set(state, next).pipe(
65-
Effect.andThen(Effect.yieldNow),
66-
Effect.map(() => atoms.get(atom)),
67-
);
68-
69-
yield* Effect.yieldNow;
70-
expect(atoms.get(atom)).toBe(1);
80+
const { generation, generationAfter } = yield* makeCatalogHarness();
81+
const first = generation();
7182
// A retry reports the generation it is attempting before it is established.
7283
expect(
7384
yield* generationAfter(
7485
connectionState({ phase: "connecting", stage: "opening", generation: 2, lastFailure }),
7586
),
76-
).toBe(1);
87+
).toBe(first);
7788
expect(
7889
yield* generationAfter(
7990
connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
8091
),
81-
).toBe(1);
92+
).toBe(first);
8293
expect(
8394
yield* generationAfter(
8495
connectionState({ phase: "connected", attempt: 2, generation: 2 }),
96+
newSession(),
97+
),
98+
).not.toBe(first);
99+
}),
100+
),
101+
);
102+
103+
it.effect("changes when a replaced supervisor's first session reuses an old generation", () =>
104+
Effect.scoped(
105+
Effect.gen(function* () {
106+
const { generation, generationAfter } = yield* makeCatalogHarness();
107+
const first = generation();
108+
yield* generationAfter(
109+
connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
110+
);
111+
// Re-pairing or editing a route installs a new supervisor, whose counter starts over.
112+
yield* generationAfter(connectionState({ phase: "available", generation: 0 }));
113+
expect(
114+
yield* generationAfter(
115+
connectionState({ phase: "connected", attempt: 1, generation: 1 }),
116+
newSession(),
85117
),
86-
).toBe(2);
118+
).not.toBe(first);
87119
}),
88120
),
89121
);

‎packages/client-runtime/src/state/runtime.test.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -743,7 +743,7 @@ describe("environment query lifecycle", () => {
743743
),
744744
);
745745

746-
it.effect("a read started on a new session generation sees that session", () =>
746+
it.effect("a refresh started on a new session generation answers from that session", () =>
747747
Effect.scoped(
748748
Effect.gen(function* () {
749749
const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
@@ -754,27 +754,37 @@ describe("environment query lifecycle", () => {
754754
retryAt: 1,
755755
}),
756756
});
757-
const registry = AtomRegistry.make();
757+
const registry = yield* mountEnvironmentQuery(harness.atom);
758+
// Callers hold the failure a read got while the environment was retrying.
759+
const failed = yield* Effect.promise(() =>
760+
executeAtomQuery(registry, harness.atom, { reportFailure: false }),
761+
);
762+
expect(AsyncResult.isFailure(failed)).toBe(true);
763+
758764
const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
759765
const sessionGeneration = environmentSessionGenerationAtom(
760766
harness.runtime,
761767
QUERY_ENVIRONMENT.environmentId,
762768
);
763769
const unmount = registry.mount(sessionGeneration);
764-
const unsubscribe = registry.subscribe(sessionGeneration, (generation) => {
765-
void executeAtomQuery(registry, harness.atom, { reportFailure: false }).then((result) => {
766-
if (generation === 2) Deferred.doneUnsafe(answered, Effect.succeed(result));
767-
});
770+
const unsubscribe = registry.subscribe(sessionGeneration, () => {
771+
void executeAtomQuery(registry, harness.atom, {
772+
refresh: true,
773+
reportFailure: false,
774+
}).then((result) => Deferred.doneUnsafe(answered, Effect.succeed(result)));
768775
});
769776
yield* Effect.addFinalizer(() =>
770777
Effect.sync(() => {
771778
unsubscribe();
772779
unmount();
773-
registry.dispose();
774780
}),
775781
);
776782
yield* Effect.yieldNow;
777783

784+
yield* SubscriptionRef.set(
785+
harness.supervisorSession,
786+
Option.some({} as RpcSession.RpcSession),
787+
);
778788
yield* SubscriptionRef.set(
779789
harness.supervisorState,
780790
queryConnectionState({ generation: 2 }),

‎packages/client-runtime/src/state/runtime.ts‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -610,9 +610,9 @@ const sessionGenerationAtomsByRuntime = new WeakMap<
610610
>();
611611

612612
/**
613-
* The generation of the environment's latest established session, kept while it reconnects.
614-
* It changes only when a new session comes up, so a one-shot read that failed while the
615-
* environment was unreachable can watch it to run again once it is back.
613+
* Counts established sessions; it changes only when a new one comes up, so failed one-shot reads
614+
* can watch it to run again. Keyed on the session object because the supervisor's `generation`
615+
* restarts when the registry installs a new supervisor (re-pairing, route edits).
616616
*/
617617
export function environmentSessionGenerationAtom<R, ER>(
618618
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
@@ -621,15 +621,26 @@ export function environmentSessionGenerationAtom<R, ER>(
621621
let family = sessionGenerationAtomsByRuntime.get(runtime);
622622
if (family === undefined) {
623623
const connectionAtom = environmentConnectionAtoms(runtime);
624+
const sessionsSeen = Atom.family((id: EnvironmentIdType) =>
625+
Atom.make(
626+
(get): { readonly session: RpcSession.RpcSession | null; readonly count: number } => {
627+
const previous = Option.getOrElse(
628+
get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(),
629+
() => ({ session: null, count: 0 }),
630+
);
631+
const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id))));
632+
if (connection === null || connection[0].phase !== "connected") return previous;
633+
const session = Option.getOrNull(connection[1]);
634+
return session === null || session === previous.session
635+
? previous
636+
: { session, count: previous.count + 1 };
637+
},
638+
),
639+
);
624640
family = Atom.family((id: EnvironmentIdType) =>
625-
Atom.make((get): number => {
626-
const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id))));
627-
return connection !== null &&
628-
connection[0].phase === "connected" &&
629-
Option.isSome(connection[1])
630-
? connection[0].generation
631-
: Option.getOrElse(get.self<number>(), () => 0);
632-
}).pipe(Atom.withLabel(`environment-session-generation:${id}`)),
641+
Atom.make((get) => get(sessionsSeen(id)).count).pipe(
642+
Atom.withLabel(`environment-session-generation:${id}`),
643+
),
633644
);
634645
sessionGenerationAtomsByRuntime.set(runtime, family);
635646
}

0 commit comments

Comments
 (0)