fix(worker): harden run completion boundary

This commit is contained in:
ZacharyZhang-NY committed 2026-04-29 00:04:00 -04:00
1 parent e34503df68
commit 7504df170e
3 files changed
+413 -14

No files matched your search

@@ -15,6 +15,10 @@ export interface RunFinishedHooks {
| { ok: false; errorMessage: string }; | { ok: false; errorMessage: string };
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export function handleRunFinished( export function handleRunFinished(
event: Extract<WorkerMessageEvent, { type: "run-finished" }>, event: Extract<WorkerMessageEvent, { type: "run-finished" }>,
deps: HandlerDeps, deps: HandlerDeps,
@@ -37,7 +41,11 @@ export function handleRunFinished(
} }
: event; : event;
if (boundaryResult && !boundaryResult.ok) { if (boundaryResult && !boundaryResult.ok) {
try {
deps.db.core.runs.markRunCompletionFailure(event.runId, boundaryResult.errorMessage); deps.db.core.runs.markRunCompletionFailure(event.runId, boundaryResult.errorMessage);
} catch (error) {
deps.logger.error(`[worker] markRunCompletionFailure failed for artifact boundary ${event.runId}: ${errorMessage(error)}`);
}
} }
emitAndNotifyCompletion(effectiveEvent, deps, rfCtx); emitAndNotifyCompletion(effectiveEvent, deps, rfCtx);
const { hadDeferredWakes } = runPostCompletionAutomation(effectiveEvent, deps, context, rfCtx); const { hadDeferredWakes } = runPostCompletionAutomation(effectiveEvent, deps, context, rfCtx);
@@ -16,6 +16,22 @@ export interface RunFinishedContext {
runOutcome: ReturnType<HandlerDeps["db"]["core"]["runs"]["finishRun"]>; runOutcome: ReturnType<HandlerDeps["db"]["core"]["runs"]["finishRun"]>;
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function runCompletionSideEffect(
logger: HandlerDeps["logger"],
label: string,
operation: () => void,
): void {
try {
operation();
} catch (error) {
logger.error(`[worker] ${label} failed after run completion: ${errorMessage(error)}`);
}
}
export function finalizeRun( export function finalizeRun(
event: RunFinishedEvent, event: RunFinishedEvent,
deps: HandlerDeps, deps: HandlerDeps,
@@ -71,6 +87,7 @@ export function finalizeRun(
leaseRenewalMap.delete(event.runId); leaseRenewalMap.delete(event.runId);
const runOutcome = db.core.runs.finishRun({ ...event, unattributedCost }); const runOutcome = db.core.runs.finishRun({ ...event, unattributedCost });
runCompletionSideEffect(logger, "run activity logging", () => {
db.core.activity.addActivity({ db.core.activity.addActivity({
companyId: run.companyId, companyId: run.companyId,
actor: run.agentId, actor: run.agentId,
@@ -79,17 +96,20 @@ export function finalizeRun(
entityId: run.id, entityId: run.id,
detail: event.summary ?? event.errorMessage ?? "", detail: event.summary ?? event.errorMessage ?? "",
}); });
});
return { run, task, runOutcome }; return { run, task, runOutcome };
} }
export function releaseCompletedRunWorkspaceLock( export function releaseCompletedRunWorkspaceLock(
rfCtx: RunFinishedContext | null, rfCtx: RunFinishedContext | null,
deps: Pick<HandlerDeps, "db">, deps: Pick<HandlerDeps, "db" | "logger">,
): void { ): void {
const workspaceId = rfCtx?.run.workspaceId; const workspaceId = rfCtx?.run.workspaceId;
if (!workspaceId) return; if (!workspaceId) return;
runCompletionSideEffect(deps.logger, "workspace lock release", () => {
deps.db.core.workspaces.releaseWorkspaceLock(workspaceId, rfCtx.run.id); deps.db.core.workspaces.releaseWorkspaceLock(workspaceId, rfCtx.run.id);
});
} }
export function accumulateAndRotateSession( export function accumulateAndRotateSession(
@@ -120,6 +140,7 @@ export function accumulateAndRotateSession(
const session = db.core.tasks.getSessionById(agentRecord.sessionId); const session = db.core.tasks.getSessionById(agentRecord.sessionId);
if (!session) return; if (!session) return;
try {
sessionService.accumulateTokenUsage( sessionService.accumulateTokenUsage(
session.id, session.id,
event.inputTokens ?? 0, event.inputTokens ?? 0,
@@ -137,6 +158,9 @@ export function accumulateAndRotateSession(
sessionService.rotateSession(updatedSession); sessionService.rotateSession(updatedSession);
logger.info(`[session] Rotated session for agent ${run.agentId}: ${rotationResult.reason}`); logger.info(`[session] Rotated session for agent ${run.agentId}: ${rotationResult.reason}`);
} }
} catch (error) {
logger.error(`[session] accumulation/rotation failed for run ${run.id}: ${errorMessage(error)}`);
}
} }
export function emitAndNotifyCompletion( export function emitAndNotifyCompletion(
@@ -147,14 +171,19 @@ export function emitAndNotifyCompletion(
const { db, emitEvent, notify, logger } = deps; const { db, emitEvent, notify, logger } = deps;
const { run, task, runOutcome } = rfCtx; const { run, task, runOutcome } = rfCtx;
runCompletionSideEffect(logger, "run-updated event emission", () => {
emitEvent({ type: "run-updated", runId: run.id, action: "completed" }); emitEvent({ type: "run-updated", runId: run.id, action: "completed" });
});
runCompletionSideEffect(logger, "run-status event emission", () => {
emitEvent({ emitEvent({
type: "run-status", type: "run-status",
runId: run.id, runId: run.id,
status: event.status, status: event.status,
message: event.summary ?? event.errorMessage ?? event.status, message: event.summary ?? event.errorMessage ?? event.status,
}); });
});
if ((event.status === "failed" || event.status === "timed_out" || event.status === "interrupted") && task) { if ((event.status === "failed" || event.status === "timed_out" || event.status === "interrupted") && task) {
runCompletionSideEffect(logger, "task failure notification", () => {
notify({ notify({
title: "Task Failed", title: "Task Failed",
body: `${task.title} -- manual intervention needed`, body: `${task.title} -- manual intervention needed`,
@@ -162,6 +191,7 @@ export function emitAndNotifyCompletion(
navigation: { section: "tasks", entityId: task.id }, navigation: { section: "tasks", entityId: task.id },
batchKey: "failed_runs", batchKey: "failed_runs",
}); });
});
} }
let updatedAgent: ReturnType<HandlerDeps["db"]["core"]["entity"]["getAgent"]> | null = null; let updatedAgent: ReturnType<HandlerDeps["db"]["core"]["entity"]["getAgent"]> | null = null;
@@ -175,6 +205,7 @@ export function emitAndNotifyCompletion(
} }
if (updatedAgent && runOutcome.budgetHardStopped) { if (updatedAgent && runOutcome.budgetHardStopped) {
runCompletionSideEffect(logger, "budget auto-pause activity logging", () => {
db.core.activity.addActivity({ db.core.activity.addActivity({
companyId: updatedAgent.companyId, companyId: updatedAgent.companyId,
actor: "system", actor: "system",
@@ -183,6 +214,8 @@ export function emitAndNotifyCompletion(
entityId: updatedAgent.id, entityId: updatedAgent.id,
detail: `Budget exhausted at ${updatedAgent.spentMonthlyUsd.toFixed(2)} / ${updatedAgent.budgetMonthlyUsd.toFixed(2)} USD.`, detail: `Budget exhausted at ${updatedAgent.spentMonthlyUsd.toFixed(2)} / ${updatedAgent.budgetMonthlyUsd.toFixed(2)} USD.`,
}); });
});
runCompletionSideEffect(logger, "budget auto-pause notification", () => {
notify({ notify({
title: "Agent Paused", title: "Agent Paused",
body: `${updatedAgent.name} paused -- budget limit reached`, body: `${updatedAgent.name} paused -- budget limit reached`,
@@ -190,7 +223,10 @@ export function emitAndNotifyCompletion(
navigation: { section: "agents", entityId: updatedAgent.id }, navigation: { section: "agents", entityId: updatedAgent.id },
batchKey: "agent_paused", batchKey: "agent_paused",
}); });
});
runCompletionSideEffect(logger, "agent-updated event emission", () => {
emitEvent({ type: "agent-updated", agentId: updatedAgent.id, action: "paused" }); emitEvent({ type: "agent-updated", agentId: updatedAgent.id, action: "paused" });
});
} }
} }
@@ -203,15 +239,23 @@ export function runPostCompletionAutomation(
const { db, logger, isQuitting, wakeAgentIfPossible, processRunCompletion, onRunCompleted, notify, budgetService } = deps; const { db, logger, isQuitting, wakeAgentIfPossible, processRunCompletion, onRunCompleted, notify, budgetService } = deps;
const { destroyed, MAX_RETRY_ATTEMPTS, RETRY_COOLDOWN_MS, pendingRetryTimers } = context; const { destroyed, MAX_RETRY_ATTEMPTS, RETRY_COOLDOWN_MS, pendingRetryTimers } = context;
const { run, task } = rfCtx; const { run, task } = rfCtx;
let housekeepingStatus = event.status;
let housekeepingSummary = event.summary ?? null;
let housekeepingErrorMessage = event.errorMessage ?? null;
// Policy-based incident check after run completion. Always runs once the // Policy-based incident check after run completion. Always runs once the
// run is finalized — cost is read from the cost_entries SUM inside // run is finalized — cost is read from the cost_entries SUM inside
// finishRun/checkAndCreateIncidents, not from the worker event. // finishRun/checkAndCreateIncidents, not from the worker event.
if (budgetService && event.status === "succeeded") { if (budgetService && event.status === "succeeded") {
try {
budgetService.checkAndCreateIncidents(run.companyId, run.agentId, task?.projectId ?? null); budgetService.checkAndCreateIncidents(run.companyId, run.agentId, task?.projectId ?? null);
} catch (error) {
logger.error(`[worker] budget incident check failed for run ${run.id}: ${errorMessage(error)}`);
}
} }
if ((event.status === "failed" || event.status === "timed_out") && !isQuitting() && !destroyed && run.taskId) { if ((event.status === "failed" || event.status === "timed_out") && !isQuitting() && !destroyed && run.taskId) {
try {
handleFailureEscalation( handleFailureEscalation(
{ {
db, db,
@@ -234,11 +278,15 @@ export function runPostCompletionAutomation(
pendingRetryTimers.add(retryTimer); pendingRetryTimers.add(retryTimer);
}, },
); );
} catch (error) {
logger.error(`[worker] failure escalation failed for run ${run.id}: ${errorMessage(error)}`);
}
} }
// EXEC-05: Promote deferred wakes after run completion // EXEC-05: Promote deferred wakes after run completion
let hadDeferredWakes = false; let hadDeferredWakes = false;
if (!isQuitting() && !destroyed) { if (!isQuitting() && !destroyed) {
try {
const promoted = db.automation.wakeup.promoteWakeupRequests(run.agentId, run.companyId); const promoted = db.automation.wakeup.promoteWakeupRequests(run.agentId, run.companyId);
const pendingWakeTrigger = db.automation.wakeup.getPreferredWakeTrigger(run.agentId, run.companyId); const pendingWakeTrigger = db.automation.wakeup.getPreferredWakeTrigger(run.agentId, run.companyId);
if (promoted > 0) { if (promoted > 0) {
@@ -251,10 +299,37 @@ export function runPostCompletionAutomation(
); );
wakeAgentIfPossible(run.agentId, run.companyId, pendingWakeTrigger); wakeAgentIfPossible(run.agentId, run.companyId, pendingWakeTrigger);
} }
} catch (error) {
logger.error(`[worker] deferred wake processing failed for run ${run.id}: ${errorMessage(error)}`);
}
} }
if (!isQuitting() && !destroyed) { if (!isQuitting() && !destroyed) {
try {
processRunCompletion(run, event as z.infer<typeof workerMessageSchema> & { type: "run-finished" }); processRunCompletion(run, event as z.infer<typeof workerMessageSchema> & { type: "run-finished" });
} catch (error) {
const message = errorMessage(error);
logger.error(`[worker] processRunCompletion failed for run ${run.id}: ${message}`);
housekeepingStatus = "failed";
housekeepingSummary = null;
housekeepingErrorMessage = message;
try {
db.core.runs.markRunCompletionFailure(run.id, message);
} catch (markError) {
logger.error(`[worker] markRunCompletionFailure failed for run ${run.id}: ${errorMessage(markError)}`);
}
if (task?.status === "in_progress") {
try {
db.core.tasks.advanceTaskStatus(
task.id,
"blocked",
`Run completion automation failed: ${message}`,
);
} catch (statusError) {
logger.error(`[worker] failed to block task ${task.id} after completion automation failure: ${errorMessage(statusError)}`);
}
}
}
} }
// Run housekeeping: thread events + knowledge candidates // Run housekeeping: thread events + knowledge candidates
@@ -265,9 +340,9 @@ export function runPostCompletionAutomation(
run.taskId, run.taskId,
run.agentId, run.agentId,
run.companyId, run.companyId,
event.status, housekeepingStatus,
event.summary ?? null, housekeepingSummary,
event.errorMessage ?? null, housekeepingErrorMessage,
); );
} catch (err) { } catch (err) {
logger.error(`[worker] onRunCompleted housekeeping failed: ${err instanceof Error ? err.message : String(err)}`); logger.error(`[worker] onRunCompleted housekeeping failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -275,7 +350,7 @@ export function runPostCompletionAutomation(
} }
// Reset retry count on successful completion // Reset retry count on successful completion
if (event.status === "succeeded" && run.taskId) { if (housekeepingStatus === "succeeded" && run.taskId) {
handleSuccessReset(db, run.taskId, logger); handleSuccessReset(db, run.taskId, logger);
} }
+325 -9
View File
@@ -24,19 +24,45 @@ function runFinishedMessage(runId: string) {
}; };
} }
function createHandlerDeps(calls: string[]) { function createHandlerDeps(calls: string[], options: {
const releaseWorkspaceLock = vi.fn(() => calls.push("releaseWorkspaceLock")); taskId?: string | null;
taskStatus?: string;
sessionAccumulateThrows?: boolean;
processRunCompletionThrows?: boolean;
activityThrows?: boolean;
emitEventThrows?: boolean;
wakeupThrows?: boolean;
releaseWorkspaceThrows?: boolean;
markRunCompletionFailureThrows?: boolean;
} = {}) {
const releaseWorkspaceLock = vi.fn(() => {
calls.push("releaseWorkspaceLock");
if (options.releaseWorkspaceThrows) {
throw new Error("workspace release failed");
}
});
const finishRun = vi.fn(() => { const finishRun = vi.fn(() => {
calls.push("finishRun"); calls.push("finishRun");
return { budgetHardStopped: false }; return { budgetHardStopped: false };
}); });
const rotateSession = vi.fn(() => calls.push("rotateSession")); const rotateSession = vi.fn(() => calls.push("rotateSession"));
const processRunCompletion = vi.fn(() => calls.push("processRunCompletion")); const processRunCompletion = vi.fn(() => {
calls.push("processRunCompletion");
if (options.processRunCompletionThrows) {
throw new Error("processRunCompletion failed");
}
});
const releaseRunResources = vi.fn((): RunResourceReleaseResult => { const releaseRunResources = vi.fn((): RunResourceReleaseResult => {
calls.push("releaseRunResources"); calls.push("releaseRunResources");
return { ok: true as const }; return { ok: true as const };
}); });
const markRunCompletionFailure = vi.fn(() => calls.push("markRunCompletionFailure")); const markRunCompletionFailure = vi.fn(() => {
calls.push("markRunCompletionFailure");
if (options.markRunCompletionFailureThrows) {
throw new Error("mark completion failed");
}
});
const advanceTaskStatus = vi.fn(() => calls.push("advanceTaskStatus"));
const db = { const db = {
core: { core: {
@@ -45,14 +71,21 @@ function createHandlerDeps(calls: string[]) {
id: RUN_ID, id: RUN_ID,
companyId: "company-1", companyId: "company-1",
agentId: "agent-1", agentId: "agent-1",
taskId: null, taskId: options.taskId ?? null,
workspaceId: "workspace-1", workspaceId: "workspace-1",
})), })),
finishRun, finishRun,
markRunCompletionFailure, markRunCompletionFailure,
}, },
workspaces: { releaseWorkspaceLock }, workspaces: { releaseWorkspaceLock },
activity: { addActivity: vi.fn(() => calls.push("addActivity")) }, activity: {
addActivity: vi.fn(() => {
calls.push("addActivity");
if (options.activityThrows) {
throw new Error("activity write failed");
}
}),
},
entity: { entity: {
getAgent: vi.fn(() => ({ getAgent: vi.fn(() => ({
id: "agent-1", id: "agent-1",
@@ -60,11 +93,19 @@ function createHandlerDeps(calls: string[]) {
reportsTo: "manager-1", reportsTo: "manager-1",
sessionId: "session-1", sessionId: "session-1",
})), })),
getTask: vi.fn(() => ({
id: options.taskId ?? "task-1",
companyId: "company-1",
agentId: "agent-1",
title: "Completion task",
status: options.taskStatus ?? "in_progress",
})),
countActiveGoalsForCompany: vi.fn(() => 0), countActiveGoalsForCompany: vi.fn(() => 0),
}, },
tasks: { tasks: {
getSessionById: vi.fn(() => ({ id: "session-1" })), getSessionById: vi.fn(() => ({ id: "session-1" })),
listAgentTasks: vi.fn(() => []), listAgentTasks: vi.fn(() => []),
advanceTaskStatus,
}, },
agents: { agents: {
getDirectReports: vi.fn(() => []), getDirectReports: vi.fn(() => []),
@@ -76,14 +117,24 @@ function createHandlerDeps(calls: string[]) {
}, },
automation: { automation: {
wakeup: { wakeup: {
promoteWakeupRequests: vi.fn(() => 0), promoteWakeupRequests: vi.fn(() => {
if (options.wakeupThrows) {
throw new Error("wakeup promotion failed");
}
return 0;
}),
getPreferredWakeTrigger: vi.fn(() => null), getPreferredWakeTrigger: vi.fn(() => null),
}, },
}, },
}; };
const sessionService = { const sessionService = {
accumulateTokenUsage: vi.fn(() => calls.push("accumulateTokenUsage")), accumulateTokenUsage: vi.fn(() => {
calls.push("accumulateTokenUsage");
if (options.sessionAccumulateThrows) {
throw new Error("session accumulation failed");
}
}),
evaluateRotation: vi.fn(() => ({ shouldRotate: true, reason: "unit-test" })), evaluateRotation: vi.fn(() => ({ shouldRotate: true, reason: "unit-test" })),
rotateSession, rotateSession,
}; };
@@ -98,7 +149,12 @@ function createHandlerDeps(calls: string[]) {
error: vi.fn(), error: vi.fn(),
}, },
isQuitting: vi.fn(() => false), isQuitting: vi.fn(() => false),
emitEvent: vi.fn(() => calls.push("emitEvent")), emitEvent: vi.fn(() => {
calls.push("emitEvent");
if (options.emitEventThrows) {
throw new Error("emit failed");
}
}),
wakeAgentIfPossible: vi.fn(() => null), wakeAgentIfPossible: vi.fn(() => null),
processRunCompletion, processRunCompletion,
notify: vi.fn(), notify: vi.fn(),
@@ -111,6 +167,7 @@ function createHandlerDeps(calls: string[]) {
processRunCompletion, processRunCompletion,
releaseRunResources, releaseRunResources,
markRunCompletionFailure, markRunCompletionFailure,
advanceTaskStatus,
}; };
} }
@@ -227,6 +284,265 @@ describe("worker completion boundary", () => {
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID }); expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
}); });
it("continues completion when artifact failure marking throws", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
processRunCompletion,
releaseRunResources,
markRunCompletionFailure,
} = createHandlerDeps(calls, { markRunCompletionFailureThrows: true });
releaseRunResources.mockImplementationOnce(() => {
calls.push("releaseRunResources");
return { ok: false as const, errorMessage: "completion_reconcile failed" };
});
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(markRunCompletionFailure).toHaveBeenCalledWith(RUN_ID, "completion_reconcile failed");
expect(processRunCompletion).toHaveBeenCalledWith(
expect.objectContaining({ id: RUN_ID }),
expect.objectContaining({
status: "failed",
errorMessage: "completion_reconcile failed",
usageStatus: "error_stop",
}),
);
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("continues completion automation when session accumulation fails", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
processRunCompletion,
} = createHandlerDeps(calls, { sessionAccumulateThrows: true });
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(processRunCompletion).toHaveBeenCalled();
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("marks completion failed and blocks the task when completion automation throws", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
markRunCompletionFailure,
advanceTaskStatus,
} = createHandlerDeps(calls, {
taskId: "task-1",
taskStatus: "in_progress",
processRunCompletionThrows: true,
});
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(markRunCompletionFailure).toHaveBeenCalledWith(RUN_ID, "processRunCompletion failed");
expect(advanceTaskStatus).toHaveBeenCalledWith(
"task-1",
"blocked",
expect.stringContaining("Run completion automation failed: processRunCompletion failed"),
);
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("releases workspace and acknowledges completion when activity logging fails", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
processRunCompletion,
} = createHandlerDeps(calls, { activityThrows: true });
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(processRunCompletion).toHaveBeenCalled();
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("releases workspace and acknowledges completion when renderer event emission fails", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
processRunCompletion,
} = createHandlerDeps(calls, { emitEventThrows: true });
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(processRunCompletion).toHaveBeenCalled();
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("releases workspace and acknowledges completion when deferred wake promotion fails", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
processRunCompletion,
} = createHandlerDeps(calls, { wakeupThrows: true });
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(processRunCompletion).toHaveBeenCalled();
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("acknowledges completion when workspace release fails", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
processRunCompletion,
} = createHandlerDeps(calls, { releaseWorkspaceThrows: true });
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(processRunCompletion).toHaveBeenCalled();
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("blocks the task and acknowledges completion when marking completion failure throws", async () => {
const calls: string[] = [];
const {
deps,
releaseWorkspaceLock,
markRunCompletionFailure,
advanceTaskStatus,
} = createHandlerDeps(calls, {
taskId: "task-1",
taskStatus: "in_progress",
processRunCompletionThrows: true,
markRunCompletionFailureThrows: true,
});
const worker = { postMessage: vi.fn(() => calls.push("completionAck")) };
await handleWorkerMessage(
runFinishedMessage(RUN_ID),
worker as never,
deps as never,
workerMessageSchema,
false,
2,
30_000,
new Map(),
3,
new Set(),
new Map(),
);
expect(markRunCompletionFailure).toHaveBeenCalledWith(RUN_ID, "processRunCompletion failed");
expect(advanceTaskStatus).toHaveBeenCalledWith(
"task-1",
"blocked",
expect.stringContaining("Run completion automation failed: processRunCompletion failed"),
);
expect(releaseWorkspaceLock).toHaveBeenCalledWith("workspace-1", RUN_ID);
expect(worker.postMessage).toHaveBeenCalledWith({ type: "run-completion-ack", runId: RUN_ID });
});
it("keeps same-workspace runs queued until parent acknowledges completion", async () => { it("keeps same-workspace runs queued until parent acknowledges completion", async () => {
const parentPort = new EventEmitter() as EventEmitter & { const parentPort = new EventEmitter() as EventEmitter & {
postMessage: ReturnType<typeof vi.fn>; postMessage: ReturnType<typeof vi.fn>;