diff --git a/server/src/services/adapter-execution-control.test.ts b/server/src/services/adapter-execution-control.test.ts index 7167e51f249..cc030434897 100644 --- a/server/src/services/adapter-execution-control.test.ts +++ b/server/src/services/adapter-execution-control.test.ts @@ -5,6 +5,7 @@ import { captureAdapterStopOwnership, createAdapterExecutionControl, registerAdapterExecutionControl, + reportAdapterStopIfUnsettled, waitForAdapterStop, } from "./adapter-execution-control.js"; @@ -204,3 +205,72 @@ it.each(["replaced", "wrong_run", "wrong_promise", "throwing_reader"])("omits pe other.finish(); adapterExecutionControls.delete(runId); }); + +it("reports a Stop once, with its pending phase, only when it stays unsettled", async () => { + vi.useFakeTimers(); + const runId = "11111111-1111-4111-8111-111111111111"; + const control = createAdapterExecutionControl(); + await registerAdapterExecutionControl(runId, control); + const report = vi.fn(); + try { + control.phases.enter("workspace_restore"); + reportAdapterStopIfUnsettled(control.settled, report, { runId, adapterType: "codex_local" }, control, { reportAfterMs: 5000 }); + // A repeated Stop for the same execution must not add another report. + reportAdapterStopIfUnsettled(control.settled, report, { runId }, control, { reportAfterMs: 5000 }); + await vi.advanceTimersByTimeAsync(4999); + expect(report).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(report).toHaveBeenCalledOnce(); + const error = report.mock.calls[0]![0] as AdapterStopTimeoutError; + expect(error).toBeInstanceOf(AdapterStopTimeoutError); + expect(error.diagnostics).toMatchObject({ + runId, adapterType: "codex_local", timeoutMs: 5000, phase: "workspace_restore", phaseElapsedMs: expect.any(Number), + }); + expect(vi.getTimerCount()).toBe(0); + expect(adapterExecutionControls.get(runId)).toBe(control); + } finally { + control.finish(); + adapterExecutionControls.delete(runId); + } +}); + +it("does not report a Stop that settles before the report bound", async () => { + vi.useFakeTimers(); + const control = createAdapterExecutionControl(); + const report = vi.fn(); + reportAdapterStopIfUnsettled(control.settled, report, undefined, control, { reportAfterMs: 5000 }); + await vi.advanceTimersByTimeAsync(1000); + control.finish(); + await control.settled; + expect(vi.getTimerCount()).toBe(0); + await vi.advanceTimersByTimeAsync(10_000); + expect(report).not.toHaveBeenCalled(); +}); + +it("measures the report bound from the Stop request, including its response wait", async () => { + vi.useFakeTimers(); + const control = createAdapterExecutionControl(); + const report = vi.fn(); + const stopRequestedAt = Date.now(); + // The Stop request's own response wait elapses before the watch starts. + const responseWait = stopTimeout(waitForAdapterStop(control.settled, 2000)); + await vi.advanceTimersByTimeAsync(2000); + await responseWait; + reportAdapterStopIfUnsettled(control.settled, report, undefined, control, { stopRequestedAt, reportAfterMs: 5000 }); + await vi.advanceTimersByTimeAsync(2999); + expect(report).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(report).toHaveBeenCalledOnce(); + expect((report.mock.calls[0]![0] as AdapterStopTimeoutError).diagnostics).toMatchObject({ timeoutMs: 5000 }); + control.finish(); +}); + +it("keeps a failing reporter from escaping its timer", async () => { + vi.useFakeTimers(); + const control = createAdapterExecutionControl(); + const report = vi.fn(() => { throw new Error("reporter down"); }); + reportAdapterStopIfUnsettled(control.settled, report, undefined, undefined, { reportAfterMs: 1000 }); + await vi.advanceTimersByTimeAsync(1000); + expect(report).toHaveBeenCalledOnce(); + control.finish(); +}); diff --git a/server/src/services/adapter-execution-control.ts b/server/src/services/adapter-execution-control.ts index 06f60cab9fb..9b1b9f17d08 100644 --- a/server/src/services/adapter-execution-control.ts +++ b/server/src/services/adapter-execution-control.ts @@ -68,9 +68,9 @@ export async function registerAdapterExecutionControl( adapterExecutionControls.set(runId, control); } -export async function waitForAdapterStop( +function adapterStopTimeoutError( settled: Promise, - timeoutMs = 60_000, + timeoutMs: number, diagnostics?: AdapterStopContext, owner?: ReturnType, ) { @@ -83,21 +83,27 @@ export async function waitForAdapterStop( return null; } }; + return new AdapterStopTimeoutError(timeoutMs, { + ...diagnostics, + phase: undefined, + phaseElapsedMs: undefined, + ...currentPhase(), + }); +} + +export async function waitForAdapterStop( + settled: Promise, + timeoutMs = 60_000, + diagnostics?: AdapterStopContext, + owner?: ReturnType, +) { let timer: ReturnType | undefined; try { await Promise.race([ settled, new Promise((_, reject) => { timer = setTimeout( - () => - reject( - new AdapterStopTimeoutError(timeoutMs, { - ...diagnostics, - phase: undefined, - phaseElapsedMs: undefined, - ...currentPhase(), - }), - ), + () => reject(adapterStopTimeoutError(settled, timeoutMs, diagnostics, owner)), timeoutMs, ); }), @@ -106,3 +112,42 @@ export async function waitForAdapterStop( clearTimeout(timer); } } + +// A Stop request's wait is a response budget, not the adapter's settlement +// bound: workspace sync-back and cooperative provider cancellation routinely +// settle a few minutes after it. Only a Stop still unsettled this long after +// it was requested is an operational failure worth reporting. +export const UNSETTLED_ADAPTER_STOP_REPORT_MS = 10 * 60_000; +const watchedAdapterStops = new WeakSet>(); + +/** Reports at most once per execution, and only if it never settles in time. */ +export function reportAdapterStopIfUnsettled( + settled: Promise, + report: (error: AdapterStopTimeoutError) => void, + diagnostics?: AdapterStopContext, + owner?: ReturnType, + { + stopRequestedAt = Date.now(), + reportAfterMs = UNSETTLED_ADAPTER_STOP_REPORT_MS, + }: { stopRequestedAt?: number; reportAfterMs?: number } = {}, +) { + if (watchedAdapterStops.has(settled)) return; + watchedAdapterStops.add(settled); + let done = false; + // The bound runs from the Stop request, which already spent its response wait. + const remainingMs = Math.max(0, stopRequestedAt + reportAfterMs - Date.now()); + const timer = setTimeout(() => { + if (done) return; + try { + report(adapterStopTimeoutError(settled, reportAfterMs, diagnostics, owner)); + } catch { + // Reporting is diagnostic only. + } + }, remainingMs); + // Never hold process shutdown open for a diagnostic. + timer.unref?.(); + void settled.then(() => { + done = true; + clearTimeout(timer); + }); +} diff --git a/server/src/services/heartbeat/run-control.test.ts b/server/src/services/heartbeat/run-control.test.ts index 0234f326f48..d140f7f234d 100644 --- a/server/src/services/heartbeat/run-control.test.ts +++ b/server/src/services/heartbeat/run-control.test.ts @@ -5,7 +5,15 @@ import { eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { runningProcesses } from "../../adapters/index.js"; -import { adapterExecutionControls } from "../adapter-execution-control.js"; +import { + adapterExecutionControls, + createAdapterExecutionControl, + reportAdapterStopIfUnsettled, + waitForAdapterStop, +} from "../adapter-execution-control.js"; +import { AdapterStopTimeoutError } from "../adapter-stop-timeout.js"; +import { HttpError } from "../../errors.js"; +import { captureException } from "../../sentry.js"; import { terminateLocalService } from "../local-service-supervisor.js"; import { createHeartbeatRunState } from "./run-state.js"; import { createHeartbeatRunPreparation } from "./run-preparation.js"; @@ -13,6 +21,14 @@ import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from ". import { createHeartbeatRunControl, type HeartbeatRunControlDependencies } from "./run-control.js"; vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() })); +vi.mock("../adapter-execution-control.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + waitForAdapterStop: vi.fn(actual.waitForAdapterStop), + reportAdapterStopIfUnsettled: vi.fn(actual.reportAdapterStopIfUnsettled), + }; +}); vi.mock("../local-service-supervisor.js", async (importOriginal) => ({ ...await importOriginal(), terminateLocalService: vi.fn(async () => undefined), @@ -256,6 +272,67 @@ describe.skipIf(!support.supported)("heartbeat run-control database wiring", () expect(deps.failedProcessRunCancellations.get(run.id)?.error).toBe(failure); }); + async function ownedAdapterRun() { + const { company, agent } = await fixture(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, status: "running", runtimeMode: "legacy", runtimeModeResolvedAt: new Date() }).returning(); + const control = createAdapterExecutionControl(); + adapterExecutionControls.set(run.id, control); + return { run, control }; + } + + it("answers an owned adapter Stop that is still settling with a pending conflict", async () => { + const { run, control } = await ownedAdapterRun(); + const deps = callbacks(db); + deps.activeRunExecutions.add(run.id); + try { + let waitStartedAt = 0; + vi.mocked(waitForAdapterStop).mockImplementationOnce(async () => { + waitStartedAt = Date.now(); + throw new AdapterStopTimeoutError(60_000, { runId: run.id }); + }); + const requestedAt = Date.now(); + const error = await createHeartbeatRunControl(db, deps).cancelRunInternal(run.id).catch((err: unknown) => err); + expect(error).toBeInstanceOf(HttpError); + expect(error).toMatchObject({ + status: 409, + message: "Execution is still stopping; termination has not been verified.", + details: { code: "adapter_stop_pending", runId: run.id }, + }); + expect(control.controller.signal.aborted).toBe(true); + // Only a Stop that never settles is reported, from the same execution. + expect(reportAdapterStopIfUnsettled).toHaveBeenCalledWith(control.settled, captureException, + expect.objectContaining({ runId: run.id, adapterType: "codex_local", runtimeMode: "legacy", abortRequested: true }), control, + { stopRequestedAt: expect.any(Number) }); + // Its report bound runs from the Stop request, before the response wait. + const { stopRequestedAt } = vi.mocked(reportAdapterStopIfUnsettled).mock.calls.at(-1)![4]!; + expect(stopRequestedAt).toBeGreaterThanOrEqual(requestedAt); + expect(stopRequestedAt).toBeLessThanOrEqual(waitStartedAt); + // A pending Stop is not a cancellation receipt. + expect(deps.setRunStatusFromLive).not.toHaveBeenCalled(); + expect(deps.finalizeAgentStatus).not.toHaveBeenCalled(); + expect((await deps.getRun(run.id))?.status).toBe("running"); + expect(deps.failedProcessRunCancellations.has(run.id)).toBe(false); + } finally { + control.finish(); + adapterExecutionControls.delete(run.id); + } + }); + + it("keeps other owned adapter Stop failures unchanged", async () => { + const { run, control } = await ownedAdapterRun(); + const deps = callbacks(db); + vi.mocked(reportAdapterStopIfUnsettled).mockClear(); + try { + const failure = new Error("owner wait failed"); + vi.mocked(waitForAdapterStop).mockRejectedValueOnce(failure); + await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(run.id)).rejects.toBe(failure); + expect(reportAdapterStopIfUnsettled).not.toHaveBeenCalled(); + } finally { + control.finish(); + adapterExecutionControls.delete(run.id); + } + }); + it("deduplicates agent batches and cancels only unclaimed pending wakes", async () => { const { company, agent } = await fixture(); const [otherAgent] = await db.insert(agents).values({ companyId: company.id, name: "Other agent" }).returning(); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index f744f35d147..f4b0529ddc9 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -44,8 +44,11 @@ import { import { adapterExecutionControls, captureAdapterStopOwnership, + reportAdapterStopIfUnsettled, waitForAdapterStop, } from "../adapter-execution-control.js"; +import { AdapterStopTimeoutError } from "../adapter-stop-timeout.js"; +import { captureException } from "../../sentry.js"; import { randomUUID } from "node:crypto"; import { and, @@ -999,6 +1002,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont processCancellationSettlement, ); } + const stopRequestedAt = Date.now(); const cancellation = await (async () => { try { if (control) { @@ -1059,12 +1063,24 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont } if (control) { - await waitForAdapterStop(control.settled, undefined, { + const stopDiagnostics = { runId: run.id, adapterType: agent?.adapterType, runtimeMode: run.runtimeMode, abortRequested: control.controller.signal.aborted, - }, control); + }; + try { + await waitForAdapterStop(control.settled, undefined, stopDiagnostics, control); + } catch (error) { + if (!(error instanceof AdapterStopTimeoutError)) throw error; + // The owned adapter is still settling (for example copying the + // workspace back) and keeps its Stop proof requirements. Answer + // this request honestly; report only a Stop that never settles. + reportAdapterStopIfUnsettled(control.settled, captureException, stopDiagnostics, control, { + stopRequestedAt, + }); + throw conflict(error.message, { code: "adapter_stop_pending", runId: run.id }); + } const stopped = await getRun(run.id); if (stopped && isHeartbeatRunTerminalStatus(stopped.status)) { if (