Skip to content

Commit 2e92c03

Browse files
committed
fix(client-runtime): drop shell items buffered from a superseded session
1 parent 13330c5 commit 2e92c03

2 files changed

Lines changed: 162 additions & 5 deletions

File tree

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

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,138 @@ describe("environment shell synchronization", () => {
11221122
expect(filled).toEqual([link(2)]);
11231123
}),
11241124
);
1125+
it.effect("drops a superseded session's snapshot applied after the next session subscribes", () =>
1126+
Effect.gen(function* () {
1127+
const NEXT_VERSION = "2.0.0";
1128+
const oldEvents = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
1129+
const newEvents = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
1130+
const supersededPulled = yield* Deferred.make<void>();
1131+
const markerPulled = yield* Deferred.make<void>();
1132+
const nextSubscribed = yield* Deferred.make<void>();
1133+
const applyBlocked = yield* Deferred.make<void>();
1134+
const releaseApply = yield* Deferred.make<void>();
1135+
const saved = yield* Queue.unbounded<{
1136+
readonly snapshot: OrchestrationV2ShellSnapshot;
1137+
readonly vouch: Persistence.ShellCacheVouch | undefined;
1138+
}>();
1139+
const supersededRow = { ...v2ThreadShell, id: ThreadId.make("superseded-row") };
1140+
1141+
const oldClient = {
1142+
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
1143+
Stream.fromQueue(oldEvents).pipe(
1144+
Stream.tap((item) =>
1145+
item.kind === "snapshot" && item.snapshot.snapshotSequence === 2
1146+
? Deferred.succeed(supersededPulled, undefined)
1147+
: (item.kind as string) === "future.event"
1148+
? Deferred.succeed(markerPulled, undefined)
1149+
: Effect.void,
1150+
),
1151+
),
1152+
} as unknown as WsRpcProtocolClient;
1153+
const newClient = {
1154+
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
1155+
Stream.unwrap(
1156+
Deferred.succeed(nextSubscribed, undefined).pipe(
1157+
Effect.as(Stream.fromQueue(newEvents)),
1158+
),
1159+
),
1160+
} as unknown as WsRpcProtocolClient;
1161+
const sessionFor = (
1162+
client: WsRpcProtocolClient,
1163+
serverVersion: string,
1164+
): RpcSession.RpcSession => ({
1165+
...session(client),
1166+
initialConfig: Effect.succeed({
1167+
shellResumeCompletionMarker: true,
1168+
environment: { serverVersion },
1169+
} as never),
1170+
});
1171+
const activeSession = yield* SubscriptionRef.make(
1172+
Option.some(sessionFor(oldClient, SERVER_VERSION)),
1173+
);
1174+
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
1175+
target: TARGET,
1176+
state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
1177+
session: activeSession,
1178+
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
1179+
connect: Effect.void,
1180+
disconnect: Effect.void,
1181+
retryNow: Effect.void,
1182+
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
1183+
const cache = Persistence.EnvironmentCacheStore.of({
1184+
loadShell: () => Effect.succeedNone,
1185+
saveShell: (_id, snapshot, vouch) =>
1186+
Queue.offer(saved, { snapshot, vouch }).pipe(Effect.asVoid),
1187+
loadThread: () => Effect.succeedNone,
1188+
saveThread: () => Effect.void,
1189+
removeThread: () => Effect.void,
1190+
loadServerConfig: () => Effect.succeedNone,
1191+
saveServerConfig: () => Effect.void,
1192+
loadVcsRefs: () => Effect.succeedNone,
1193+
saveVcsRefs: () => Effect.void,
1194+
removeVcsRefs: () => Effect.void,
1195+
clearVcsRefs: () => Effect.void,
1196+
clear: () => Effect.void,
1197+
});
1198+
// Stamping the first vouch parks the consumer mid-apply, so the next item stays buffered
1199+
// in the switchMap behind it while the session changes.
1200+
const realClock = yield* Clock.clockWith(Effect.succeed);
1201+
const gatedClock: Clock.Clock = {
1202+
currentTimeMillisUnsafe: () => realClock.currentTimeMillisUnsafe(),
1203+
currentTimeNanosUnsafe: () => realClock.currentTimeNanosUnsafe(),
1204+
currentTimeNanos: realClock.currentTimeNanos,
1205+
monotonicTimeNanosUnsafe: () => realClock.monotonicTimeNanosUnsafe(),
1206+
monotonicTimeNanos: realClock.monotonicTimeNanos,
1207+
sleep: (duration) => realClock.sleep(duration),
1208+
currentTimeMillis: Deferred.succeed(applyBlocked, undefined).pipe(
1209+
Effect.flatMap((first) => (first ? Deferred.await(releaseApply) : Effect.void)),
1210+
Effect.andThen(realClock.currentTimeMillis),
1211+
),
1212+
};
1213+
const shellState = yield* makeEnvironmentShellState().pipe(
1214+
Effect.provideService(Clock.Clock, gatedClock),
1215+
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
1216+
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
1217+
Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, {
1218+
load: () => Effect.succeedNone,
1219+
}),
1220+
);
1221+
1222+
yield* Queue.offer(oldEvents, { kind: "snapshot", snapshot: LIVE_SHELL_SNAPSHOT });
1223+
yield* Deferred.await(applyBlocked);
1224+
yield* Queue.offer(oldEvents, {
1225+
kind: "snapshot",
1226+
snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 2, threads: [supersededRow] },
1227+
});
1228+
yield* Deferred.await(supersededPulled);
1229+
// The upstream pulls again only after it has buffered the snapshot above.
1230+
yield* Queue.offer(oldEvents, { kind: "future.event", sequence: 99 } as never);
1231+
yield* Deferred.await(markerPulled);
1232+
yield* SubscriptionRef.set(activeSession, Option.some(sessionFor(newClient, NEXT_VERSION)));
1233+
yield* Deferred.await(nextSubscribed);
1234+
yield* Deferred.succeed(releaseApply, undefined);
1235+
yield* Queue.offer(newEvents, {
1236+
kind: "thread.updated",
1237+
sequence: 3,
1238+
location: "active",
1239+
thread: { ...v2ThreadShell, title: "From the new session" },
1240+
});
1241+
const settled = yield* SubscriptionRef.changes(shellState).pipe(
1242+
Stream.filter(
1243+
(state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 3,
1244+
),
1245+
Stream.runHead,
1246+
Effect.map(Option.getOrThrow),
1247+
);
1248+
expect(Option.getOrThrow(settled.snapshot).threads.map((thread) => thread.id)).not.toContain(
1249+
supersededRow.id,
1250+
);
1251+
1252+
yield* TestClock.adjust("500 millis");
1253+
const persisted = yield* Queue.take(saved);
1254+
expect(persisted.vouch?.serverVersion).toBe(SERVER_VERSION);
1255+
}),
1256+
);
11251257
});
11261258

