Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
89 changes: 89 additions & 0 deletions apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5572,6 +5572,95 @@ it.effect.each([
}),
);

it.effect(
"ProviderSessionManagerV2 unloads each idle native thread a fresh session replaced in the same app thread",
() =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
const effect = Effect.gen(function* () {
const eventSink = yield* EventSink.EventSinkV2;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-fresh-rounds");
const providerSessionId = idAllocator.derive.providerSession({
providerInstanceId: modelSelection.instanceId,
});
yield* eventSink.write({
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
});
const runtime = yield* manager.open({
threadId,
providerSessionId,
modelSelection,
runtimePolicy,
});
// Each scheduled "fresh session" round opens a new native thread in the same app thread.
for (const round of [1, 2]) {
const runId = idAllocator.derive.run({ threadId, ordinal: round });
const providerThread = makeProviderThread({
idAllocator,
threadId,
providerSessionId,
now,
nativeThreadId: `native-round-${round}`,
});
yield* runtime.startTurn({
appThread: (yield* projectionStore.getThreadProjection(threadId)).thread,
threadId,
runId,
runOrdinal: round,
providerTurnOrdinal: 1,
attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }),
rootNodeId: idAllocator.derive.rootNode({ runId }),
providerThread,
message: {
createdBy: "user",
creationSource: "server",
messageId: yield* idAllocator.allocate.message({ threadId, ordinal: round }),
text: "Reply with OK.",
attachments: [],
},
modelSelection,
runtimePolicy,
});
const subscription = yield* runtime.subscribeEvents!;
yield* Queue.offer((yield* Ref.get(state)).eventQueues.get(String(providerSessionId))!, {
type: "turn.terminal",
driver: CODEX_DRIVER,
providerThreadId: providerThread.id,
providerTurnId: idAllocator.derive.providerTurn({
driver: CODEX_DRIVER,
nativeTurnId: `native-turn-${round}`,
}),
runOrdinal: round,
status: "completed",
failure: null,
threadDisposition: "reusable",
});
yield* subscription.events.pipe(Stream.runHead);
}

yield* TestClock.adjust("1 second");
assert.sameMembers(
[...(yield* Ref.get(state)).unloadedNativeThreadIds],
["native-round-1", "native-round-2"],
);
});

