Skip to content

Commit 3dd37be

Browse files
committed
fix(client-runtime): bind shell writes to their source session
1 parent d7c232f commit 3dd37be

2 files changed

Lines changed: 94 additions & 19 deletions

File tree

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

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -132,14 +132,17 @@ const FAMILY_SNAPSHOT: OrchestrationV2ShellSnapshot = {
132132
const makeFamilyHarness = Effect.fn("test.makeFamilyHarness")(function* (input: {
133133
readonly cached: Option.Option<DeferredShellSnapshot>;
134134
readonly initialVersion: string;
135+
readonly snapshot?: DeferredShellSnapshot;
135136
}) {
136137
const subscribeInputs = yield* Queue.unbounded<unknown>();
137138
const saved = yield* Queue.unbounded<{ readonly verifiedServerVersion?: string }>();
138139
const httpLoads = yield* Ref.make(0);
139-
const familySession = (serverVersion: string): RpcSession.RpcSession => {
140-
const events = Stream.make<ReadonlyArray<OrchestrationV2ShellStreamItem>>({
140+
const familySession = (
141+
serverVersion: string,
142+
events = Stream.make<ReadonlyArray<OrchestrationV2ShellStreamItem>>({
141143
kind: "synchronized",
142-
}).pipe(Stream.concat(Stream.never));
144+
}).pipe(Stream.concat(Stream.never)),
145+
): RpcSession.RpcSession => {
143146
const client = {
144147
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (subscribeInput: unknown) =>
145148
Stream.unwrap(Queue.offer(subscribeInputs, subscribeInput).pipe(Effect.as(events))),
@@ -181,7 +184,9 @@ const makeFamilyHarness = Effect.fn("test.makeFamilyHarness")(function* (input:
181184
});
182185
const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
183186
load: () =>
184-
Ref.update(httpLoads, (count) => count + 1).pipe(Effect.as(Option.some(FAMILY_SNAPSHOT))),
187+
Ref.update(httpLoads, (count) => count + 1).pipe(
188+
Effect.as(Option.some(input.snapshot ?? FAMILY_SNAPSHOT)),
189+
),
185190
});
186191
const shellState = yield* makeEnvironmentShellState().pipe(
187192
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
@@ -194,7 +199,7 @@ const makeFamilyHarness = Effect.fn("test.makeFamilyHarness")(function* (input:
194199
Stream.runHead,
195200
Effect.map(Option.getOrThrow),
196201
);
197-
return { sessions, familySession, subscribeInputs, saved, httpLoads, stateWhere };
202+
return { sessions, familySession, subscribeInputs, saved, httpLoads, stateWhere, shellState };
198203
});
199204

200205
describe("environment shell synchronization", () => {
@@ -823,6 +828,61 @@ describe("environment shell synchronization", () => {
823828
}),
824829
);
825830

831+
it.effect(
832+
"does not verify a replacement session with a buffered snapshot from its predecessor",
833+
() =>
834+
Effect.gen(function* () {
835+
const links =
836+
yield* Deferred.make<ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>>();
837+
const h = yield* makeFamilyHarness({
838+
cached: Option.none(),
839+
initialVersion: "1.0.0",
840+
snapshot: { ...FAMILY_SNAPSHOT, loadPullRequests: Deferred.await(links) },
841+
});
842+
yield* Queue.take(h.subscribeInputs);
843+
yield* h.stateWhere((state) => state.status === "live");
844+
const configStarted = yield* Deferred.make<void>();
845+
const configGate = yield* Deferred.make<void>();
846+
const replacement = h.familySession("2.0.0");
847+
const next = {
848+
...replacement,
849+
initialConfig: Deferred.succeed(configStarted, undefined).pipe(
850+
Effect.andThen(Deferred.await(configGate)),
851+
Effect.andThen(replacement.initialConfig),
852+
),
853+
};
854+
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
855+
const old = h.familySession("1.0.0", Stream.fromQueue(events));
856+
yield* SubscriptionRef.set(h.sessions, Option.some(old));
857+
yield* Queue.take(h.subscribeInputs);
858+
const held = yield* Deferred.make<void>();
859+
const release = yield* Deferred.make<void>();
860+
const writer = yield* Effect.forkChild(
861+
h.shellState.semaphore.withPermit(
862+
Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))),
863+
),
864+
);
865+
yield* Deferred.await(held);
866+
yield* Deferred.succeed(links, new Map());
867+
yield* TestClock.adjust("1 millis");
868+
yield* Queue.offer(events, {
869+
kind: "snapshot",
870+
snapshot: { ...FAMILY_SNAPSHOT, snapshotSequence: 99 },
871+
});
872+
yield* TestClock.adjust("1 millis");
873+
yield* SubscriptionRef.set(h.sessions, Option.some(next));
874+
yield* Deferred.await(configStarted);
875+
yield* Deferred.succeed(release, undefined);
876+
yield* Fiber.join(writer);
877+
yield* h.stateWhere((state) =>
878+
Option.exists(state.snapshot, (snapshot) => snapshot.snapshotSequence === 99),
879+
);
880+
yield* Deferred.succeed(configGate, undefined);
881+
expect(yield* Queue.take(h.subscribeInputs)).toMatchObject({ afterSequence: 1 });
882+
expect(yield* Ref.get(h.httpLoads)).toBe(2);
883+
}),
884+
);
885+
826886
it.effect("resumes the cached snapshot on a cold start of the build that verified it", () =>
827887
Effect.gen(function* () {
828888
const cached = { ...FAMILY_SNAPSHOT, verifiedServerVersion: "1.0.0" };

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

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
type ThreadId,
99
type ThreadPullRequestLink,
1010
} from "@t3tools/contracts";
11+
import * as Array from "effect/Array";
1112
import * as Cause from "effect/Cause";
1213
import * as Effect from "effect/Effect";
1314
import * as Fiber from "effect/Fiber";
@@ -26,7 +27,7 @@ import * as ConnectionWakeups from "../connection/wakeups.ts";
2627
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
2728
import * as Persistence from "../platform/persistence.ts";
2829
import { runCachePersistence } from "./cachePersistence.ts";
29-
import { subscribeDynamic } from "../rpc/client.ts";
30+
import { subscribeDynamicWithSession } from "../rpc/client.ts";
3031
import type { RpcSession } from "../rpc/session.ts";
3132
import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
3233
import type { DeferredShellSnapshot } from "./shellPullRequests.ts";
@@ -227,9 +228,11 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
227228
const snapshotWriteLock = yield* Semaphore.make(1);
228229

229230
const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
231+
session: RpcSession,
230232
items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
231233
pendingLinkIds?: ReadonlySet<ThreadId>,
232234
) {
235+
if ((yield* Ref.get(activeSubscriptionSession)) !== session) return;
233236
const initial = yield* SubscriptionRef.get(state);
234237
let waiting = yield* Ref.get(awaitingCompletion);
235238
let verifyingResume = yield* Ref.get(awaitingResumeVerification);
@@ -303,11 +306,8 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
303306
);
304307
}
305308
if (receivedSnapshot || verifiedResume) {
306-
const session = yield* Ref.get(activeSubscriptionSession);
307-
if (session !== null) {
308-
yield* Ref.set(lastAuthoritativeSession, session);
309-
yield* Ref.set(verifiedServerVersion, yield* Ref.get(activeServerVersion));
310-
}
309+
yield* Ref.set(lastAuthoritativeSession, session);
310+
yield* Ref.set(verifiedServerVersion, yield* Ref.get(activeServerVersion));
311311
}
312312
if (Option.isSome(next.snapshot)) {
313313
yield* Ref.set(latestLiveSnapshot, next.snapshot);
@@ -395,10 +395,9 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
395395

396396
yield* setSynchronizing;
397397
yield* Effect.forkScoped(
398-
subscribeDynamic(
398+
subscribeDynamicWithSession(
399399
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
400400
Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
401-
yield* Ref.set(activeSubscriptionSession, session);
402401
const config = yield* session.initialConfig.pipe(Effect.option);
403402
const omitIdleSubagents = Option.exists(
404403
config,
@@ -410,10 +409,15 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
410409
onNone: () => null,
411410
onSome: (value) => value.environment?.serverVersion ?? null,
412411
});
413-
yield* Ref.set(activeServerVersion, serverVersion);
414-
yield* Ref.set(awaitingCompletion, true);
415-
yield* Ref.set(awaitingResumeVerification, false);
416-
yield* setSynchronizing;
412+
yield* snapshotWriteLock.withPermit(
413+
Effect.gen(function* () {
414+
yield* Ref.set(activeSubscriptionSession, session);
415+
yield* Ref.set(activeServerVersion, serverVersion);
416+
yield* Ref.set(awaitingCompletion, true);
417+
yield* Ref.set(awaitingResumeVerification, false);
418+
yield* setSynchronizing;
419+
}),
420+
);
417421

418422
// Foreground resubscriptions on the same live session resume from the in-memory
419423
// cursor. A new session may too when an earlier session of the same server build
@@ -461,7 +465,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
461465
? []
462466
: httpSnapshot.value.threads.map((thread) => thread.id),
463467
);
464-
yield* applyItems([{ kind: "snapshot", snapshot }], pendingLinkIds);
468+
yield* applyItems(session, [{ kind: "snapshot", snapshot }], pendingLinkIds);
465469
canResume = true;
466470
current = yield* SubscriptionRef.get(state);
467471
if (Option.isSome(current.snapshot)) {
@@ -488,7 +492,18 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
488492
retryExpectedFailureAfter: "250 millis",
489493
resubscribe: foregroundResubscriptions,
490494
},
491-
).pipe(Stream.runForEachArray((items) => applyItems(items))),
495+
).pipe(
496+
Stream.runForEachArray((items) =>
497+
Effect.forEach(
498+
Array.groupWith(items, ([left], [right]) => left === right),
499+
(group) =>
500+
applyItems(
501+
group[0][0],
502+
group.map(([, item]) => item),
503+
),
504+
),
505+
),
506+
),
492507
);
493508
yield* SubscriptionRef.changes(supervisor.state).pipe(
494509
Stream.runForEach((connectionState) => {

0 commit comments

Comments
 (0)