GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): resend every stopped request a closed session was carrying · pingdotgg/t3code@f1c76cc

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/orchestration-v2
    • ProviderTurnStartService.ts
    • testkit
      • ProviderSwitch.integration.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/orchestration-v2/ProviderTurnStartService.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+74-58Lines changed: 74 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -154,46 +154,46 @@ export function abandonedProviderTurns(
154154
const CUT_TURN_SETTLED = "cut-turn-settled";
155155

156156
/**
157-
* The previous run's cancelled or stopped turn when no adapter said whether it kept the request.
158-
* A restart cancels the turn with no adapter left to tell. A Stop leaves its request with the
159-
* session, which is gone once the session closes.
157+
* The latest cancelled or stopped turn when no adapter said whether it kept the request. A restart
158+
* cancels the turn with no adapter left to tell. A Stop leaves its request with the session, which
159+
* carries it into the next turn and is gone once the session closes. Later runs whose request the
160+
* provider never got are passed over: a stopped request they carried was lost with them.
160161
*/
161162
function unsettledCutProviderTurn(
162163
projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
163164
run: Pick<OrchestrationV2Run, "ordinal">,
164165
providerThread: Pick<OrchestrationV2ProviderThread, "id" | "nativeThreadRef">,
165166
) {
166-
const previous = projection.runs.reduce<OrchestrationV2Run | undefined>(
167-
(latest, candidate) =>
168-
candidate.ordinal < run.ordinal &&
169-
candidate.providerThreadId === providerThread.id &&
170-
candidate.startedAt !== null &&
171-
(latest === undefined || candidate.ordinal > latest.ordinal)
172-
? candidate
173-
: latest,
174-
undefined,
175-
);
176-
if (
177-
(previous?.status !== "cancelled" && previous?.status !== "interrupted") ||
178-
previous.activeAttemptId === null
179-
)
180-
return undefined;
181-
const turn = projection.providerTurns.findLast(
182-
(candidate) =>
183-
candidate.runAttemptId === previous.activeAttemptId &&
184-
candidate.providerThreadId === providerThread.id,
185-
);
186-
const nativeTurnId = turn?.nativeTurnRef?.nativeId;
187-
if (
188-
turn === undefined ||
189-
nativeTurnId == null ||
190-
(turn.status !== "cancelled" && turn.status !== "interrupted") ||
191-
turn.promptDropped === true ||
192-
(turn.nativeThreadRef !== undefined &&
193-
turn.nativeThreadRef.nativeId !== providerThread.nativeThreadRef?.nativeId)
194-
)
195-
return undefined;
196-
return { run: previous, turn, nativeTurnId };
167+
const previousRuns = projection.runs
168+
.filter(
169+
(candidate) =>
170+
candidate.ordinal < run.ordinal &&
171+
candidate.providerThreadId === providerThread.id &&
172+
candidate.startedAt !== null,
173+
)
174+
.toSorted((left, right) => right.ordinal - left.ordinal);
175+
for (const previous of previousRuns) {
176+
const turn =
177+
previous.activeAttemptId === null
178+
? undefined
179+
: projection.providerTurns.findLast(
180+
(candidate) =>
181+
candidate.runAttemptId === previous.activeAttemptId &&
182+
candidate.providerThreadId === providerThread.id,
183+
);
184+
if (turn === undefined || !isDeliveredProviderTurn(turn)) continue;
185+
const nativeTurnId = turn.nativeTurnRef?.nativeId;
186+
if (
187+
(previous.status !== "cancelled" && previous.status !== "interrupted") ||
188+
nativeTurnId == null ||
189+
(turn.status !== "cancelled" && turn.status !== "interrupted") ||
190+
(turn.nativeThreadRef !== undefined &&
191+
turn.nativeThreadRef.nativeId !== providerThread.nativeThreadRef?.nativeId)
192+
)
193+
return undefined;
194+
return { run: previous, turn, nativeTurnId };
195+
}
196+
return undefined;
197197
}
198198

199199
export const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
@@ -1109,61 +1109,77 @@ export const layer: Layer.Layer<
11091109
const session = sessionResult.success;
11101110
if (!(yield* isCurrentAttemptInStatus("starting"))) return;
11111111
const cutTurn = unsettledCutProviderTurn(projection, run, providerThread);
1112-
if (
1113-
cutTurn !== undefined &&
1112+
// A cut turn the provider did not keep may itself have carried an earlier stopped request,
1113+
// which is lost with it, so keep asking back to a turn the provider kept.
1114+
const droppedCutTurns: Array<NonNullable<typeof cutTurn>> = [];
1115+
for (
1116+
let candidate = cutTurn;
1117+
candidate !== undefined &&
11141118
session.nativeTurnKept !== undefined &&
11151119
!(yield* (
11161120
session
1117-
.nativeTurnKept({ providerThread, nativeTurnId: cutTurn.nativeTurnId })
1121+
.nativeTurnKept({ providerThread, nativeTurnId: candidate.nativeTurnId })
11181122
// As when the turn ends: an unknown answer resends the request rather than losing it.
11191123
.pipe(Effect.orElseSucceed(() => false))
1120-
))
1124+
));
1125+
candidate = unsettledCutProviderTurn(projection, candidate.run, providerThread)
11211126
) {
1122-
// Settle it as a failed turn is settled: mark the request dropped and take back its inline
1123-
// context, so this turn resends both. Starting again reads the settled state.
1127+
droppedCutTurns.push(candidate);
1128+
}
1129+
const earliestCutTurn = droppedCutTurns.at(-1);
1130+
if (earliestCutTurn !== undefined) {
1131+
// Settle them as a failed turn is settled: mark each request dropped and take back their
1132+
// inline context, so this turn resends all of it. Starting again reads the settled state.
11241133
const occurredAt = yield* DateTime.now;
11251134
const allocateEventId = () =>
11261135
idAllocator.allocate.event({ threadId: projection.thread.id });
11271136
// Its attempt starts before it delivers anything, so later inline deliveries are its own,
11281137
// including handoffs carried from an earlier run that they still target.
11291138
const cutStartedAt =
1130-
projection.attempts.find((candidate) => candidate.id === cutTurn.run.activeAttemptId)
1131-
?.startedAt ?? cutTurn.run.startedAt;
1139+
projection.attempts.find(
1140+
(candidate) => candidate.id === earliestCutTurn.run.activeAttemptId,
1141+
)?.startedAt ?? earliestCutTurn.run.startedAt;
11321142
const settled = yield* eventSink.writeIfRunCurrent({
11331143
threadId: projection.thread.id,
11341144
runId: run.id,
11351145
activeAttemptId: attempt.id,
11361146
expectedStatus: "starting",
11371147
events: [
1138-
{
1139-
id: yield* allocateEventId(),
1140-
type: "provider-turn.updated" as const,
1141-
threadId: projection.thread.id,
1142-
runId: cutTurn.run.id,
1143-
nodeId: cutTurn.turn.nodeId,
1144-
providerInstanceId: cutTurn.run.providerInstanceId,
1145-
occurredAt,
1146-
payload: { ...cutTurn.turn, promptDropped: true as const },
1147-
},
1148+
...(yield* Effect.forEach(droppedCutTurns, (dropped) =>
1149+
Effect.map(allocateEventId(), (id) => ({
1150+
id,
1151+
type: "provider-turn.updated" as const,
1152+
threadId: projection.thread.id,
1153+
runId: dropped.run.id,
1154+
nodeId: dropped.turn.nodeId,
1155+
providerInstanceId: dropped.run.providerInstanceId,
1156+
occurredAt,
1157+
payload: { ...dropped.turn, promptDropped: true as const },
1158+
})),
1159+
)),
11481160
...(yield* Effect.forEach(
11491161
projection.contextHandoffs.filter(
11501162
(handoff) =>
11511163
handoff.delivery?.status === "inline" &&
11521164
handoff.delivery.nativeThreadId === providerThread.nativeThreadRef?.nativeId &&
1153-
(handoff.targetRunId === cutTurn.run.id ||
1165+
(droppedCutTurns.some((dropped) => handoff.targetRunId === dropped.run.id) ||
11541166
(cutStartedAt !== null &&
11551167
DateTime.isGreaterThanOrEqualTo(handoff.updatedAt, cutStartedAt))),
11561168
),
1157-
({ delivery: _delivery, ...handoff }) =>
1158-
Effect.map(allocateEventId(), (id) => ({
1169+
({ delivery: _delivery, ...handoff }) => {
1170+
const owner =
1171+
droppedCutTurns.find((dropped) => handoff.targetRunId === dropped.run.id) ??
1172+
earliestCutTurn;
1173+
return Effect.map(allocateEventId(), (id) => ({
11591174
id,
11601175
type: "context-handoff.updated" as const,
11611176
threadId: projection.thread.id,
1162-
runId: cutTurn.run.id,
1163-
providerInstanceId: cutTurn.run.providerInstanceId,
1177+
runId: owner.run.id,
1178+
providerInstanceId: owner.run.providerInstanceId,
11641179
occurredAt,
11651180
payload: { ...handoff, updatedAt: occurredAt },
1166-
})),
1181+
}));
1182+
},
11671183
)),
11681184
],
11691185
});
Collapse file

‎apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+103Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6847,4 +6847,107 @@ describe("orchestration v2 provider switching", () => {
68476847
);
68486848
}),
68496849
);
6850+
6851+
it.effect("resends every stopped request that a closed session was carrying", () =>
6852+
Effect.gen(function* () {
6853+
const cwd = yield* checkpointWorkspace("stopped-twice-session-closed");
6854+
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
6855+
// The session that saw run 2's Stop carries its request into run 3. Once the session
6856+
// closes, neither stopped request is in the provider's history.
6857+
let sessionOpen = true;
6858+
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
6859+
makeTestAdapter({
6860+
instanceId: CODEX_MODEL_SELECTION.instanceId,
6861+
driver: CODEX_DRIVER,
6862+
capabilities: CodexProviderCapabilitiesV2,
6863+
modelSelection: CODEX_MODEL_SELECTION,
6864+
responseByRunOrdinal: { 1: "Morning Codex summary.", 2: "", 3: "", 4: "Recovered." },
6865+
capturedTurns,
6866+
interruptedRunOrdinals: new Set([2, 3]),
6867+
nativeTurnKept: (nativeTurnId) =>
6868+
!(nativeTurnId.endsWith(":2") || nativeTurnId.endsWith(":3")) ||
6869+
(sessionOpen && nativeTurnId.endsWith(":2")),
6870+
}),
6871+
]);
6872+
6873+
yield* Effect.gen(function* () {
6874+
const orchestrator = yield* Orchestrator.OrchestratorV2;
6875+
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
6876+
const testThreadId = ThreadId.make("thread:stopped-twice-session-closed");
6877+
yield* orchestrator.dispatch({
6878+
type: "thread.create",
6879+
createdBy: "user",
6880+
creationSource: "web",
6881+
commandId: CommandId.make("command:stopped-twice:create"),
6882+
threadId: testThreadId,
6883+
projectId,
6884+
title: "Stopped twice, session closed",
6885+
modelSelection: CODEX_MODEL_SELECTION,
6886+
runtimeMode: "full-access",
6887+
interactionMode: "default",
6888+
branch: null,
6889+
worktreePath: cwd,
6890+
});
6891+
let step = 0;
6892+
const send = (text: string) =>
6893+
Effect.gen(function* () {
6894+
step += 1;
6895+
yield* orchestrator.dispatch({
6896+
type: "message.dispatch",
6897+
createdBy: "user",
6898+
creationSource: "web",
6899+
commandId: CommandId.make(`command:stopped-twice:msg-${step}`),
6900+
threadId: testThreadId,
6901+
messageId: MessageId.make(`message:stopped-twice:${step}`),
6902+
text,
6903+
attachments: [],
6904+
modelSelection: CODEX_MODEL_SELECTION,
6905+
dispatchMode: { type: "start_immediately" },
6906+
});
6907+
yield* worker.drain();
6908+
yield* waitForIdle(testThreadId);
6909+
yield* worker.drain();
6910+
return yield* orchestrator.getThreadProjection(testThreadId);
6911+
});
6912+
6913+
yield* send("Morning task");
6914+
yield* send("First stopped question");
6915+
const afterRun3 = yield* send("Second stopped question");
6916+
// The live session carries run 2's request itself, so the server sends nothing extra.
6917+
assert.notInclude((yield* Ref.get(capturedTurns)).at(-1)!.text, "First stopped question");
6918+
6919+
sessionOpen = false;
6920+
const afterRun4 = yield* send("Resume");
6921+
const run4Turn = (yield* Ref.get(capturedTurns)).at(-1)!;
6922+
assert.include(run4Turn.text, "First stopped question");
6923+
assert.include(run4Turn.text, "Second stopped question");
6924+
for (const ordinal of [2, 3]) {
6925+
const stoppedRun = afterRun3.runs.find((run) => run.ordinal === ordinal)!;
6926+
assert.equal(stoppedRun.status, "interrupted");
6927+
const stoppedTurn = afterRun4.providerTurns.find(
6928+
(turn) => turn.runAttemptId === stoppedRun.activeAttemptId,
6929+
);
6930+
assert.equal(stoppedTurn?.promptDropped, true);
6931+
}
6932+
}).pipe(
6933+
Effect.provide(
6934+
ProviderReplayHarness.layerWithRegistry(
6935+
{
6936+
name: "stopped-twice-session-closed",
6937+
runtimePolicyOverride: {
6938+
cwd,
6939+
approvalPolicy: "never",
6940+
sandboxPolicy: {
6941+
type: "readOnly",
6942+
access: { type: "fullAccess" },
6943+
networkAccess: false,
6944+
},
6945+
},
6946+
},
6947+
layerRegistry,
6948+
),
6949+
),
6950+
);
6951+
}),
6952+
);
68506953
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.