Skip to content

Commit 49d5625

Browse files
github-actions[bot]juliusmarminge
authored andcommitted
fix(server): fail V2 turns when the OpenCode event stream ends
1 parent c495cce commit 49d5625

2 files changed

Lines changed: 197 additions & 3 deletions

File tree

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

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
type OrchestrationV2ProviderTurn,
1818
} from "@t3tools/contracts";
1919
import * as Effect from "effect/Effect";
20+
import * as Clock from "effect/Clock";
2021
import * as DateTime from "effect/DateTime";
2122
import * as Deferred from "effect/Deferred";
2223
import * as Fiber from "effect/Fiber";
@@ -1367,6 +1368,167 @@ describe("OpenCodeAdapterV2", () => {
13671368
}).pipe(Effect.provide(idAllocatorLayer), Effect.scoped),
13681369
);
13691370

1371+
it.effect("fails an active turn when the OpenCode event stream ends cleanly", () =>
1372+
Effect.gen(function* () {
1373+
const nativeEvents = asyncEventStream();
1374+
const harness = yield* makeOpenCodeRuntimeHarness(
1375+
"clean-event-eof",
1376+
"native-opencode-clean-event-eof",
1377+
{
1378+
event: {
1379+
subscribe: async (_input: unknown, options: { signal?: AbortSignal }) => {
1380+
options.signal?.addEventListener("abort", () => nativeEvents.close(), { once: true });
1381+
return { stream: nativeEvents.stream };
1382+
},
1383+
},
1384+
session: {
1385+
create: async () => ({
1386+
data: { id: "native-opencode-clean-event-eof", time: { created: 1, updated: 1 } },
1387+
}),
1388+
promptAsync: async () => ({ data: true }),
1389+
},
1390+
},
1391+
);
1392+
yield* harness.startTurn();
1393+
const terminalEvents = yield* harness.runtime.events.pipe(
1394+
Stream.runCollect,
1395+
Effect.forkScoped,
1396+
);
1397+
1398+
nativeEvents.close();
1399+
const received = Array.from(yield* Fiber.join(terminalEvents));
1400+
assert.isTrue(
1401+
received.some(
1402+
(event) =>
1403+
event.type === "provider_session.updated" && event.providerSession.status === "error",
1404+
),
1405+
);
1406+
const terminal = received.find((event) => event.type === "turn.terminal");
1407+
assert.equal(terminal?.status, "failed");
1408+
assert.equal(terminal?.failure?.class, "transport_error");
1409+
assert.equal((yield* Effect.exit(harness.startTurn()))._tag, "Failure");
1410+
}).pipe(Effect.provide(idAllocatorLayer), Effect.scoped),
1411+
);
1412+
1413+
it.effect("fails compaction when its response races stream termination", () =>
1414+
Effect.gen(function* () {
1415+
const nativeEvents = asyncEventStream();
1416+
const summarizeStarted = promiseGate<void>();
1417+
const summarizeResult = promiseGate<{ data: boolean }>();
1418+
const baseClock = yield* Clock.Clock;
1419+
const eofClockRead = yield* Deferred.make<void>();
1420+
const releaseEofClockRead = yield* Deferred.make<void>();
1421+
let blockNextClockRead = false;
1422+
const blockingClock: Clock.Clock = {
1423+
...baseClock,
1424+
currentTimeMillis: Effect.suspend(() => {
1425+
if (!blockNextClockRead) return baseClock.currentTimeMillis;
1426+
blockNextClockRead = false;
1427+
return Deferred.succeed(eofClockRead, undefined).pipe(
1428+
Effect.andThen(Deferred.await(releaseEofClockRead)),
1429+
Effect.andThen(baseClock.currentTimeMillis),
1430+
);
1431+
}),
1432+
};
1433+
const harness = yield* makeOpenCodeRuntimeHarness(
1434+
"compaction-eof-race",
1435+
"native-opencode-compaction-eof-race",
1436+
{
1437+
event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
1438+
session: {
1439+
create: async () => ({
1440+
data: { id: "native-opencode-compaction-eof-race", time: { created: 1, updated: 1 } },
1441+
}),
1442+
summarize: () => {
1443+
summarizeStarted.resolve();
1444+
return summarizeResult.promise;
1445+
},
1446+
},
1447+
},
1448+
).pipe(Effect.provideService(Clock.Clock, blockingClock));
1449+
const events = yield* harness.runtime.events.pipe(Stream.runCollect, Effect.forkScoped);
1450+
const start = yield* harness.startTurn("/compact").pipe(Effect.forkScoped);
1451+
yield* Effect.promise(() => summarizeStarted.promise);
1452+
blockNextClockRead = true;
1453+
nativeEvents.close();
1454+
yield* Deferred.await(eofClockRead);
1455+
summarizeResult.resolve({ data: true });
1456+
yield* Fiber.join(start);
1457+
yield* Deferred.succeed(releaseEofClockRead, undefined);
1458+
const received = Array.from(yield* Fiber.join(events));
1459+
const terminals = received.filter((event) => event.type === "turn.terminal");
1460+
assert.lengthOf(terminals, 1);
1461+
assert.equal(terminals[0]?.status, "failed");
1462+
assert.equal(terminals[0]?.failure?.class, "transport_error");
1463+
assert.isFalse(
1464+
received.some(
1465+
(event) =>
1466+
event.type === "turn_item.updated" &&
1467+
event.turnItem.type === "compaction" &&
1468+
event.turnItem.status === "completed",
1469+
),
1470+
);
1471+
}).pipe(Effect.provide(idAllocatorLayer), Effect.scoped),
1472+
);
1473+
1474+
it.effect("does not register a turn after the OpenCode event stream ends", () =>
1475+
Effect.gen(function* () {
1476+
const nativeEvents = asyncEventStream();
1477+
let promptCalls = 0;
1478+
const harness = yield* makeOpenCodeRuntimeHarness(
1479+
"event-eof-start-race",
1480+
"native-opencode-event-eof-start-race",
1481+
{
1482+
event: {
1483+
subscribe: async (_input: unknown, options: { signal?: AbortSignal }) => {
1484+
options.signal?.addEventListener("abort", () => nativeEvents.close(), { once: true });
1485+
return { stream: nativeEvents.stream };
1486+
},
1487+
},
1488+
session: {
1489+
create: async () => ({
1490+
data: {
1491+
id: "native-opencode-event-eof-start-race",
1492+
time: { created: 1, updated: 1 },
1493+
},
1494+
}),
1495+
promptAsync: async () => {
1496+
promptCalls += 1;
1497+
return { data: true };
1498+
},
1499+
},
1500+
},
1501+
);
1502+
const baseClock = yield* Clock.Clock;
1503+
const startClockRead = yield* Deferred.make<void>();
1504+
const releaseStartClockRead = yield* Deferred.make<void>();
1505+
let blockNextClockRead = true;
1506+
const blockingClock: Clock.Clock = {
1507+
...baseClock,
1508+
currentTimeMillis: Effect.suspend(() => {
1509+
if (!blockNextClockRead) return baseClock.currentTimeMillis;
1510+
blockNextClockRead = false;
1511+
return Deferred.succeed(startClockRead, undefined).pipe(
1512+
Effect.andThen(Deferred.await(releaseStartClockRead)),
1513+
Effect.andThen(baseClock.currentTimeMillis),
1514+
);
1515+
}),
1516+
};
1517+
const start = yield* harness
1518+
.startTurn()
1519+
.pipe(Effect.provideService(Clock.Clock, blockingClock), Effect.exit, Effect.forkScoped);
1520+
yield* Deferred.await(startClockRead);
1521+
1522+
const events = yield* harness.runtime.events.pipe(Stream.runCollect, Effect.forkScoped);
1523+
nativeEvents.close();
1524+
yield* Fiber.join(events);
1525+
yield* Deferred.succeed(releaseStartClockRead, undefined);
1526+
1527+
assert.isTrue(Exit.isFailure(yield* Fiber.join(start)));
1528+
assert.equal(promptCalls, 0);
1529+
}).pipe(Effect.provide(idAllocatorLayer), Effect.scoped),
1530+
);
1531+
13701532
it("holds stale idle through prompt admission until the new user message is observed", () => {
13711533
const admission = {
13721534
admissionPending: true,

‎apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1039,7 +1039,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
10391039
updatedAt: now,
10401040
lastError: null,
10411041
};
1042-
const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
1042+
const events = yield* Queue.unbounded<ProviderAdapterV2Event, Cause.Done>();
1043+
let nativeStreamFailure: OrchestrationV2ProviderFailure | null = null;
10431044
const threads = new Map<string, OpenCodeThreadState>();
10441045
const pendingRequests = new Map<string, PendingOpenCodeRequest>();
10451046
const pendingRequestsByNativeId = new Map<string, PendingOpenCodeRequest>();
@@ -2113,6 +2114,10 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
21132114
},
21142115
) {
21152116
if (turn.finalized) return;
2117+
if (nativeStreamFailure !== null) {
2118+
status = "failed";
2119+
terminal = { failure: nativeStreamFailure, threadDisposition: "broken" };
2120+
}
21162121
turn.finalized = true;
21172122
const completedAt = yield* DateTime.now;
21182123
for (const part of turn.parts.values()) {
@@ -2795,6 +2800,10 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
27952800
const detail = Exit.isSuccess(exit)
27962801
? "OpenCode event stream ended unexpectedly."
27972802
: openCodeRuntimeErrorDetail(Cause.squash(exit.cause));
2803+
nativeStreamFailure = makeProviderFailure({
2804+
message: detail,
2805+
class: "transport_error",
2806+
});
27982807
yield* updateProviderSession("error", detail);
27992808
for (const state of threads.values()) {
28002809
if (state.activeTurn !== null)
@@ -2803,6 +2812,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
28032812
threadDisposition: "broken",
28042813
});
28052814
}
2815+
yield* Queue.end(events);
28062816
}),
28072817
),
28082818
Effect.forkIn(scope),
@@ -3082,6 +3092,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
30823092
}),
30833093
startTurn: (turnInput) =>
30843094
Effect.gen(function* () {
3095+
if (nativeStreamFailure !== null) {
3096+
return yield* protocolError(
3097+
"OpenCode event stream has ended; reconnect the provider session before starting another turn.",
3098+
);
3099+
}
30853100
const sessionId = nativeThreadId(turnInput.providerThread);
30863101
const state = threads.get(sessionId);
30873102
if (state === undefined) {
@@ -3119,6 +3134,21 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
31193134
startedAt,
31203135
completedAt: null,
31213136
};
3137+
const admissionMessageId = yield* makeOpenCodeMessageId();
3138+
// No Effect may be yielded between this check and installing the
3139+
// turn. If the event stream ended while IDs were being prepared,
3140+
// registering afterward would leave a running turn that the EOF
3141+
// handler had already finished scanning.
3142+
if (nativeStreamFailure !== null) {
3143+
return yield* protocolError(
3144+
"OpenCode event stream has ended; reconnect the provider session before starting another turn.",
3145+
);
3146+
}
3147+
if (state.activeTurn !== null) {
3148+
return yield* protocolError(
3149+
`OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`,
3150+
);
3151+
}
31223152
const turn: ActiveOpenCodeTurn = {
31233153
isRoot: true,
31243154
threadId: turnInput.threadId,
@@ -3140,7 +3170,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
31403170
providerTurn,
31413171
nextItemOrdinal: turnInput.providerTurnOrdinal * 100 + 1,
31423172
nativeUserMessageId: null,
3143-
admissionMessageId: yield* makeOpenCodeMessageId(),
3173+
admissionMessageId,
31443174
interrupted: false,
31453175
finalized: false,
31463176
planId: null,
@@ -3178,7 +3208,9 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
31783208
),
31793209
).pipe(
31803210
Effect.tap(() =>
3181-
turn.interrupted ? Effect.void : emitCompactionItem(state, turn),
3211+
turn.interrupted || turn.finalized || nativeStreamFailure !== null
3212+
? Effect.void
3213+
: emitCompactionItem(state, turn),
31823214
),
31833215
Effect.tap(() =>
31843216
finalizeTurn(state, turn, turn.interrupted ? "interrupted" : "completed"),

0 commit comments

Comments
 (0)