11271259
describe("environment shell cold start from a vouched cache", () => {

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

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ import * as ConnectionWakeups from "../connection/wakeups.ts";
2727
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
2828
import * as Persistence from "../platform/persistence.ts";
2929
import { runCachePersistence } from "./cachePersistence.ts";
30-
import { subscribeDynamic } from "../rpc/client.ts";
30+
import { subscribeDynamicWithSession } from "../rpc/client.ts";
31+
import type { RpcSession } from "../rpc/session.ts";
3132
import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
3233
import type { DeferredShellSnapshot } from "./shellPullRequests.ts";
3334
import {
@@ -141,6 +142,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
141142
// shell last came from, or that a cache resume has completed for; null otherwise.
142143
const authoritativeOmission = yield* Ref.make<string | null>(null);
143144
const activeSubscription = yield* Ref.make<{
145+
readonly session: RpcSession;
144146
readonly omissionKey: string;
145147
readonly serverVersion: string | null;
146148
} | null>(null);
@@ -255,7 +257,13 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
255257
const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
256258
items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
257259
pendingLinkIds?: ReadonlySet<ThreadId>,
260+
producer?: RpcSession,
258261
) {
262+
// Read once under the lock: a resubscribe can rewrite it while this batch applies.
263+
const subscription = yield* Ref.get(activeSubscription);
264+
// A batch buffered across a session change must not take the new session's vouch; the new
265+
// subscription resumes or reloads on its own.
266+
if (producer !== undefined && subscription?.session !== producer) return;
259267
const initial = yield* SubscriptionRef.get(state);
260268
let waiting = yield* Ref.get(awaitingCompletion);
261269
let next = initial;
@@ -336,7 +344,6 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
336344
const previousVouch = yield* Ref.get(lineageVouch);
337345
let vouch = previousVouch;
338346
if (receivedAuthoritativeSnapshot) {
339-
const subscription = yield* Ref.get(activeSubscription);
340347
vouch =
341348
subscription?.serverVersion == null
342349
? undefined
@@ -444,7 +451,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
444451

445452
yield* setSynchronizing;
446453
yield* Effect.forkScoped(
447-
subscribeDynamic(
454+
subscribeDynamicWithSession(
448455
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
449456
Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
450457
const { omitIdleSubagents, omitOlderSettled, serverVersion } =
@@ -462,7 +469,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
462469
})),
463470
);
464471
const omissionKey = `${omitIdleSubagents}:${omitOlderSettled}`;
465-
yield* Ref.set(activeSubscription, { omissionKey, serverVersion });
472+
yield* Ref.set(activeSubscription, { session, omissionKey, serverVersion });
466473
yield* Ref.set(pendingCacheResume, null);
467474
yield* Ref.set(awaitingCompletion, true);
468475
yield* setSynchronizing;
@@ -549,7 +556,25 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
549556
retryExpectedFailureAfter: "250 millis",
550557
resubscribe: foregroundResubscriptions,
551558
},
552-
).pipe(Stream.runForEachArray((items) => applyItems(items))),
559+
).pipe(
560+
// A buffered chunk can span a session change, so apply each session's run separately.
561+
Stream.runForEachArray(
562+
Effect.fnUntraced(function* (entries) {
563+
let start = 0;
564+
while (start < entries.length) {
565+
const producer = entries[start]![0];
566+
let end = start + 1;
567+
while (end < entries.length && entries[end]![0] === producer) end++;
568+
yield* applyItems(
569+
entries.slice(start, end).map(([, item]) => item),
570+
undefined,
571+
producer,
572+
);
573+
start = end;
574+
}
575+
}),
576+
),
577+
),
553578
);
554579
yield* SubscriptionRef.changes(supervisor.state).pipe(
555580
Stream.runForEach((connectionState) => {

0 commit comments

Comments
 (0)