fix: defer Boat admission while provider stop is pending

This commit is contained in:
Dotta committed 2026-10-10 22:06:55 -05:00
1 parent 44b1b52362
commit a4c864a062
20 files changed
+422 -30

No files matched your search

@@ -14,7 +14,7 @@ import { spawnSync } from "node:child_process";
import { remoteProgram } from "../adapters/remote-program.js";
import { createComputerService } from "./service.js";
import type { ComputerBackend, ComputerRepository } from "./ports.js";
import { ComputerError, type ComputerRecord } from "../domain/ledger.js";
import { ComputerError, ComputerStopPendingError, type ComputerRecord } from "../domain/ledger.js";
function fixture() {
let record: ComputerRecord | undefined;
@@ -497,19 +497,44 @@ describe("computer ownership", () => {
expect((await f.repository.get(f.scope)).ledger.owners[0]?.generation).toBe(first.owner.generation);
});
it("bounds the wait for terminal predecessor teardown without forcing retirement", async () => {
it.each([false, true])("bounds terminal predecessor teardown with pending-stop deferral=%s", async (deferPendingStop) => {
const f = fixture();
await f.attach();
await f.admit();
vi.mocked(f.repository.runState).mockResolvedValue("terminal");
const wait = vi.fn(async () => {});
const waiting = createComputerService(f.repository, f.backend, () => new Date("2026-10-10T12:00:00Z"), { admissionWaitMs: 2000, wait });
await expect(waiting.admit({ ...f.scope, agentId: "agent", runId: "follow-up", sessionKey: "session", idleTimeoutMs: 60_000 }))
await expect(waiting.admit({ ...f.scope, agentId: "agent", runId: "follow-up", sessionKey: "session", idleTimeoutMs: 60_000, deferPendingStop }))
.rejects.toMatchObject({ code: "conflict" });
expect(wait).toHaveBeenCalledTimes(2);
expect(f.backend.retire).not.toHaveBeenCalled();
});
it("defers an exact pending stop before owner creation and admits the same session after completion", async () => {
const f = fixture(); await f.attach(); await f.service.reconcile();
vi.mocked(f.backend.ready).mockClear();
const request = { ...f.scope, agentId: "agent", runId: "run", sessionKey: "saved-session", idleTimeoutMs: 60_000, deferPendingStop: true };
await expect(f.service.admit(request)).rejects.toBeInstanceOf(ComputerStopPendingError);
expect((await f.repository.get(f.scope)).ledger.owners).toEqual([]);
expect(f.backend.ready).not.toHaveBeenCalled(); expect(f.backend.launch).not.toHaveBeenCalled();
f.completeStop(); await f.service.reconcile();
const binding = await f.service.admit({ ...request, runId: "retry" });
await binding.launch({ command: "runnerd" });
expect((await f.repository.get(f.scope)).ledger.owners[0]).toMatchObject({ sessionKey: "saved-session", runId: "retry" });
expect(f.backend.launch).toHaveBeenCalledOnce();
});
it.each(["failing", "superseded", "different-action", "detaching"])("does not defer %s stop evidence", async kind => {
const f = fixture(); await f.attach(); await f.service.reconcile();
vi.mocked(f.backend.stopStatus).mockImplementation(async () => {
if (kind === "different-action") await f.repository.update(f.scope, record => { record.ledger.action!.id = "replacement"; });
if (kind === "detaching") await f.repository.update(f.scope, record => { record.ledger.status = "detaching"; });
return { id: "stop_1", status: ["failing", "superseded"].includes(kind) ? kind : "pending" };
});
const failure = await f.service.admit({ ...f.scope, agentId: "agent", runId: "run", sessionKey: "session", idleTimeoutMs: 60_000, deferPendingStop: true }).catch(error => error);
expect(failure).toBeInstanceOf(ComputerError); expect(failure).not.toBeInstanceOf(ComputerStopPendingError);
expect((await f.repository.get(f.scope)).ledger.owners).toEqual([]);
});
it("waits for a normal provider snapshot stop before admitting the next turn", async () => {
const f = fixture();
await f.attach();
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import type { ComputerRepository, ComputerBackend } from "./ports.js";
import {
ComputerError,
ComputerStopPendingError,
assertAdmission,
exactOwner,
expired,
@@ -57,6 +58,7 @@ export function createComputerService(
async function admitRecord<T>(
scope: Scope,
change: (record: ComputerRecord) => T,
pendingStopRunId?: string,
): Promise<T> {
const attempts = Math.ceil((options.admissionWaitMs ?? 120_000) / 1000);
const wait =
@@ -71,13 +73,13 @@ export function createComputerService(
} catch (error) {
if (
!(error instanceof ComputerError) ||
error.code !== "conflict" ||
attempt >= attempts
error.code !== "conflict"
)
throw error;
const current = await repository.get(scope);
if (current.ledger.status !== "attached") throw error;
if (error instanceof ComputerSessionBusyError && error.runId && error.agentId) {
if (attempt >= attempts) throw error;
// A terminal database status does not prove the process has stopped.
// Wait for the existing owner transition; never retire it here or
// advance its generation while final commands might still run.
@@ -86,6 +88,17 @@ export function createComputerService(
continue;
}
if (!current.ledger.action) throw error;
if (pendingStopRunId && current.ledger.action.providerStopId) {
const action = current.ledger.action;
const stop = await backend.stopStatus(current, action.providerStopId!);
const latest = await repository.get(scope);
if (stop.id === action.providerStopId && stop.status === "pending" &&
latest.ledger.status === "attached" && latest.ledger.action?.id === action.id &&
latest.ledger.action.providerStopId === stop.id) {
throw new ComputerStopPendingError({ ...scope, computerId: current.id, stopId: stop.id, runId: pendingStopRunId });
}
}
if (attempt >= attempts) throw error;
await reconcileRecord(current);
if ((await repository.get(scope)).ledger.action) await wait(1000);
}
@@ -387,6 +400,7 @@ finally:
probeId?: string;
sessionKey: string;
idleTimeoutMs: number;
deferPendingStop?: boolean;
},
) {
if (input.agentId) segment(input.agentId);
@@ -455,7 +469,7 @@ finally:
: agentHome,
};
return { record: structuredClone(record), owner: structuredClone(owner) };
});
}, input.deferPendingStop ? input.runId : undefined);
await backend.ready(result.record);
await backend.claim(result.record);
if (result.owner.generation === 1 && !result.owner.process) {
@@ -60,6 +60,15 @@ export class ComputerError extends Error {
this.name = "ComputerError";
}
}
/** A verified provider stop is pending before this run acquired an owner. */
export class ComputerStopPendingError extends ComputerError {
constructor(readonly admission: {
companyId: string; environmentId: string; computerId: string; stopId: string; runId: string;
}) {
super("conflict", "Computer is still saving its previous session.");
this.name = "ComputerStopPendingError";
}
}
export function segment(value: string): string {
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value))
throw new ComputerError("invalid", "Invalid computer resource identifier");
+1 -1
View File
@@ -3,7 +3,7 @@ import { secretService } from "../../services/secrets.js";
import { computerRepository } from "./adapters/repository.js";
import { boatBackend } from "./adapters/boat.js";
import { createComputerService } from "./application/service.js";
export { ComputerError } from "./domain/ledger.js";
export { ComputerError, ComputerStopPendingError } from "./domain/ledger.js";
export type {
OwnerRef as ComputerOwnerRef,
ProcessClaim as ComputerProcessClaim,
@@ -127,6 +127,7 @@ function readNonEmptyString(value: unknown): string | null {
}
function classifyRetryReasonKind(retryReason: string | null): RetryReasonKind {
if (retryReason === "computer_admission_wait") return "computer_admission_wait";
if (retryReason === MAX_TURN_CONTINUATION_RETRY_REASON) return "max_turn_continuation";
if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) return "disposition_repair";
if ((retryReason === "ai_connection_busy" || retryReason === "ai_connection_pool_wait")) return "ai_connection_wait";
@@ -293,7 +294,7 @@ export function createPostgresRunDispatchAdapter(
runAgentId: input.agentId,
issueId,
retryReasonKind,
enforceIssueExecutionLock: retryReasonKind === "max_turn_continuation" || retryReasonKind === "ai_connection_wait",
enforceIssueExecutionLock: retryReasonKind === "max_turn_continuation" || retryReasonKind === "ai_connection_wait" || retryReasonKind === "computer_admission_wait",
isNonAssigneeWorkspaceBusyRetry: isNonAssigneeWorkspaceBusyRetry(retryReason, input.contextSnapshot),
budgetBlock: null,
agentInvokable: true,
@@ -510,13 +510,13 @@ describe("native replacement execution authority", () => {
});
describe("AI subscription wait ownership", () => {
describe.each(["ai_connection_wait", "computer_admission_wait"] as const)("%s ownership", (retryReasonKind) => {
it.each([null, "another-run"])("preserves assignee lock guards and admits only recorded non-assignee waits: %s", (issueExecutionRunId) => {
const gate = {
...baseGateFacts(), retryReasonKind: "ai_connection_wait" as const,
...baseGateFacts(), retryReasonKind,
enforceIssueExecutionLock: true, issueExecutionRunId,
};
const queued = { ...baseStalenessFacts(), retryReasonKind: "ai_connection_wait" as const, issueExecutionRunId };
const queued = { ...baseStalenessFacts(), retryReasonKind, issueExecutionRunId };
expect(decideScheduledRetryGate(gate, NOW)).toMatchObject({ allowed: false, errorCode: "issue_execution_lock_changed" });
expect(decideQueuedRunStaleness(queued, NOW)).toMatchObject({ stale: true, errorCode: "issue_execution_lock_changed" });
const nonAssignee = { issueAssigneeAgentId: "another-agent", isNonAssigneeWorkspaceBusyRetry: true };
@@ -10,6 +10,7 @@ export type RetryReasonKind =
| "max_turn_continuation"
| "disposition_repair"
| "native_safe_replacement"
| "computer_admission_wait"
| "ai_connection_wait"
| "other";
@@ -408,7 +409,7 @@ export function decideScheduledRetryGate(
const lockOutcome = decideExecutionLock({
requiresExecutionLock:
(requiresInProgress ||
(facts.retryReasonKind === "ai_connection_wait" && !facts.isNonAssigneeWorkspaceBusyRetry)) &&
((facts.retryReasonKind === "ai_connection_wait" || facts.retryReasonKind === "computer_admission_wait") && !facts.isNonAssigneeWorkspaceBusyRetry)) &&
facts.enforceIssueExecutionLock,
runId: facts.runId,
issueExecutionRunId: facts.issueExecutionRunId,
@@ -640,7 +641,7 @@ export function decideQueuedRunStaleness(
const lockOutcome = decideExecutionLock({
// A server-recorded non-assignee wake never held the task execution lock.
requiresExecutionLock: requiresInProgress ||
(facts.retryReasonKind === "ai_connection_wait" && !facts.isNonAssigneeWorkspaceBusyRetry),
((facts.retryReasonKind === "ai_connection_wait" || facts.retryReasonKind === "computer_admission_wait") && !facts.isNonAssigneeWorkspaceBusyRetry),
runId: facts.runId,
issueExecutionRunId: facts.issueExecutionRunId,
});
@@ -16,6 +16,7 @@ function readNonEmptyString(value: unknown): string | null {
}
export const MAX_TURN_CONTINUATION_RETRY_REASON = "max_turns_continuation";
export const COMPUTER_ADMISSION_WAIT_RETRY_REASON = "computer_admission_wait";
export const WORKSPACE_BUSY_RETRY_REASON = "workspace_busy";
export const AI_CONNECTION_POOL_WAIT_RETRY_REASON = "ai_connection_pool_wait";
export const AI_CONNECTION_BUSY_RETRY_REASON = "ai_connection_busy";
@@ -40,6 +41,8 @@ export function isNonAssigneeWorkspaceBusyRetry(
contextSnapshot: Record<string, unknown>,
): boolean {
return (
(retryReason === COMPUTER_ADMISSION_WAIT_RETRY_REASON &&
contextSnapshot.computerAdmissionDeferredWhileAssignee === false) ||
(retryReason === WORKSPACE_BUSY_RETRY_REASON &&
contextSnapshot.workspaceBusyDeferredWhileAssignee === false) ||
((retryReason === AI_CONNECTION_BUSY_RETRY_REASON || retryReason === AI_CONNECTION_POOL_WAIT_RETRY_REASON) &&
+1
View File
@@ -12,6 +12,7 @@ import type { RunDispatchWriter, ScheduledRetryReader } from "./application/port
export {
MAX_TURN_CONTINUATION_RETRY_REASON,
WORKSPACE_BUSY_RETRY_REASON,
COMPUTER_ADMISSION_WAIT_RETRY_REASON,
AI_CONNECTION_BUSY_RETRY_REASON,
AI_CONNECTION_POOL_WAIT_RETRY_REASON,
INTERACTION_CONTINUATION_INFRA_RETRY_REASON,