Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(capture): keep every turn captured across engine rollovers and queued prompts

Samrat Talukdar7d0059b3e068
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index e35edc5d..087b6978 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -12,7 +12,7 @@
*/
import { Worker } from "node:worker_threads";
-import { CaptureHost, type CaptureDiagnostics, type CaptureHostOptions, type EngineTarget, type PromptRecord } from "./capture-host.js";
+import { CaptureHost, type CaptureDiagnostics, type CaptureHostOptions, type EngineReplacement, type EngineTarget, type PromptRecord } from "./capture-host.js";
import {
invokeCapture,
serializeResponse,
@@ -61,6 +61,8 @@ export type CaptureService = {
recordWebVisit(sessionId: string, visit: CollectorWebVisit): boolean;
archiveSessionStarted(sessionId: string, root: string, target: EngineTarget): void;
observeSession(sessionId: string, target: EngineTarget): void;
+ /** An engine was closed and another took over its sessions: turn observers reading it move there. */
+ engineReplaced(closedBaseUrl: string, replacement: EngineReplacement): void;
sessionDeleted(sessionId: string): void;
signOut(): Promise<void>;
/**
@@ -158,6 +160,10 @@ class CaptureClient implements CaptureService {
this.send({ kind: "call", id: null, method: "observeSession", args: [sessionId, target] });
}
+ engineReplaced(closedBaseUrl: string, replacement: EngineReplacement): void {
+ this.send({ kind: "call", id: null, method: "engineReplaced", args: [closedBaseUrl, replacement] });
+ }
+
sessionDeleted(sessionId: string): void {
if (this.sessions.get(sessionId) === true) this.sessions.set(sessionId, false);
this.send({ kind: "call", id: null, method: "sessionDeleted", args: [sessionId] });
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index 6f5396f6..09a5248b 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -11,8 +11,12 @@
import { collectPromptAttachments, promptBodyForTrace, v2PromptBodyForTrace } from "./collector-attachments.js";
import {
createSessionObservers,
+ currentEngineTarget,
+ engineReplaced,
observeCollectedSession,
projectArchiveEngineReads,
+ promptDispatched,
+ type EngineReplacement,
type EngineTarget,
type SessionObservers,
} from "./collector-observer.js";
@@ -21,7 +25,7 @@ import { SessionArchiver, type SessionArchiverOptions } from "./session-archive/
import { ProjectArchiveLifecycle, type ArchiveLifecycleLog } from "./session-archive/lifecycle.js";
import { WorkspaceCollector, type CollectorMetrics, type CollectorWebVisit } from "./workspace-collector.js";
-export type { EngineTarget } from "./collector-observer.js";
+export type { EngineReplacement, EngineTarget } from "./collector-observer.js";
export type CaptureLog = ArchiveLifecycleLog;
@@ -39,6 +43,11 @@ export type PromptRecord = {
root: string;
/** A prompt dispatch: its file parts become "attachment" events. */
attachments: boolean;
+ /**
+ * When a prompt dispatch went out (epoch milliseconds, taken before the
+ * engine saw it): a turn of the session still being followed ends here.
+ */
+ dispatchedAt?: number;
};
export type CaptureHostOptions = {
@@ -117,6 +126,8 @@ export class CaptureHost {
/** The "engine.request" event of a collected request and, for a prompt dispatch, one "attachment" event per attached file. */
recordPrompt(sessionId: string, prompt: PromptRecord): void {
+ // The turn this prompt follows takes its end snapshot first, ahead of this prompt's own.
+ if (prompt.dispatchedAt !== undefined) promptDispatched(this.observers, this.collector, sessionId, prompt.dispatchedAt);
const payload = requestPayload(prompt.body);
this.collector.recordTrace(sessionId, "engine.request", {
method: prompt.method,
@@ -139,7 +150,12 @@ export class CaptureHost {
/** A prompt was dispatched: the project archive's session start (a base once per session, see lifecycle.ts). */
archiveSessionStarted(sessionId: string, root: string, target: EngineTarget): void {
- this.archive.sessionStarted({ sessionId, root, engine: projectArchiveEngineReads(target, sessionId) });
+ this.archive.sessionStarted({ sessionId, root, engine: projectArchiveEngineReads(() => currentEngineTarget(this.observers, target), sessionId) });
+ }
+
+ /** An engine was closed and `replacement` took over its sessions: observations reading it move there. */
+ engineReplaced(closedBaseUrl: string, replacement: EngineReplacement): void {
+ engineReplaced(this.observers, closedBaseUrl, replacement);
}
/** The engine accepted a collected request: follow the session until its turn settles. */
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index 35ad185a..a4f4ac78 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -7,7 +7,7 @@
* logs and closed sessions. Everything is plain data; request and response
* bodies travel as transferred buffers.
*/
-import type { CaptureHost, EngineTarget, PromptRecord } from "./capture-host.js";
+import type { CaptureHost, EngineReplacement, EngineTarget, PromptRecord } from "./capture-host.js";
import type { FolderGateOptions } from "./session-archive/detect.js";
import type { CollectorWebVisit } from "./workspace-collector.js";
@@ -23,6 +23,7 @@ export type CaptureCalls = {
recordWebVisit: [sessionId: string, visit: CollectorWebVisit];
archiveSessionStarted: [sessionId: string, root: string, target: EngineTarget];
observeSession: [sessionId: string, target: EngineTarget];
+ engineReplaced: [closedBaseUrl: string, replacement: EngineReplacement];
sessionDeleted: [sessionId: string];
signOut: [];
stop: [options?: CaptureStopOptions];
@@ -126,6 +127,8 @@ export function invokeCapture(host: CaptureHost, call: CaptureCall): unknown {
return host.archiveSessionStarted(...call.args);
case "observeSession":
return host.observeSession(...call.args);
+ case "engineReplaced":
+ return host.engineReplaced(...call.args);
case "sessionDeleted":
return host.sessionDeleted(...call.args);
case "signOut":
diff --git a/apps/server/src/collector-observer.test.ts b/apps/server/src/collector-observer.test.ts
index cc0edf69..c8224e1b 100644
--- a/apps/server/src/collector-observer.test.ts
+++ b/apps/server/src/collector-observer.test.ts
@@ -6,8 +6,10 @@ import { zstdDecompressSync } from "node:zlib";
import {
createSessionObservers,
+ engineReplaced,
observeCollectedSession,
projectArchiveEngineReads,
+ promptDispatched,
type EngineTarget,
type ObservedCollector,
type ObserverTiming,
@@ -70,6 +72,8 @@ function startEngine() {
/** Real milliseconds the next status reads take to answer, one entry per read. */
statusDelaysMs: [] as number[],
statusReads: 0,
+ /** The Authorization header of every request. */
+ authorizations: [] as string[],
/** Runs once a page of messages was read. */
onMessagesRead: null as (() => void) | null,
};
@@ -78,6 +82,7 @@ function startEngine() {
port: 0,
async fetch(request) {
const url = new URL(request.url);
+ control.authorizations.push(request.headers.get("authorization") ?? "");
if (url.pathname === "/session/status") {
control.statusReads += 1;
const delay = control.statusDelaysMs.shift();
@@ -443,6 +448,129 @@ describe("collector observer", () => {
});
});
+describe("collector observer across engine rollovers and queued prompts", () => {
+ /** A message the engine created at `created` (epoch ms); an assistant one finished. */
+ const at = (id: string, role: "user" | "assistant", created: number): EngineMessage => {
+ const each = message(id, role);
+ each.info.time = role === "assistant" ? { created, completed: created + 1 } : { created };
+ if (role === "assistant") each.info.finish = "stop";
+ return each;
+ };
+
+ test("an engine closed mid-turn by a rollover hands the observation to the engine that took over: the turn settles there with its messages and snapshot", async () => {
+ const clock = fakeClock();
+ // Two engine generations over one shared database: the same messages answer on both.
+ const draining = startEngine();
+ const primary = startEngine();
+ const collector = new FakeCollector();
+ const archive = fakeArchive();
+ const observers = createSessionObservers();
+ const shared = [message("msg_user_0001", "user")];
+ draining.control.messages = shared;
+ primary.control.messages = shared;
+ // The turn runs on the draining engine; the new primary never ran it, so it reports the session idle.
+ draining.control.status = () => (clock.elapsed() < 90_000 ? "busy" : "idle");
+ primary.control.status = () => "idle";
+ // The turn ends; a moment later (before the observer saw it idle twice) the pool retires the
+ // drained engine: it tells the observers first, then closes it.
+ clock.at(90_000, () => shared.push(message("msg_assistant_0001", "assistant")));
+ clock.at(90_500, () => {
+ engineReplaced(observers, draining.target.baseUrl, { baseUrl: primary.target.baseUrl, authorization: "Basic bmV3LWVuZ2luZQ==" });
+ void draining.server.stop(true);
+ });
+
+ await observe({ collector, archive, observers, target: draining.target, timing: clock.timing });
+
+ expect(collector.labels()).not.toContain("session.engine_unavailable");
+ expect(collector.labels()).not.toContain("session.observer_timeout");
+ expect(collector.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
+ expect(collector.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
+ expect(archive.calls).toEqual(["followed", "completed"]);
+ // It settled within seconds of the turn's end, reading the new engine with that engine's credentials.
+ expect(clock.elapsed()).toBeLessThan(100_000);
+ expect(primary.control.authorizations.length).toBeGreaterThan(0);
+ expect(new Set(primary.control.authorizations)).toEqual(new Set(["Basic bmV3LWVuZ2luZQ=="]));
+ // A request that still names the closed engine (it was routed before the close) is read from the new one.
+ const late = new FakeCollector();
+ const lateArchive = fakeArchive();
+ await observe({ collector: late, archive: lateArchive, observers, target: draining.target, timing: clock.timing });
+ expect(late.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
+ expect(observers.sessions.size).toBe(0);
+ });
+
+ test("a prompt sent within two seconds of the turn going idle ends that turn: each prompt gets its own snapshot, messages and settle", async () => {
+ const clock = fakeClock();
+ const engine = startEngine();
+ const collector = new FakeCollector();
+ const archive = fakeArchive();
+ const observers = createSessionObservers();
+ const start = clock.timing.now!();
+ engine.control.messages = [at("msg_user_0001", "user", start)];
+ let busyUntil = 59_500;
+ engine.control.status = () => (clock.elapsed() < busyUntil ? "busy" : "idle");
+ clock.at(59_500, () => engine.control.messages.push(at("msg_assistant_0001", "assistant", start + 59_000)));
+ // A queued prompt goes out a second after the turn went idle, between the observer's first idle
+ // read and the second one it settles on: the server records the dispatch, then the engine stores
+ // the prompt and runs a second turn.
+ clock.at(60_500, () => {
+ const dispatchedAt = clock.timing.now!();
+ promptDispatched(observers, collector, SESSION, dispatchedAt);
+ busyUntil = 3 * 60_000;
+ engine.control.messages.push(at("msg_user_0002", "user", dispatchedAt + 5));
+ // The prompt's response reaches the observer like any collected request.
+ void observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ });
+ clock.at(3 * 60_000, () => engine.control.messages.push(at("msg_assistant_0002", "assistant", start + 179_000)));
+
+ await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+
+ expect(collector.labels()).toEqual([
+ // Turn 1's end snapshot is taken as prompt 2 goes out (ahead of prompt 2's own snapshot).
+ "snapshot:turn_completed",
+ "session.idle", "flush:turn",
+ "session.idle", "snapshot:turn_completed", "flush:turn",
+ ]);
+ expect(collector.turnMessageIds()).toEqual([
+ ["msg_user_0001", "msg_assistant_0001"],
+ ["msg_user_0002", "msg_assistant_0002"],
+ ]);
+ expect(collector.checkpoint).toBe("msg_assistant_0002");
+ expect(archive.calls).toEqual(["followed", "completed", "followed", "completed"]);
+ expect(archive.turns.map((turn) => turn?.length)).toEqual([2, 4]);
+ });
+
+ test("a prompt sent into a turn still answering waits for that answer to finish before the turn settles", async () => {
+ const clock = fakeClock();
+ const engine = startEngine();
+ const collector = new FakeCollector();
+ const archive = fakeArchive();
+ const observers = createSessionObservers();
+ const start = clock.timing.now!();
+ const answering = at("msg_assistant_0001", "assistant", start + 1_000);
+ answering.info.time = { created: start + 1_000 };
+ delete answering.info.finish;
+ engine.control.messages = [at("msg_user_0001", "user", start), answering];
+ engine.control.status = () => (clock.elapsed() < 5 * 60_000 ? "busy" : "idle");
+ clock.at(30_000, () => {
+ const dispatchedAt = clock.timing.now!();
+ promptDispatched(observers, collector, SESSION, dispatchedAt);
+ engine.control.messages.push(at("msg_user_0002", "user", dispatchedAt + 5));
+ });
+ // Turn 1's answer ends a minute later; turn 2 answers after it.
+ clock.at(90_000, () => { answering.info.time = { created: start + 1_000, completed: start + 90_000 }; answering.info.finish = "stop"; });
+ clock.at(5 * 60_000, () => engine.control.messages.push(at("msg_assistant_0002", "assistant", start + 200_000)));
+
+ await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+
+ expect(collector.turnMessageIds()).toEqual([
+ ["msg_user_0001", "msg_assistant_0001"],
+ ["msg_user_0002", "msg_assistant_0002"],
+ ]);
+ expect(collector.labels().filter((label) => label === "snapshot:turn_completed")).toHaveLength(2);
+ expect(archive.calls).toEqual(["followed", "completed", "followed", "completed"]);
+ });
+});
+
describe("collector observer with the project archive", () => {
const user = (id: string) => message(`msg_user_${id}`, "user");
const answer = (id: string) => message(`msg_assistant_${id}`, "assistant");
diff --git a/apps/server/src/collector-observer.ts b/apps/server/src/collector-observer.ts
index 71045516..a9dff24d 100644
--- a/apps/server/src/collector-observer.ts
+++ b/apps/server/src/collector-observer.ts
@@ -20,22 +20,104 @@ export type EngineTarget = {
engine: "v1" | "v2";
};
+/**
+ * The turn being followed: whether its turn_completed snapshot was taken
+ * already, and when the next prompt of the session was dispatched while it
+ * had not settled (null until then). Such a turn ends at that prompt: its
+ * snapshot is taken right as the prompt goes out, and its messages stop
+ * before the prompt's own.
+ */
+type FollowedTurn = { snapshotTaken: boolean; cutAt: number | null };
+
/**
* A session being observed: the engine its latest collected request went to
* (an engine that restarted may answer on another port), how many requests
- * asked for it while it was, and the observation itself.
+ * asked for it while it was, the turn being followed, and the observation itself.
*/
-type ObservedSession = { target: EngineTarget; requests: number; done: Promise<void> };
+type ObservedSession = { target: EngineTarget; requests: number; turn: FollowedTurn | null; done: Promise<void> };
+
+/** The engine that took over from a closed one: its base URL and its Authorization header. */
+export type EngineReplacement = { baseUrl: string; authorization: string | null };
-/** Turn observers of one server: the sessions being observed, their last seen message, and the stop signal. */
+/** How many replaced engines are remembered (a request's target may still name one of them). */
+const MAX_REPLACED_ENGINES = 16;
+
+/**
+ * Turn observers of one server: the sessions being observed, their last seen
+ * message, the engines that took over from closed ones (by the closed one's
+ * origin), and the stop signal.
+ */
export type SessionObservers = {
sessions: Map<string, ObservedSession>;
lastMessageIds: Map<string, string>;
+ replacedEngines: Map<string, EngineReplacement>;
controller: AbortController;
};
export function createSessionObservers(): SessionObservers {
- return { sessions: new Map(), lastMessageIds: new Map(), controller: new AbortController() };
+ return { sessions: new Map(), lastMessageIds: new Map(), replacedEngines: new Map(), controller: new AbortController() };
+}
+
+function originOf(url: string): string {
+ try {
+ return new URL(url).origin;
+ } catch {
+ return url;
+ }
+}
+
+function replaceTarget(target: EngineTarget, replacement: EngineReplacement): EngineTarget {
+ const headers = target.headers.filter(([name]) => name.toLowerCase() !== "authorization");
+ if (replacement.authorization) headers.push(["authorization", replacement.authorization]);
+ return { ...target, baseUrl: replacement.baseUrl, headers };
+}
+
+/** `target`, moved onto the engine that took over when the one it names was closed (following a chain of takeovers). */
+export function currentEngineTarget(observers: SessionObservers, target: EngineTarget): EngineTarget {
+ let current = target;
+ for (let hops = 0; hops < MAX_REPLACED_ENGINES; hops += 1) {
+ const replacement = observers.replacedEngines.get(originOf(current.baseUrl));
+ if (!replacement || originOf(replacement.baseUrl) === originOf(current.baseUrl)) return current;
+ current = replaceTarget(current, replacement);
+ }
+ return current;
+}
+
+/**
+ * An engine was closed and another took over its sessions (an engine pool
+ * rollover retiring a drained engine, or a dead engine replaced): every
+ * observation reading the closed engine reads the new one from now on. The
+ * sessions live in the engines' shared database, so a turn that ran on the
+ * closed engine settles, with its messages, from the one that took over.
+ */
+export function engineReplaced(observers: SessionObservers, closedBaseUrl: string, replacement: EngineReplacement): void {
+ const closed = originOf(closedBaseUrl);
+ if (closed === originOf(replacement.baseUrl)) return;
+ observers.replacedEngines.delete(closed);
+ observers.replacedEngines.set(closed, replacement);
+ while (observers.replacedEngines.size > MAX_REPLACED_ENGINES) {
+ const oldest = observers.replacedEngines.keys().next().value;
+ if (oldest === undefined) break;
+ observers.replacedEngines.delete(oldest);
+ }
+ for (const session of observers.sessions.values()) session.target = currentEngineTarget(observers, session.target);
+}
+
+/**
+ * A prompt of a followed session was dispatched (at `at`, the dispatching
+ * thread's clock) while the turn before it has not settled: a queued prompt
+ * sent right as that turn went idle, or a prompt sent into a running turn.
+ * That turn ends here. Its turn_completed snapshot is taken now, ahead of
+ * the new prompt's own snapshot, so both turns keep their turn.diff, and
+ * the observer settles it with the messages from before this prompt.
+ */
+export function promptDispatched(observers: SessionObservers, collector: Pick<ObservedCollector, "captureSnapshot">, sessionId: string, at: number): void {
+ const turn = observers.sessions.get(sessionId)?.turn;
+ if (!turn || turn.cutAt !== null) return;
+ turn.cutAt = at;
+ if (turn.snapshotTaken) return;
+ turn.snapshotTaken = true;
+ collector.captureSnapshot(sessionId, "turn_completed");
}
/** What the observer asks of the collector. */
@@ -133,6 +215,8 @@ const MAX_STATUS_RETRY_MS = 30_000;
const ENGINE_UNAVAILABLE_TRACE_MS = 60_000;
/** A session never seen busy that stays idle this long settles without a finished answer (its prompt never ran). */
const NEVER_BUSY_SETTLE_MS = 10 * 60_000;
+/** A turn ended by the next prompt waits at most this long for that prompt's message to show up in the engine before it settles as it is. */
+const CUT_PROMPT_WAIT_MS = 15_000;
/** A settled turn whose messages the engine did not answer for (a timeout, a dropped connection) is read again after these waits. */
const HISTORY_RETRY_DELAYS_MS = [2_000, 5_000];
@@ -476,6 +560,56 @@ async function readEngineHistory(
return { outline: outline.reverse(), delta: delta.reverse(), sizes: sizes.reverse(), omitted };
}
+/** When the engine created a message (info.time.created, epoch milliseconds), if it says. */
+function messageCreatedAt(message: unknown): number | null {
+ if (!isRecord(message)) return null;
+ const info = isRecord(message.info) ? message.info : message;
+ const time = isRecord(info.time) ? info.time : null;
+ const created = time?.created;
+ if (typeof created === "number" && Number.isFinite(created)) return created;
+ if (typeof created === "string") {
+ const parsed = Date.parse(created);
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+ return null;
+}
+
+function messageRole(message: unknown): unknown {
+ if (!isRecord(message)) return undefined;
+ const info = isRecord(message.info) ? message.info : message;
+ return info.role ?? info.type;
+}
+
+/**
+ * The history of a turn the next prompt ended (that prompt dispatched at
+ * `cutAt`): everything before the first user message the engine created
+ * from then on. `found` says whether that message is there yet, and
+ * `answered` whether the newest assistant message before it finished.
+ */
+function historyBefore(history: EngineHistory, cutAt: number): { history: EngineHistory; found: boolean; answered: boolean } {
+ const cut = history.outline.findIndex((message) => messageRole(message) === "user" && (messageCreatedAt(message) ?? -Infinity) >= cutAt);
+ const kept = cut < 0 ? history.outline : history.outline.slice(0, cut);
+ const newestAssistant = [...kept].reverse().find((message) => messageRole(message) === "assistant");
+ const newestUser = [...kept].reverse().find((message) => messageRole(message) === "user");
+ // An answer that ended its step on tool calls goes on with another step.
+ const answered = isRecord(newestAssistant) && isFinishedAssistantMessage(newestAssistant)
+ && (isRecord(newestAssistant.info) ? newestAssistant.info.finish : newestAssistant.finish) !== "tool-calls"
+ && kept.indexOf(newestAssistant) > (newestUser === undefined ? -1 : kept.indexOf(newestUser));
+ if (cut < 0) return { history, found: false, answered };
+ const later = new Set(history.outline.slice(cut).map(traceMessageId).filter((id): id is string => id !== null));
+ const keep = history.delta.map((message) => !later.has(traceMessageId(message) ?? ""));
+ return {
+ history: {
+ outline: kept,
+ delta: history.delta.filter((_, index) => keep[index]),
+ sizes: history.sizes.filter((_, index) => keep[index]),
+ omitted: history.omitted,
+ },
+ found: true,
+ answered,
+ };
+}
+
/** Messages one trace flush carries, oldest first, and their JSON size. */
type MessagePart = { messages: unknown[]; bytes: number };
@@ -512,9 +646,10 @@ function statusPollDelay(elapsedMs: number): number {
* session, how many turns has it completed), made like the collector
* observer's: same engine, headers and query, never from the request path.
*/
-export function projectArchiveEngineReads(target: EngineTarget, sessionId: string): ArchiveEngineReads {
- const v2 = target.engine === "v2";
- const fetchEngine = engineFetch(() => target, () => AbortSignal.timeout(20_000));
+export function projectArchiveEngineReads(target: EngineTarget | (() => EngineTarget), sessionId: string): ArchiveEngineReads {
+ const current = typeof target === "function" ? target : () => target;
+ const v2 = current().engine === "v2";
+ const fetchEngine = engineFetch(current, () => AbortSignal.timeout(20_000));
const session = `${v2 ? "/api/session" : "/session"}/${encodeURIComponent(sessionId)}`;
return {
session: async () => {
@@ -563,13 +698,15 @@ export function observeCollectedSession(input: {
if (!input.collector.enabled) return Promise.resolve();
const observer = input.observers;
const { collector, sessionId } = input;
+ // A request that reached an engine since closed names it: its sessions are read from the one that took over.
+ const requestTarget = currentEngineTarget(observer, input.target);
const observed = observer.sessions.get(sessionId);
if (observed) {
- observed.target = input.target;
+ observed.target = requestTarget;
observed.requests += 1;
return observed.done;
}
- const session: ObservedSession = { target: input.target, requests: 0, done: Promise.resolve() };
+ const session: ObservedSession = { target: requestTarget, requests: 0, turn: null, done: Promise.resolve() };
observer.sessions.set(sessionId, session);
const timing: ObserverTiming = {
now: () => Date.now(),
@@ -591,10 +728,18 @@ export function observeCollectedSession(input: {
if (stopped.aborted) throw error;
return false;
};
- // Whether the turn's snapshot was taken, and whether the project archive
- // heard of the turn's end: a failure after either must not repeat it.
- let turnCaptured = false;
+ // Whether the project archive heard of the turn's end: a failure after it
+ // must not repeat it. Whether the turn's snapshot was taken is the
+ // followed turn's own (a prompt dispatched before it settled takes it).
let turnArchived = false;
+ const turnState = (): FollowedTurn => (session.turn ??= { snapshotTaken: false, cutAt: null });
+ /** The followed turn's turn_completed snapshot, unless it was taken already. */
+ const captureTurnSnapshot = (): void => {
+ const turn = turnState();
+ if (turn.snapshotTaken) return;
+ turn.snapshotTaken = true;
+ collector.captureSnapshot(sessionId, "turn_completed");
+ };
/** The session's status ("idle" when the engine does not list it); throws when the engine does not answer. */
const readStatus = async (): Promise<string> => {
@@ -617,12 +762,19 @@ export function observeCollectedSession(input: {
}
};
- /** Everything a settled turn records, in order: messages, subagents, the idle event, the snapshot, the trace and the archive delta. */
- const settle = async (status: string): Promise<void> => {
- let history: EngineHistory | null = null;
+ /**
+ * Everything a settled turn records, in order: messages, subagents, the
+ * idle event, the snapshot, the trace and the archive delta. `read` is the
+ * history when it was read already; a turn ended by the next prompt keeps
+ * only the messages from before that prompt.
+ */
+ const settle = async (status: string, read?: EngineHistory): Promise<void> => {
+ let history: EngineHistory | null = read ?? null;
let unavailable: Record<string, unknown> = { unavailable: true };
try {
- history = await readHistory();
+ history ??= await readHistory();
+ const cutAt = session.turn?.cutAt ?? null;
+ if (cutAt !== null) history = historyBefore(history, cutAt).history;
} catch (error) {
if (stopped.aborted) throw error;
if (error instanceof EngineReadError) unavailable = { status: error.status, unavailable: true };
@@ -679,8 +831,7 @@ export function observeCollectedSession(input: {
collector.recordTrace(sessionId, "session.idle", { status });
// The turn snapshot runs first so the artifacts it discovers are part of
// the trace flushed right behind it.
- turnCaptured = true;
- collector.captureSnapshot(sessionId, "turn_completed");
+ captureTurnSnapshot();
collector.flushTrace(sessionId, { messages: history ? newest.messages : unavailable });
// The delta's turn number is the engine's completed-turn count, which
// survives app restarts; without the messages the archiver numbers it
@@ -691,9 +842,10 @@ export function observeCollectedSession(input: {
/**
* Follows one turn until it settles: resolves with the requests counted
- * when the session was first seen idle, or null past the safety bound.
+ * when the session was first seen idle, "cut" when the next prompt ended
+ * it, or null past the safety bound.
*/
- const followTurn = async (): Promise<number | null> => {
+ const followTurn = async (): Promise<number | "cut" | null> => {
// A turn is running: the previous turn's idle final archive, if armed, is off.
input.archive.turnFollowed(sessionId);
const startedAt = timing.now();
@@ -705,7 +857,15 @@ export function observeCollectedSession(input: {
let failures = 0;
let unavailableSince: number | null = null;
let unavailableTraced = false;
+ let readTarget = session.target;
+ // When the observer first saw that the next prompt ended this turn.
+ let cutSeenAt: number | null = null;
while (timing.now() - startedAt < timing.maxTurnMs) {
+ // An engine that took over from a closed one is read at once, without the closed one's backoff.
+ if (session.target !== readTarget) {
+ readTarget = session.target;
+ failures = 0;
+ }
const elapsed = timing.now() - startedAt;
const delay = failures > 0
? Math.max(statusPollDelay(elapsed), Math.min(MAX_STATUS_RETRY_MS, 1_000 * 2 ** (failures - 1)))
@@ -732,6 +892,29 @@ export function observeCollectedSession(input: {
failures = 0;
unavailableSince = null;
unavailableTraced = false;
+ const cutAt = session.turn?.cutAt ?? null;
+ if (cutAt !== null) {
+ // The next prompt went out before this turn settled. The turn ends
+ // with the messages from before that prompt once they are all there:
+ // its answer finished (the session may be busy with the next turn),
+ // or the session is idle. A prompt the engine never recorded is not
+ // waited for long: the turn then settles as the engine left it.
+ cutSeenAt ??= timing.now();
+ let history: EngineHistory;
+ try {
+ history = await readHistory();
+ } catch (error) {
+ if (stopped.aborted) throw error;
+ continue;
+ }
+ const before = historyBefore(history, cutAt);
+ const waited = timing.now() - cutSeenAt;
+ if (before.found ? status === "idle" || before.answered : waited >= CUT_PROMPT_WAIT_MS) {
+ await settle(status, history);
+ return "cut";
+ }
+ continue;
+ }
if (status !== "idle") {
observedBusy = true;
idleReads = 0;
@@ -757,8 +940,7 @@ export function observeCollectedSession(input: {
// No longer followed, the turn still gets its snapshot and turn.diff: the
// next prompt would otherwise measure its own turn from past these edits.
// Its messages are left after the checkpoint for the next settled turn.
- turnCaptured = true;
- collector.captureSnapshot(sessionId, "turn_completed");
+ captureTurnSnapshot();
collector.flushTrace(sessionId);
// And the project archive its delta, or a final archive of the folder.
turnArchived = true;
@@ -770,16 +952,19 @@ export function observeCollectedSession(input: {
const checkpoint = await collector.sessionCheckpoint(sessionId);
if (checkpoint.lastMessageId) observer.lastMessageIds.set(sessionId, checkpoint.lastMessageId);
while (true) {
- turnCaptured = false;
+ session.turn = { snapshotTaken: false, cutAt: null };
turnArchived = false;
const requests = await followTurn();
+ session.turn = null;
+ // A turn ended by the next prompt is followed by that prompt's turn.
+ if (requests === "cut") continue;
// A request that came in once the session was idle (the next prompt) started a turn of its own.
if (requests === null || session.requests === requests) return;
}
})().catch((error: unknown) => {
if (!stopped.aborted) {
collector.recordTrace(sessionId, "session.observer_failed", { error: errorMessage(error) });
- if (!turnCaptured) collector.captureSnapshot(sessionId, "turn_completed");
+ if (!session.turn?.snapshotTaken) collector.captureSnapshot(sessionId, "turn_completed");
collector.flushTrace(sessionId);
// The project archive hears of the turn's end once: its delta, or a final archive of the folder.
if (!turnArchived) input.archive.turnIncomplete(sessionId);
diff --git a/apps/server/src/engine-pool.test.ts b/apps/server/src/engine-pool.test.ts
index 05332942..166b963b 100644
--- a/apps/server/src/engine-pool.test.ts
+++ b/apps/server/src/engine-pool.test.ts
@@ -26,6 +26,8 @@ const ENV_NAMES = [
"OMNIRUSH_ENGINE_MIN_SPAWN_INTERVAL_MS",
"OMNIRUSH_POOL_LOG",
"OMNIRUSH_POOL_STATE",
+ "OMNIRUSH_ENGINE_DRAIN_REQUEST_GRACE_MS",
+ "OMNIRUSH_ENGINE_PROMPT_START_GRACE_MS",
];
const cleanups: Array<() => void | Promise<void>> = [];
@@ -90,9 +92,12 @@ async function writeFakeEngineBin(root: string): Promise<string> {
"const server = Bun.serve({",
" hostname: '127.0.0.1',",
" port: requestedPort,",
- " fetch(request) {",
+ " async fetch(request) {",
" const url = new URL(request.url);",
" append(`${server.port} ${request.method} ${url.pathname}`);",
+ " // A slow answer (a session create waiting on a cold instance).",
+ " const delay = Number(url.searchParams.get('delay') ?? 0);",
+ " if (delay > 0) await Bun.sleep(delay);",
" if (url.pathname === '/session/status') {",
" const entries = busySessions(server.port, url.searchParams.get('directory')).map((id) => [id, { type: 'busy' }]);",
" return Response.json(Object.fromEntries(entries));",
@@ -759,6 +764,136 @@ describe("engine pool", () => {
expect(events).toContain(`"sessionID":"ses_${newPort}"`);
});
+ test("a drained engine stays up while a request to it is in flight, and names the engine that took over before it closes", async () => {
+ const fixture = await createFixture();
+ const replaced: Array<{ closed: string; replacement: string; aliveWhenTold: boolean }> = [];
+ let first: ManagedOpencodeServer | null = null;
+ fixture.hooks.onEngineReplaced = (closed, replacement) => {
+ replaced.push({ closed, replacement: replacement.baseUrl, aliveWhenTold: first?.isAlive() === true });
+ };
+ const { pool, primary } = await createPool(fixture);
+ first = primary;
+ // A session create went to the engine before the model catalog reload flipped it.
+ const release = pool.beginRequest(primary.url);
+ await fixture.setRuntimeConfig(JSON.stringify({ generation: 2 }));
+
+ const outcome = await pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace, forceStandby: true });
+
+ expect(outcome).toMatchObject({ action: "rolled_over", drainingSessions: 0 });
+ // Idle, yet not closed under the request.
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ expect(primary.isAlive()).toBe(true);
+ release();
+ expect(await waitUntil(() => !primary.isAlive(), 5_000)).toBe(true);
+ expect(replaced).toEqual([{ closed: primary.url, replacement: pool.primaryUrl() ?? "", aliveWhenTold: true }]);
+ });
+
+ test("a prompt the engine accepted but has not started when the catalog reload flips drains with it instead of being dropped", async () => {
+ const fixture = await createFixture();
+ const { pool, primary } = await createPool(fixture);
+ const oldPort = portOf(primary.url);
+ // The prompt was answered (204) before its run started: the engine does not report the session busy yet.
+ pool.beginRequest(primary.url, { method: "POST", proxyPath: "/session/ses_starting/prompt_async" })();
+ await fixture.setRuntimeConfig(JSON.stringify({ generation: 2 }));
+
+ const outcome = await pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace, forceStandby: true });
+
+ expect(outcome).toMatchObject({ action: "rolled_over", drainingSessions: 1 });
+ expect(pool.routeRequest("GET", "/session/ses_starting/message")?.target.baseUrl).toBe(primary.url);
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ expect(primary.isAlive()).toBe(true);
+ // The run starts, then ends: the engine closes once it is idle.
+ await fixture.setBusy(oldPort, ["ses_starting"]);
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(primary.isAlive()).toBe(true);
+ await fixture.setBusy(oldPort, []);
+ expect(await waitUntil(() => !primary.isAlive(), 5_000)).toBe(true);
+ });
+
+ test("a prompt that never starts holds a drained engine only for the start grace period", async () => {
+ const fixture = await createFixture();
+ setEnv("OMNIRUSH_ENGINE_PROMPT_START_GRACE_MS", "500");
+ const { pool, primary } = await createPool(fixture);
+ pool.beginRequest(primary.url, { method: "POST", proxyPath: "/session/ses_never/prompt_async" })();
+ await fixture.setRuntimeConfig(JSON.stringify({ generation: 2 }));
+ expect(await pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace, forceStandby: true }))
+ .toMatchObject({ action: "rolled_over", drainingSessions: 1 });
+ expect(await waitUntil(() => !primary.isAlive(), 5_000)).toBe(true);
+ });
+
+ test("a request that never answers holds a drained engine only for the grace period", async () => {
+ const fixture = await createFixture();
+ setEnv("OMNIRUSH_ENGINE_DRAIN_REQUEST_GRACE_MS", "300");
+ const { pool, primary } = await createPool(fixture);
+ pool.beginRequest(primary.url);
+ await fixture.setRuntimeConfig(JSON.stringify({ generation: 2 }));
+ expect((await pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace, forceStandby: true })).action)
+ .toBe("rolled_over");
+ expect(await waitUntil(() => !primary.isAlive(), 5_000)).toBe(true);
+ });
+
+ test("a session created while the startup catalog reload rolls the engine over is answered, never a 500", async () => {
+ const fixture = await createFixture();
+ const { pool, primary } = await createPool(fixture);
+ const oldPort = portOf(primary.url);
+ // The create waits on the old engine's cold instance while the reload flips to a standby.
+ const url = new URL("http://127.0.0.1/opencode/session?delay=2500");
+ const create = proxyOpencodeRequest({
+ config: fixture.config,
+ request: new Request(url, { method: "POST", body: JSON.stringify({ title: "new" }), headers: { "content-type": "application/json" } }),
+ url,
+ workspace: fixture.workspace,
+ proxyPath: "/session",
+ });
+ const settled = create.then(() => "answered", () => "failed");
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ await fixture.setRuntimeConfig(JSON.stringify({ generation: 2 }));
+
+ expect((await pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace, forceStandby: true })).action)
+ .toBe("rolled_over");
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(await Promise.race([settled, Promise.resolve("pending")])).toBe("pending");
+
+ const response = await create;
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ port: oldPort, path: "/session" });
+ // Then the drained engine closes.
+ expect(await waitUntil(() => !primary.isAlive(), 5_000)).toBe(true);
+ });
+
+ test("a request that finds its engine gone mid-rollover is sent again to the engine that took over", async () => {
+ const fixture = await createFixture();
+ let flip: () => void = () => undefined;
+ const flipped = new Promise<void>((resolve) => { flip = resolve; });
+ let standbyReady: () => void = () => undefined;
+ const standbyHealthy = new Promise<void>((resolve) => { standbyReady = resolve; });
+ fixture.hooks.prepareStandby = async () => {
+ standbyReady();
+ await flipped;
+ };
+ const { pool, primary } = await createPool(fixture);
+ await fixture.setRuntimeConfig(JSON.stringify({ generation: 2 }));
+ const rollover = pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace, forceStandby: true });
+ await standbyHealthy;
+ // The old engine is gone before the flip; a request is routed to it all the same.
+ await primary.close();
+ const url = new URL("http://127.0.0.1/opencode/session");
+ const create = proxyOpencodeRequest({
+ config: fixture.config,
+ request: new Request(url, { method: "POST", body: "{}", headers: { "content-type": "application/json" } }),
+ url,
+ workspace: fixture.workspace,
+ proxyPath: "/session",
+ });
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ flip();
+ expect((await rollover).action).toBe("rolled_over");
+
+ const response = await create;
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ port: portOf(pool.primaryUrl() ?? "http://127.0.0.1:0"), path: "/session" });
+ });
+
test("returns a controlled 502 when the selected engine is unreachable", async () => {
const fixture = await createFixture();
const { primary } = await createPool(fixture);
diff --git a/apps/server/src/engine-pool.ts b/apps/server/src/engine-pool.ts
index f1287414..bd544b68 100644
--- a/apps/server/src/engine-pool.ts
+++ b/apps/server/src/engine-pool.ts
@@ -95,6 +95,13 @@ export type EnginePoolHooks = {
onPrimaryLost?: (config: ServerConfig) => void;
/** Called once when the pool shuts down, before its engines are retired. */
onDisposed?: () => void;
+ /**
+ * Called when an engine is closed while another serves (a drained
+ * generation retired, a dead primary replaced), before it closes: whatever
+ * still reads the closed engine (the collector's turn observers) moves to
+ * `replacement`, which reads the same sessions from the shared database.
+ */
+ onEngineReplaced?: (closedBaseUrl: string, replacement: EnginePoolConnection) => void;
logger?: EnginePoolLogger;
};
@@ -119,6 +126,10 @@ type Generation = {
drainTimer: ReturnType<typeof setInterval> | null;
drainDeadline: number | null;
drainActivityWatch: AbortController | null;
+ /** Proxied requests in flight to this engine (a drained engine closes only once they answered, or a grace period passed). */
+ requestsInFlight: number;
+ /** Re-runs the drain check (set while draining). */
+ drainCheck: (() => void) | null;
};
export type EnginePoolSnapshot = {
@@ -176,6 +187,24 @@ function drainTimeoutMs(): number {
return positiveIntFromEnv("OMNIRUSH_ENGINE_DRAIN_TIMEOUT_MS", 15 * 60_000);
}
+/**
+ * How long a drained engine stays up for proxied requests still in flight to
+ * it (a session create waiting on the instance's cold boot) before it closes
+ * anyway.
+ */
+function drainRequestGraceMs(): number {
+ return nonNegativeIntFromEnv("OMNIRUSH_ENGINE_DRAIN_REQUEST_GRACE_MS", 60_000);
+}
+
+/**
+ * How long a session an engine was just sent a prompt for counts as running
+ * there before the engine reports it (the engine accepts a prompt before its
+ * run starts, which may wait on the folder's instance booting).
+ */
+function promptStartGraceMs(): number {
+ return nonNegativeIntFromEnv("OMNIRUSH_ENGINE_PROMPT_START_GRACE_MS", 60_000);
+}
+
/** Delay before the drain activity watch reconnects to a lost engine event stream. */
function drainActivityReconnectMs(): number {
return positiveIntFromEnv("OMNIRUSH_ENGINE_DRAIN_ACTIVITY_RECONNECT_MS", 1_000);
@@ -226,14 +255,15 @@ export function isEngineConnectionFailure(error: unknown): boolean {
let current: unknown = error;
for (let depth = 0; depth < 6 && current !== null && current !== undefined; depth += 1) {
if (typeof current === "string") {
- return /ECONNREFUSED|ECONNRESET|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|UND_ERR_HEADERS_TIMEOUT|socket hang up|Unable to connect|Headers Timeout Error/i.test(current);
+ return /ECONNREFUSED|ECONNRESET|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|UND_ERR_HEADERS_TIMEOUT|UND_ERR_SOCKET|other side closed|socket hang up|Unable to connect|Headers Timeout Error/i.test(current);
}
if (!isRecord(current) || visited.has(current)) return false;
visited.add(current);
const code = current.code;
- if (code === "ECONNREFUSED" || code === "ECONNRESET" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "UND_ERR_HEADERS_TIMEOUT") return true;
+ // UND_ERR_SOCKET ("other side closed"): the engine closed the connection before it answered.
+ if (code === "ECONNREFUSED" || code === "ECONNRESET" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "UND_ERR_HEADERS_TIMEOUT" || code === "UND_ERR_SOCKET") return true;
const message = current.message;
- if (typeof message === "string" && /ECONNREFUSED|ECONNRESET|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|UND_ERR_HEADERS_TIMEOUT|socket hang up|Unable to connect|Headers Timeout Error/i.test(message)) return true;
+ if (typeof message === "string" && /ECONNREFUSED|ECONNRESET|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|UND_ERR_HEADERS_TIMEOUT|UND_ERR_SOCKET|other side closed|socket hang up|Unable to connect|Headers Timeout Error/i.test(message)) return true;
current = current.cause;
}
return false;
@@ -252,6 +282,14 @@ export function isConnectionRefusedClassError(error: unknown): boolean {
return isEngineConnectionFailure(error);
}
+function sameOrigin(left: string, right: string): boolean {
+ try {
+ return new URL(left).origin === new URL(right).origin;
+ } catch {
+ return left === right;
+ }
+}
+
function isRoutableGeneration(
generation: Generation,
): generation is Generation & { status: "primary" | "draining" } {
@@ -428,6 +466,12 @@ export class EnginePool {
private readonly activeSessionsByGeneration = new Map<string, Set<string>>();
private readonly eventProxyControllers = new Set<AbortController>();
private readonly drainWaiters = new Set<() => void>();
+ /**
+ * Prompts sent to an engine whose session it may not report busy yet (the
+ * engine answers a prompt before its run starts), by session: the engine
+ * they went to and when. Such a session drains like a running one.
+ */
+ private readonly startingPrompts = new Map<string, { generationId: string; at: number }>();
constructor(input: { config: ServerConfig; template: EngineSpawnTemplate; hooks: EnginePoolHooks }) {
this.config = input.config;
@@ -456,6 +500,8 @@ export class EnginePool {
drainTimer: null,
drainDeadline: null,
drainActivityWatch: null,
+ requestsInFlight: 0,
+ drainCheck: null,
});
this.lastSpawnAt = Date.now();
}
@@ -490,6 +536,49 @@ export class EnginePool {
void this.recoverDeadPrimary(workspace).catch(() => undefined);
}
+ /**
+ * A proxied request to `baseUrl` is going out: a draining engine is not
+ * closed under it (for at most OMNIRUSH_ENGINE_DRAIN_REQUEST_GRACE_MS).
+ * Call the returned release once the engine answered or the request failed.
+ */
+ beginRequest(baseUrl: string, request?: { method: string; proxyPath: string }): () => void {
+ const generation = this.generationForUrl(baseUrl);
+ if (!generation) return () => undefined;
+ const sessionId = request && isPromptishSessionRequest(request.method, request.proxyPath) ? sessionIdFromPath(request.proxyPath) : null;
+ if (sessionId) this.noteStartingPrompt(generation, sessionId);
+ generation.requestsInFlight += 1;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ generation.requestsInFlight = Math.max(0, generation.requestsInFlight - 1);
+ if (generation.requestsInFlight === 0 && generation.status === "draining") generation.drainCheck?.();
+ };
+ }
+
+ /**
+ * After a proxied request to `failedBaseUrl` failed to connect: the route
+ * to retry it on once a rollover moved the engine it went to (that engine
+ * is no longer serving, or a new primary took over while it was being
+ * replaced). Waits for a rollover in flight to flip, at most `timeoutMs`.
+ * Null when there is nothing to retry on: the engine it went to is still
+ * the one serving.
+ */
+ async rerouteAfterFailure(method: string, proxyPath: string, failedBaseUrl: string, timeoutMs: number): Promise<EnginePoolRoute | null> {
+ const deadline = this.now() + timeoutMs;
+ while (!this.disposed) {
+ const route = this.routeRequest(method, proxyPath);
+ if (route && !sameOrigin(route.target.baseUrl, failedBaseUrl)) return route;
+ // The engine it went to still serves: only a rollover (or a recovery) in flight can replace it.
+ if ((!this.inFlight && !this.recoveryInFlight) || this.now() >= deadline) return null;
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, 100);
+ timer.unref?.();
+ });
+ }
+ return null;
+ }
+
connections(): EnginePoolConnection[] {
return this.generations
.filter(isRoutableGeneration)
@@ -793,6 +882,8 @@ export class EnginePool {
drainTimer: null,
drainDeadline: null,
drainActivityWatch: null,
+ requestsInFlight: 0,
+ drainCheck: null,
};
this.generations.push(generation);
@@ -845,7 +936,8 @@ export class EnginePool {
}).catch(() => undefined);
}
- const drainingSessions = await this.nonIdleSessionIds(primary);
+ // A prompt the primary accepted but has not started yet drains with it too.
+ const drainingSessions = this.withStartingPrompts(primary, await this.nonIdleSessionIds(primary));
const pinnedRequestIds = await this.pendingRequestIds(primary);
this.flip(generation, primary, drainingSessions, pinnedRequestIds);
@@ -932,14 +1024,23 @@ export class EnginePool {
private startDrainMonitor(generation: Generation, workspace: WorkspaceInfo): void {
generation.drainDeadline = Date.now() + drainTimeoutMs();
this.watchDrainActivity(generation);
+ // When the drained engine was first found idle with requests still in flight to it.
+ let idleWithRequestsSince: number | null = null;
const tick = async (): Promise<void> => {
if (generation.status !== "draining") return;
- const remaining = await this.nonIdleSessionIds(generation);
+ const remaining = this.withStartingPrompts(generation, await this.nonIdleSessionIds(generation));
this.updateActiveSessions(generation, remaining);
if (remaining.length === 0) {
+ // A request it still serves (a session create waiting on a cold
+ // instance) would fail mid-flight: it closes once they answered.
+ if (generation.requestsInFlight > 0) {
+ idleWithRequestsSince ??= this.now();
+ if (this.now() - idleWithRequestsSince < drainRequestGraceMs()) return;
+ }
await this.retire(generation, "idle");
return;
}
+ idleWithRequestsSince = null;
if (generation.drainDeadline !== null && Date.now() >= generation.drainDeadline) {
this.hooks.logger?.log("warn", "Engine drain saw no session activity for the grace period; aborting the remaining sessions.", {
"engine.drain.sessions": remaining.join(","),
@@ -955,6 +1056,7 @@ export class EnginePool {
const timer = setInterval(() => void tick().catch(() => undefined), drainPollIntervalMs());
timer.unref?.();
generation.drainTimer = timer;
+ generation.drainCheck = () => void tick().catch(() => undefined);
// Sessions can finish between the flip and the first poll.
void tick().catch(() => undefined);
}
@@ -1051,7 +1153,9 @@ export class EnginePool {
generation.drainActivityWatch?.abort();
generation.drainActivityWatch = null;
generation.drainDeadline = null;
+ generation.drainCheck = null;
this.activeSessionsByGeneration.delete(generation.id);
+ if (cause !== "shutdown") this.notifyEngineReplaced(generation);
for (const [sessionId, generationId] of this.sessionOwnership) {
if (generationId === generation.id) this.sessionOwnership.delete(sessionId);
}
@@ -1209,6 +1313,8 @@ export class EnginePool {
drainTimer: null,
drainDeadline: null,
drainActivityWatch: null,
+ requestsInFlight: 0,
+ drainCheck: null,
};
this.generations.push(generation);
if (handle.pid) {
@@ -1228,6 +1334,7 @@ export class EnginePool {
}
this.flip(generation, null, [], []);
replacement = null;
+ if (previous) this.notifyEngineReplaced(previous);
this.consecutiveConnectionFailures = 0;
this.recoveryWorkspace = null;
if (this.recoveryTimer) clearTimeout(this.recoveryTimer);
@@ -1326,6 +1433,51 @@ export class EnginePool {
return this.hooks.now?.() ?? Date.now();
}
+ private noteStartingPrompt(generation: Generation, sessionId: string): void {
+ const now = this.now();
+ for (const [id, entry] of this.startingPrompts) {
+ if (now - entry.at >= promptStartGraceMs()) this.startingPrompts.delete(id);
+ }
+ this.startingPrompts.set(sessionId, { generationId: generation.id, at: now });
+ }
+
+ /**
+ * `nonIdle` (the sessions `generation` reports running) plus those it was
+ * sent a prompt for within the start grace period and has not reported
+ * running yet. A session seen running is tracked by its status from then on.
+ */
+ private withStartingPrompts(generation: Generation | null, nonIdle: string[]): string[] {
+ if (!generation) return nonIdle;
+ const sessions = new Set(nonIdle);
+ const now = this.now();
+ for (const [sessionId, entry] of this.startingPrompts) {
+ if (entry.generationId !== generation.id) continue;
+ if (sessions.has(sessionId) || now - entry.at >= promptStartGraceMs()) {
+ this.startingPrompts.delete(sessionId);
+ continue;
+ }
+ sessions.add(sessionId);
+ }
+ return [...sessions];
+ }
+
+ /** Tells the pool's owner that `closed` is going away and which engine serves its sessions now. */
+ private notifyEngineReplaced(closed: Generation): void {
+ const primary = this.generations.find(
+ (entry): entry is Generation & { status: "primary" } => entry.status === "primary" && entry.id !== closed.id,
+ );
+ if (!primary || !this.hooks.onEngineReplaced) return;
+ try {
+ this.hooks.onEngineReplaced(closed.handle.url, this.connectionFor(primary));
+ } catch {
+ // Advisory: closing the engine never waits on its readers.
+ }
+ }
+
+ private generationForUrl(baseUrl: string): Generation | null {
+ return this.generations.find((entry) => entry.status !== "dead" && sameOrigin(entry.handle.url, baseUrl)) ?? null;
+ }
+
private isPrimaryEndpoint(baseUrl: string): boolean {
try {
const primary = this.primaryUrl();
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index bc0d90ab..069bfa46 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1501,7 +1501,7 @@ export async function proxyOpencodeV2Request(input: {
const engine = capture && collectedSessionId ? engineTarget(input.connection.url, headers, target.search, "v2") : null;
if (capture && collectedSessionId && engine) {
capture.startSession(collectedSessionId, input.workspace.id, input.workspace.path);
- capture.recordPrompt(collectedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true });
+ capture.recordPrompt(collectedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true, dispatchedAt: Date.now() });
capture.captureSnapshot(collectedSessionId, "prompt");
capture.archiveSessionStarted(collectedSessionId, input.workspace.path, engine);
}
@@ -1616,6 +1616,38 @@ export async function proxyOpencodeV2Request(input: {
return sanitizeProxyResponse(response);
}
+/** How many times a proxied request an engine rollover cut off is sent again. */
+const ENGINE_ROLLOVER_RETRIES = 2;
+
+/** How long a request that failed on an engine being replaced waits for the replacement to serve. */
+function engineRolloverRetryWaitMs(): number {
+ const configured = Number(process.env.OMNIRUSH_ENGINE_ROLLOVER_RETRY_WAIT_MS);
+ return Number.isFinite(configured) && configured >= 0 ? configured : 30_000;
+}
+
+/**
+ * Whether a proxied request that failed to reach its engine may be sent
+ * again to the engine that took over. A request that starts a turn is sent
+ * again only when the engine never received it (nothing listened on its
+ * port); any other request may have been cut off mid-flight and is sent again.
+ */
+function engineRolloverRetryable(method: string, proxyPath: string, error: unknown): boolean {
+ if (!isEngineConnectionFailure(error)) return false;
+ const startsTurn = method === "POST"
+ && /^\/session\/[^/]+\/(?:message|prompt|prompt_async|command|shell)$/.test(normalizeOpencodeProxyPath(proxyPath));
+ return !startsTurn || engineNeverReceivedRequest(error);
+}
+
+function engineNeverReceivedRequest(error: unknown): boolean {
+ let current: unknown = error;
+ for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth += 1) {
+ const code = (current as { code?: unknown }).code;
+ if (code === "ECONNREFUSED" || code === "UND_ERR_CONNECT_TIMEOUT") return true;
+ current = (current as { cause?: unknown }).cause;
+ }
+ return false;
+}
+
function opencodeUnreachableError(error: unknown, path: string): ApiError {
return new ApiError(502, "opencode_unreachable", "OpenCode engine is unavailable", {
path,
@@ -1822,6 +1854,8 @@ export async function proxyOpencodeRequest(input: {
engine: "v1",
root: workspace.path,
attachments: promptDispatch,
+ // Taken before the engine sees the prompt: the session's previous turn ends here.
+ ...(promptDispatch ? { dispatchedAt: Date.now() } : {}),
});
if (promptDispatch) {
capture.captureSnapshot(collectedSessionId, "prompt");
@@ -1880,6 +1914,8 @@ export async function proxyOpencodeRequest(input: {
return jsonResponse(true);
}
const targetUrl = buildOpencodeProxyUrl(baseUrl, proxyPath, search);
+ // The engine that answered: a request an engine rollover cut off is sent again to the engine that took over.
+ let served = { baseUrl, headers };
// Managed OpenCode proxy traffic is loopback/engine I/O; keep streaming on Node fetch.
if (isSessionCommandProxyRequest(method, proxyPath)) {
const commandAdmission = commandAdmissionFromBody(body);
@@ -1898,11 +1934,12 @@ export async function proxyOpencodeRequest(input: {
}, 409);
}
}
+ const release = pool?.beginRequest(baseUrl, { method, proxyPath: decodeEngineRoutePath(proxyPath) });
void loopbackFetch(targetUrl, {
method,
headers,
body,
- }).then((response) => {
+ }).finally(() => release?.()).then((response) => {
enginePoolForConfig(input.config)?.reportRequestSuccess(baseUrl);
if (capture?.collectorEnabled && collectedSessionId) {
capture.recordTrace(collectedSessionId, "engine.response", {
@@ -1927,13 +1964,33 @@ export async function proxyOpencodeRequest(input: {
}
const forward = async () => {
let response: Response;
- try {
- response = await loopbackFetch(targetUrl, { method, headers, body, signal: input.recoverySignal });
- enginePoolForConfig(input.config)?.reportRequestSuccess(baseUrl);
- } catch (error) {
- if (workspace) enginePoolForConfig(input.config)?.reportRequestFailure(baseUrl, error, workspace);
- if (isEngineConnectionFailure(error)) throw opencodeUnreachableError(error, proxyPath);
- throw error;
+ for (let attempt = 0; ; attempt += 1) {
+ const release = pool?.beginRequest(served.baseUrl, { method, proxyPath: decodeEngineRoutePath(proxyPath) });
+ try {
+ response = attempt === 0
+ ? await loopbackFetch(targetUrl, { method, headers, body, signal: input.recoverySignal })
+ : await loopbackFetch(buildOpencodeProxyUrl(served.baseUrl, proxyPath, search), { method, headers: served.headers, body, signal: input.recoverySignal });
+ enginePoolForConfig(input.config)?.reportRequestSuccess(served.baseUrl);
+ break;
+ } catch (error) {
+ if (workspace) enginePoolForConfig(input.config)?.reportRequestFailure(served.baseUrl, error, workspace);
+ const reroute = pool && attempt < ENGINE_ROLLOVER_RETRIES && !input.request.signal.aborted && !input.recoverySignal?.aborted
+ && engineRolloverRetryable(method, proxyPath, error)
+ ? await pool.rerouteAfterFailure(method, decodeEngineRoutePath(proxyPath), served.baseUrl, engineRolloverRetryWaitMs())
+ : null;
+ if (!reroute) {
+ if (isEngineConnectionFailure(error)) throw opencodeUnreachableError(error, proxyPath);
+ throw error;
+ }
+ createServerLogger(input.config).log("info", "Engine request retried on the engine that took over.", {
+ "engine.retry.path": normalizeOpencodeProxyPath(proxyPath),
+ "engine.retry.attempt": attempt + 1,
+ "engine.retry.cause": error instanceof Error ? error.message : String(error),
+ });
+ served = { baseUrl: reroute.target.baseUrl, headers: headersForEngineConnection(headers, reroute.target) };
+ } finally {
+ release?.();
+ }
}
if (response.status === 404 && route?.fallback) {
@@ -1963,7 +2020,7 @@ export async function proxyOpencodeRequest(input: {
path: normalizeOpencodeProxyPath(proxyPath),
status: response.status,
});
- if (workspace && response.ok) capture.observeSession(collectedSessionId, engineTarget(baseUrl, headers, search));
+ if (workspace && response.ok) capture.observeSession(collectedSessionId, engineTarget(served.baseUrl, served.headers, search));
}
if (capture?.collectorEnabled && deletedCollectedSessionId && response.ok) capture.sessionDeleted(deletedCollectedSessionId);
return response;
@@ -5843,6 +5900,13 @@ export function createEnginePoolForConfig(input: {
reloadOpencodeEngineInPlace(poolConfig, workspace, undefined, options),
engineBusy: (poolConfig, workspace) => engineHasActiveSessions(poolConfig, workspace, true),
onPrimaryLost: (poolConfig) => requeueTaskRecoveryAfterEngineLoss(poolConfig),
+ // Turn observers still reading a closed engine read the sessions from the one that took over.
+ onEngineReplaced: (closedBaseUrl, replacement) => {
+ captureServicesByServer.get(config)?.engineReplaced(closedBaseUrl, {
+ baseUrl: replacement.baseUrl,
+ authorization: buildEngineAuthProbeHeader(replacement.username, replacement.password),
+ });
+ },
postRefreshSync: async (poolConfig, workspace) => {
await postEngineRefreshSync(poolConfig, workspace, activeEngineMcpServerState(poolConfig));
await syncAllWorkspacesRuntimeMcpToEngine(poolConfig);