yield* effect.pipe(
Effect.provide(
layerTest({
state,
idleTimeoutMs: 1000,
// Keep the shared app-server open, as other conversations do.
hasPendingBackgroundWork: Effect.succeed(true),
}),
),
);
}),
);
it.effect(
"ProviderSessionManagerV2 re-attaching a thread waits for its in-flight unload, then reloads it",
() =>
Expand Down
136 changes: 88 additions & 48 deletions apps/server/src/orchestration-v2/ProviderSessionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,12 @@ interface LiveSessionEntry {
readonly busyTurns: ReadonlySet<string>;
readonly idleFiber: Fiber.Fiber<void, never> | null;
readonly pinnedSinceMs: number | null;
readonly idleThreadUnloads: ReadonlyMap<ThreadId, IdleThreadUnload>;
/** Keyed by native thread: a fresh session leaves the replaced one to unload on its own timer. */
readonly idleThreadUnloads: ReadonlyMap<ProviderThreadId, IdleThreadUnload>;
}

interface IdleThreadUnload {
readonly threadId: ThreadId;
readonly providerThread: OrchestrationV2ProviderThread;
readonly generation: number;
readonly fiber: Fiber.Fiber<void, never> | null;
Expand Down Expand Up @@ -417,6 +419,17 @@ function providerThreadRuntimeKey(
: `${nativeThreadRef.driver}:${nativeThreadRef.nativeId}`;
}

function isLoadKeyFor(
loadKey: string | undefined,
providerThread: Parameters<typeof providerThreadRuntimeKey>[0],
): boolean {
return (
loadKey === undefined ||
(JSON.parse(loadKey) as { providerThread: string }).providerThread ===
providerThreadRuntimeKey(providerThread)
);
}

function providerThreadLoadKey(input: {
readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
readonly providerThread: Parameters<
Expand Down Expand Up @@ -1636,7 +1649,7 @@ export const layerWithOptions = (
)) ||
// Closing now would skip the archive of a child whose parent has not taken its result.
Option.isSome(
yield* Effect.findFirst(entry.idleThreadUnloads.keys(), (threadId) =>
yield* Effect.findFirst(entry.idleThreadUnloads.values(), ({ threadId }) =>
delegatedChildArchive(threadId).pipe(
Effect.map((child) => child === "awaiting_delivery"),
),
Expand Down Expand Up @@ -1679,10 +1692,11 @@ export const layerWithOptions = (
// Closing skips the threads' own idle unloads, so archive delivered children first.
yield* Effect.forEach(
entry.idleThreadUnloads,
([threadId, pending]) =>
([providerThreadId, pending]) =>
unloadIdleThread({
providerSessionId: input.providerSessionId,
threadId,
threadId: pending.threadId,
providerThreadId,
generation: pending.generation,
archiveOnly: true,
}),
Expand Down Expand Up @@ -2049,18 +2063,18 @@ export const layerWithOptions = (

const updateIdleThreadUnload = (
providerSessionId: ProviderSessionId,
threadId: ThreadId,
providerThreadId: ProviderThreadId,
update: (current: IdleThreadUnload | undefined) => IdleThreadUnload | undefined,
) =>
Ref.modify(sessions, (current) => {
const key = sessionKey(providerSessionId);
const entry = current.get(key);
if (entry === undefined) return [undefined, current] as const;
const previous = entry.idleThreadUnloads.get(threadId);
const previous = entry.idleThreadUnloads.get(providerThreadId);
const next = update(previous);
const idleThreadUnloads = new Map(entry.idleThreadUnloads);
if (next === undefined) idleThreadUnloads.delete(threadId);
else idleThreadUnloads.set(threadId, next);
if (next === undefined) idleThreadUnloads.delete(providerThreadId);
else idleThreadUnloads.set(providerThreadId, next);
const updated = new Map(current);
updated.set(key, { ...entry, idleThreadUnloads });
return [previous, updated] as const;
Expand Down Expand Up @@ -2088,8 +2102,9 @@ export const layerWithOptions = (
}
const previous = yield* updateIdleThreadUnload(
input.providerSessionId,
input.threadId,
input.providerThread.id,
(current) => ({
threadId: input.threadId,
providerThread: input.providerThread,
generation: (current?.generation ?? 0) + 1,
fiber: null,
Expand All @@ -2103,20 +2118,27 @@ export const layerWithOptions = (
function* (providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId) {
const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId));
if (entry === undefined || hasBusyTurn(entry, providerThreadId)) return;
const tracked = Array.from(entry.idleThreadUnloads).find(
([, pending]) => pending.providerThread.id === providerThreadId,
);
if (tracked === undefined) return;
const [threadId, pending] = tracked;
const pending = entry.idleThreadUnloads.get(providerThreadId);
if (pending === undefined) return;
const generation = pending.generation + 1;
const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe(
Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })),
Effect.andThen(
unloadIdleThread({
providerSessionId,
threadId: pending.threadId,
providerThreadId,
generation,
}),
),
Effect.forkIn(layerScope),
);
const previous = yield* updateIdleThreadUnload(providerSessionId, threadId, (current) =>
current?.generation === pending.generation
? { ...current, generation, fiber }
: current,
const previous = yield* updateIdleThreadUnload(
providerSessionId,
providerThreadId,
(current) =>
current?.generation === pending.generation
? { ...current, generation, fiber }
: current,
);
yield* cancelIdleFiber(
previous?.generation === pending.generation ? previous.fiber : fiber,
Expand Down Expand Up @@ -2159,6 +2181,7 @@ export const layerWithOptions = (
function* (input: {
readonly providerSessionId: ProviderSessionId;
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly generation: number;
/** Session release unloads only the threads it would archive, and never waits. */
readonly archiveOnly?: boolean;
Expand All @@ -2168,7 +2191,7 @@ export const layerWithOptions = (
Effect.gen(function* () {
const key = sessionKey(input.providerSessionId);
const entry = (yield* Ref.get(sessions)).get(key);
const pending = entry?.idleThreadUnloads.get(input.threadId);
const pending = entry?.idleThreadUnloads.get(input.providerThreadId);
const unloadThread = entry?.exposedRuntime.unloadThread;
if (
entry === undefined ||
Expand All @@ -2193,29 +2216,39 @@ export const layerWithOptions = (
if (child === "awaiting_delivery") return "deferred" as const;
const archive = child === "ready";
if (input.archiveOnly === true && !archive) return "skipped" as const;
const unloading = yield* Ref.modify(sessions, (current) => {
const latest = current.get(key);
if (
latest?.runtime !== entry.runtime ||
latest.idleThreadUnloads.get(input.threadId)?.generation !== input.generation
) {
return [false, current] as const;
}
const loadedProviderThreadKeyByThread = new Map(
latest.loadedProviderThreadKeyByThread,
);
loadedProviderThreadKeyByThread.delete(input.threadId);
const idleThreadUnloads = new Map(latest.idleThreadUnloads);
idleThreadUnloads.delete(input.threadId);
const updated = new Map(current);
updated.set(key, {
...latest,
loadedProviderThreadKeyByThread,
idleThreadUnloads,
});
return [true, updated] as const;
});
if (!unloading) return "skipped" as const;
// null when skipped, otherwise whether this native thread is the app thread's loaded one.
const unloadsLoadedThread = yield* Ref.modify(
sessions,
(current): readonly [boolean | null, Map<string, LiveSessionEntry>] => {
const latest = current.get(key);
if (
latest?.runtime !== entry.runtime ||
latest.idleThreadUnloads.get(input.providerThreadId)?.generation !==
input.generation
) {
return [null, current];
}
const idleThreadUnloads = new Map(latest.idleThreadUnloads);
idleThreadUnloads.delete(input.providerThreadId);
// A native thread a fresh session replaced is not what the app thread has loaded.
const isCurrent = isLoadKeyFor(
latest.loadedProviderThreadKeyByThread.get(input.threadId),
pending.providerThread,
);
const loadedProviderThreadKeyByThread = new Map(
latest.loadedProviderThreadKeyByThread,
);
if (isCurrent) loadedProviderThreadKeyByThread.delete(input.threadId);
const updated = new Map(current);
updated.set(key, {
...latest,
loadedProviderThreadKeyByThread,
idleThreadUnloads,
});
return [isCurrent, updated];
},
);
if (unloadsLoadedThread === null) return "skipped" as const;
const unload = (archiveThread: boolean) =>
unloadThread({
providerThread: pending.providerThread,
Expand All @@ -2236,7 +2269,7 @@ export const layerWithOptions = (
Effect.tap(() =>
Ref.update(sessions, (current) => {
const latest = current.get(key);
if (latest?.runtime !== entry.runtime) return current;
if (latest?.runtime !== entry.runtime || !unloadsLoadedThread) return current;
const linkedEnvironmentsByThread = new Map(latest.linkedEnvironmentsByThread);
linkedEnvironmentsByThread.delete(input.threadId);
return new Map(current).set(key, { ...latest, linkedEnvironmentsByThread });
Expand Down Expand Up @@ -3502,7 +3535,7 @@ export const layerWithOptions = (
return [
Option.none<{
readonly entry: LiveSessionEntry;
readonly idleUnloadFiber: Fiber.Fiber<void, never> | null;
readonly idleUnloadFibers: ReadonlyArray<Fiber.Fiber<void, never>>;
}>(),
current,
] as const;
Expand All @@ -3524,7 +3557,12 @@ export const layerWithOptions = (
})()
: entry.mcpCredentialIdByThread;
const idleThreadUnloads = new Map(entry.idleThreadUnloads);
idleThreadUnloads.delete(input.threadId);
const idleUnloadFibers: Array<Fiber.Fiber<void, never>> = [];
for (const [providerThreadId, pending] of entry.idleThreadUnloads) {
if (pending.threadId !== input.threadId) continue;
idleThreadUnloads.delete(providerThreadId);
if (pending.fiber !== null) idleUnloadFibers.push(pending.fiber);
}
const updatedEntry = {
...entry,
attachedThreadIds,
Expand All @@ -3538,13 +3576,15 @@ export const layerWithOptions = (
return [
Option.some({
entry: updatedEntry,
idleUnloadFiber: entry.idleThreadUnloads.get(input.threadId)?.fiber ?? null,
idleUnloadFibers,
}),
updated,
] as const;
});
if (Option.isSome(detachResult)) {
yield* cancelIdleFiber(detachResult.value.idleUnloadFiber);
yield* Effect.forEach(detachResult.value.idleUnloadFibers, cancelIdleFiber, {
discard: true,
});
}
const detached = Option.map(detachResult, (result) => result.entry);
// Plain detaches preserve credentials held by live shared providers across workspace handoffs.
Expand Down
Loading