Skip to content

Commit f9a3c38

Browse files
shivamhwpPR Batch Testerclaudemaria-rcksjuliusmarminge
authored
fix(antigravity): recover threads after a lost thinking signature (pingdotgg#28889)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
1 parent 6d1381f commit f9a3c38

9 files changed

Lines changed: 401 additions & 80 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts‎

Lines changed: 87 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1336,6 +1336,10 @@ describe("AcpAdapterV2", () => {
13361336
);
13371337
it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () =>
13381338
Effect.gen(function* () {
1339+
const checking = yield* Deferred.make<void>();
1340+
const releaseCheck = yield* Deferred.make<void>();
1341+
const cancelled = yield* Deferred.make<void>();
1342+
const idAllocator = yield* IdAllocator.IdAllocatorV2;
13391343
const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome");
13401344
const threadId = ThreadId.make("thread-acp-prompt-outcome");
13411345
const quota = {
@@ -1345,6 +1349,12 @@ describe("AcpAdapterV2", () => {
13451349
retryable: true,
13461350
resetAt: "2030-01-01T00:00:00.000Z",
13471351
} as const;
1352+
const poisoned = {
1353+
class: "provider_error",
1354+
message: "Saved history is unusable.",
1355+
code: "INVALID_THINKING_SIGNATURE",
1356+
retryable: true,
1357+
} as const;
13481358
// The runtime ordinal of each prompt, and the session each check watched.
13491359
const promptRuntimes: Array<number> = [];
13501360
const promptTexts: Array<string> = [];
@@ -1358,14 +1368,27 @@ describe("AcpAdapterV2", () => {
13581368
watchPromptOutcome: (sessionId) =>
13591369
Effect.sync(() => {
13601370
watchedSessions.push(sessionId);
1361-
const failed = watchedSessions.length === 1;
1362-
return () => Effect.succeed(failed ? quota : undefined);
1371+
const outcome =
1372+
watchedSessions.length === 1
1373+
? { failure: quota, threadDisposition: "reusable" as const }
1374+
: watchedSessions.length >= 3
1375+
? { failure: poisoned, threadDisposition: "broken" as const }
1376+
: undefined;
1377+
const interrupted = watchedSessions.length === 4;
1378+
return () =>
1379+
interrupted
1380+
? Deferred.succeed(checking, undefined).pipe(
1381+
Effect.andThen(Deferred.await(releaseCheck)),
1382+
Effect.as(outcome),
1383+
)
1384+
: Effect.succeed(outcome);
13631385
}),
13641386
makeRuntime: makeMockRuntime({
13651387
childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
13661388
mockAgentPath: yield* bundledMockAgentPath,
13671389
wrapRuntime: (runtime, runtimeOrdinal) => ({
13681390
...runtime,
1391+
cancel: Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid),
13691392
prompt: (payload) =>
13701393
Effect.sync(() => {
13711394
promptRuntimes.push(runtimeOrdinal);
@@ -1409,26 +1432,82 @@ describe("AcpAdapterV2", () => {
14091432
ordinal,
14101433
}),
14111434
);
1412-
const events = yield* runtime.events.pipe(
1413-
Stream.takeUntil((event) => event.type === "turn.terminal"),
1414-
Stream.runCollect,
1435+
return Array.from(
1436+
yield* runtime.events.pipe(
1437+
Stream.takeUntil((event) => event.type === "turn.terminal"),
1438+
Stream.runCollect,
1439+
),
14151440
);
1416-
return events.at(-1);
14171441
});
14181442

1419-
const failed = yield* runTurn(1);
1443+
const failed = (yield* runTurn(1)).at(-1);
14201444
if (failed?.type !== "turn.terminal" || failed.status !== "failed") {
14211445
return assert.fail("expected a failed terminal");
14221446
}
14231447
assert.deepEqual(failed.failure, quota);
1424-
const completed = yield* runTurn(2);
1448+
const completed = (yield* runTurn(2)).at(-1);
14251449
assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed");
14261450
assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime");
14271451
// The fresh runtime has no record of what reached the agent, so it sends T3's notes again.
14281452
assert.include(promptTexts[1] ?? "", "<runtime_info>");
14291453
assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default");
14301454
assert.equal(watchedSessions.length, 2);
14311455
assert.equal(watchedSessions[0], watchedSessions[1]);
1456+
1457+
// Poisoned native history marks the thread broken; its persisted error row is never resumed.
1458+
const poisonedEvents = yield* runTurn(3);
1459+
const broken = poisonedEvents.at(-1);
1460+
if (broken?.type !== "turn.terminal" || broken.status !== "failed") {
1461+
return assert.fail("expected a failed terminal");
1462+
}
1463+
assert.deepEqual(broken.failure, poisoned);
1464+
assert.equal(broken.threadDisposition, "broken");
1465+
const brokenThread = poisonedEvents.findLast(
1466+
(event) => event.type === "provider_thread.updated",
1467+
);
1468+
assert.equal(
1469+
brokenThread?.type === "provider_thread.updated"
1470+
? brokenThread.providerThread.status
1471+
: null,
1472+
"error",
1473+
);
1474+
const resumed = yield* Effect.result(
1475+
runtime.resumeThread({
1476+
threadId,
1477+
providerThread: { ...providerThread, status: "error" },
1478+
modelSelection,
1479+
runtimePolicy,
1480+
}),
1481+
);
1482+
assert.equal(
1483+
resumed._tag === "Failure" ? resumed.failure._tag : null,
1484+
"ProviderAdapterResumeThreadError",
1485+
);
1486+
1487+
const turn = yield* Effect.forkChild(runTurn(4));
1488+
yield* Deferred.await(checking);
1489+
const stop = yield* Effect.forkChild(
1490+
runtime.interruptTurn({
1491+
providerThread,
1492+
providerTurnId: idAllocator.derive.providerTurn({
1493+
driver: ACP_TEST_DRIVER,
1494+
nativeTurnId: acpScopedNativeId(instanceId, `${watchedSessions[3]}:turn:4`),
1495+
}),
1496+
}),
1497+
);
1498+
yield* Deferred.await(cancelled);
1499+
yield* Deferred.succeed(releaseCheck, undefined);
1500+
const interruptedEvents = yield* Fiber.join(turn);
1501+
yield* Fiber.join(stop);
1502+
const interrupted = interruptedEvents.at(-1);
1503+
assert.equal(
1504+
interrupted?.type === "turn.terminal" ? interrupted.status : null,
1505+
"interrupted",
1506+
);
1507+
assert.equal(
1508+
interrupted?.type === "turn.terminal" ? interrupted.threadDisposition : null,
1509+
"broken",
1510+
);
14321511
}).pipe(Effect.provide(layerTest)),
14331512
);
14341513
it.live("retains returned usage when Stop finalizes before the prompt callback", () =>

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2722,6 +2722,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
27222722
const deliveryProviderThread = canResumeAcrossInstances
27232723
? {
27242724
...queuedProviderThread,
2725+
status: activeProviderThread.status,
27252726
nativeThreadRef: activeProviderThread.nativeThreadRef,
27262727
nativeConversationHeadRef: activeProviderThread.nativeConversationHeadRef,
27272728
nativeMetadata: activeProviderThread.nativeMetadata,
@@ -2913,7 +2914,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
29132914
const providerThread: OrchestrationV2ProviderThread = {
29142915
...deliveryProviderThread,
29152916
providerSessionId,
2916-
status: "not_loaded",
2917+
status: deliveryProviderThread.status === "error" ? "error" : "not_loaded",
29172918
firstRunOrdinal: queuedProviderThread.firstRunOrdinal ?? ordinal,
29182919
lastRunOrdinal: ordinal,
29192920
handoffIds: appendContextHandoffId(
@@ -8815,7 +8816,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
88158816
: null;
88168817
const providerThread: OrchestrationV2ProviderThread = {
88178818
...ensuredProviderThread,
8818-
status: "active",
8819+
status: ensuredProviderThread.status === "error" ? "error" : "active",
88198820
firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal,
88208821
lastRunOrdinal: ordinal,
88218822
handoffIds: [

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

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2986,11 +2986,20 @@ effectIt.effect("does not mistake a failed state read for a superseded run", ()
29862986
}),
29872987
);
29882988

2989-
effectIt.effect(
2990-
"signs out the existing native provider before opening the newly selected provider",
2991-
() =>
2989+
effectIt.effect.each(["not_loaded", "error"] as const)(
2990+
"signs out the existing native provider before opening the newly selected provider with status %s",
2991+
(providerThreadStatus) =>
29922992
Effect.gen(function* () {
29932993
const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
2994+
const initial = harness.projection();
2995+
harness.setProjection({
2996+
...initial,
2997+
providerThreads: initial.providerThreads.map((thread) =>
2998+
thread.id === "new-provider-thread"
2999+
? { ...thread, status: providerThreadStatus }
3000+
: thread,
3001+
),
3002+
});
29943003

29953004
yield* harness.start;
29963005
yield* harness.start;
@@ -3016,6 +3025,9 @@ effectIt.effect(
30163025
]);
30173026
expect(projection.providerTurns).toEqual([]);
30183027
expect(projection.checkpoints).toEqual([]);
3028+
expect(
3029+
projection.providerThreads.find((thread) => thread.id === "new-provider-thread")?.status,
3030+
).toBe(providerThreadStatus);
30193031
}),
30203032
);
30213033

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

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -686,7 +686,12 @@ export const layer: Layer.Layer<
686686
},
687687
providerThreadUpdate: {
688688
...providerThread,
689-
status: providerThread.nativeThreadRef === null ? "not_loaded" : "idle",
689+
status:
690+
providerThread.status === "error"
691+
? "error"
692+
: providerThread.nativeThreadRef === null
693+
? "not_loaded"
694+
: "idle",
690695
updatedAt: now,
691696
},
692697
});
@@ -842,6 +847,12 @@ export const layer: Layer.Layer<
842847
run,
843848
checkpointScope,
844849
});
850+
const brokenNativeThread = providerThread.status === "error";
851+
// Opened without the broken native id, a session that was not live starts fresh.
852+
const opensFreshSession =
853+
brokenNativeThread &&
854+
providerThread.nativeThreadRef !== null &&
855+
!(yield* providerSessions.isLive(providerSessionId));
845856
const sessionResult = yield* Effect.result(
846857
providerSessions.open({
847858
threadId: projection.thread.id,
@@ -851,7 +862,7 @@ export const layer: Layer.Layer<
851862
...(existingSessionProjection === undefined
852863
? {}
853864
: { resumeFromSession: existingSessionProjection }),
854-
...(providerThread.nativeThreadRef?.nativeId == null
865+
...(providerThread.nativeThreadRef?.nativeId == null || brokenNativeThread
855866
? {}
856867
: { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
857868
...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
@@ -1158,6 +1169,7 @@ export const layer: Layer.Layer<
11581169
const createdAt = yield* DateTime.now;
11591170
const history = yield* projectionStore.getTurnStartHistory(input.threadId);
11601171
const boundary = contextBoundaryOrdinal({ runs: projection.runs, turnItems: history });
1172+
const from = Math.max(1, boundary);
11611173
const handoff = yield* contextHandoffService.prepareProviderHandoff({
11621174
threadId: projection.thread.id,
11631175
targetRunId: run.id,
@@ -1166,7 +1178,7 @@ export const layer: Layer.Layer<
11661178
toProviderThreadId: providerThread.id,
11671179
fromProviderInstanceId: providerThread.providerInstanceId,
11681180
toProviderInstanceId: run.providerInstanceId,
1169-
coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
1181+
coveredRunOrdinals: { from, to: Math.max(from, run.ordinal - 1) },
11701182
strategy: "full_thread_summary",
11711183
runs: projection.runs,
11721184
items: [
@@ -1536,7 +1548,10 @@ export const layer: Layer.Layer<
15361548
providerSessionId,
15371549
// Clear the native ref to force a fresh session while preserving row identity.
15381550
existingProviderThread: { ...providerThread, nativeThreadRef: null },
1539-
forceNewNativeThread: true,
1551+
// A fresh session that never loaded the broken history needs no replacement.
1552+
...(opensFreshSession && resumed._tag === "Failure"
1553+
? {}
1554+
: { forceNewNativeThread: true }),
15401555
}),
15411556
);
15421557
if (replacement === undefined) return undefined;

0 commit comments

Comments
 (0)