diff --git a/server/src/__tests__/assigned-work-invariant.test.ts b/server/src/__tests__/assigned-work-invariant.test.ts index 5b3abbbd3da..398afef8c42 100644 --- a/server/src/__tests__/assigned-work-invariant.test.ts +++ b/server/src/__tests__/assigned-work-invariant.test.ts @@ -232,7 +232,8 @@ describePostgres("assigned-work invariant sweep", () => { return { issueId, hold }; } const recent = await escalated({ endedAgoMs: 2 * HOUR, cause: "transport_timeout" }); - const old = await escalated({ endedAgoMs: 30 * HOUR, cause: "transport_timeout" }); + // No provider work started, so it stays eligible for the sweep's week, not the 24-hour window. + const old = await escalated({ endedAgoMs: 8 * 24 * HOUR, cause: "transport_timeout" }); const lasting = await escalated({ endedAgoMs: 2 * HOUR, cause: "provider_access_denied" }); const queue = wakeQueue(); const recovery = recoveryService(db, { enqueueWakeup: queue.enqueueWakeup }); @@ -247,7 +248,57 @@ describePostgres("assigned-work invariant sweep", () => { expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, recent.hold.id)))[0]) .toMatchObject({ status: "resolved", outcome: "restored", ownerType: "system", resolutionNote: "stranded_transient_continued" }); - for (const left of [old, lasting]) { + for (const [left, outcome] of [[old, "stale_reported"], [lasting, "left_to_hold_owner"]] as const) { + expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: left.issueId })) + .toMatchObject({ outcome }); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, left.hold.id)))[0].status).toBe("active"); + } + expect(queue.calls).toHaveLength(1); + }, 60_000); + + it("continues a task blocked by an environment setup failure before any provider work, including one blocked days ago", async () => { + const f = await seedCompany(); + const qualification = 'Failed to acquire lease for environment "Paperclip Sandbox" (sandbox): sandbox_snapshot_qualification_required: ' + + "The snapshot qualification is missing or stale."; + async function escalated(input: { endedAgoMs: number; executionRecovery: Record | null }) { + const blockedAt = new Date(Date.now() - input.endedAgoMs + 1_000); + const issueId = await f.issue({ status: "blocked", blockedTransitionAt: blockedAt, updatedAt: blockedAt }); + const run = await f.run(issueId, { status: "failed", errorCode: "setup_failed", livenessState: "failed", error: qualification, + resultJson: { failureCause: "lease_acquire_failed", ...(input.executionRecovery ? { executionRecovery: input.executionRecovery } : {}) }, + startedAt: new Date(Date.now() - input.endedAgoMs - 60_000), finishedAt: new Date(Date.now() - input.endedAgoMs), + createdAt: new Date(Date.now() - input.endedAgoMs - 60_000) }); + const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: issueId, + kind: "stranded_assigned_issue", status: "active", ownerType: "board", cause: "stranded_assigned_issue", + fingerprint: `source_scoped_recovery:${f.companyId}:${issueId}:stranded_assigned_issue`, + evidence: { previousStatus: "todo", latestRunId: run.id, latestRunErrorCode: "setup_failed", + routingPolicy: "board_escalation_no_takeover_v1" }, + nextAction: "Board operator: inspect the evidence, repair the runtime if appropriate.", attemptCount: 1 }).returning(); + await db.insert(activityLog).values({ companyId: f.companyId, actorType: "system", actorId: "system", action: "issue.updated", + entityType: "issue", entityId: issueId, details: { status: "blocked", previousStatus: "todo", + source: "recovery.reconcile_stranded_assigned_issue" }, createdAt: blockedAt }); + return { issueId, hold }; + } + const beforeWork = { kind: "bootstrap", providerWorkStarted: false }; + // Blocked about two days before the deploy that carries this repair. + const blockedDaysAgo = await escalated({ endedAgoMs: 40 * HOUR, executionRecovery: beforeWork }); + const workStarted = await escalated({ endedAgoMs: 2 * HOUR, executionRecovery: { kind: "bootstrap", providerWorkStarted: true } }); + const unproven = await escalated({ endedAgoMs: 2 * HOUR, executionRecovery: null }); + const tooOld = await escalated({ endedAgoMs: 8 * 24 * HOUR, executionRecovery: beforeWork }); + const queue = wakeQueue(); + const recovery = recoveryService(db, { enqueueWakeup: queue.enqueueWakeup }); + const suspects = (await recovery.assignedWork.listSuspects({ companyId: f.companyId }, null, 100)).map(row => row.id); + expect(suspects).toContain(blockedDaysAgo.issueId); + expect(suspects).not.toContain(tooOld.issueId); + + expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: blockedDaysAgo.issueId })) + .toMatchObject({ outcome: "repaired", verdict: { reason: "recovery_block" } }); + expect(queue.calls).toEqual([{ agentId: f.agentId, issueId: blockedDaysAgo.issueId, source: "issue.assigned_work_invariant" }]); + expect((await db.select().from(issues).where(eq(issues.id, blockedDaysAgo.issueId)))[0].status).toBe("todo"); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, blockedDaysAgo.hold.id)))[0]) + .toMatchObject({ status: "resolved", outcome: "restored", ownerType: "system" }); + + // Work that may have started, or a run that never recorded it had not, keeps its owner's decision. + for (const left of [workStarted, unproven]) { expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: left.issueId })) .toMatchObject({ outcome: "left_to_hold_owner" }); expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, left.hold.id)))[0].status).toBe("active"); diff --git a/server/src/services/continuation-cause.ts b/server/src/services/continuation-cause.ts index bbca767a384..4a66e9ecf9a 100644 --- a/server/src/services/continuation-cause.ts +++ b/server/src/services/continuation-cause.ts @@ -95,13 +95,25 @@ export function canContinueRecoveryRunAutomatically(run: ClassifiedRun): boolean return continuationCauseIsSystemOwned(run) && isRecoveryRun(run); } -function firstRunFailureContinues(run: Pick): boolean { - if (isRestartClassFailureCode(run.errorCode)) return true; +/** + * A setup failure the run recorded as ending before any provider work started + * (`executionRecovery` bootstrap, `providerWorkStarted: false`): an environment + * lease, sandbox qualification, provider or workspace preparation step failed, + * so the task never began and running it again repeats nothing. The generic + * `setup_failed` belongs here too; person-owned causes have their own codes + * and never reach it. Repetition is bounded by the per-task continuation + * allowance and the company-wide automatic run brake, not by this test. + */ +export function isSetupFailureBeforeProviderWork(run: Pick): boolean { const recovery = object(object(run.resultJson).executionRecovery); - return (TRANSIENT_SETUP_FAILURE_CODES as readonly unknown[]).includes(run.errorCode) + return (SETUP_FAILURE_CODES as readonly unknown[]).includes(run.errorCode) && recovery.kind === "bootstrap" && recovery.providerWorkStarted === false; } +function firstRunFailureContinues(run: Pick): boolean { + return isRestartClassFailureCode(run.errorCode) || isSetupFailureBeforeProviderWork(run); +} + export function continuesAutomatically(run: ClassifiedRun): boolean { return continuationCauseIsSystemOwned(run) && (isRecoveryRun(run) || firstRunFailureContinues(run)); } @@ -132,11 +144,17 @@ export function recoveryRunSql(alias: string): SQL { or ${context}->>'wakeReason' in (${list(AUTOMATIC_CONTINUATION_WAKE_REASONS)})))`; } +/** SQL twin of `isSetupFailureBeforeProviderWork`. */ +export function setupFailureBeforeProviderWorkSql(alias: string): SQL { + const column = (name: string) => sql.raw(`${alias}.${name}`); + return sql`(${column("error_code")} in (${list(SETUP_FAILURE_CODES)}) + and ${column("result_json")}#>>'{executionRecovery,kind}' = 'bootstrap' + and ${column("result_json")}#>>'{executionRecovery,providerWorkStarted}' = 'false')`; +} + export function continuesAutomaticallySql(alias: string): SQL { const column = (name: string) => sql.raw(`${alias}.${name}`); return sql`(${continuationCauseIsSystemOwnedSql(alias)} and (${recoveryRunSql(alias)} or ${column("error_code")} in (${list(RESTART_CLASS_FAILURE_CODES)}) - or (${column("error_code")} in (${list(TRANSIENT_SETUP_FAILURE_CODES)}) - and ${column("result_json")}#>>'{executionRecovery,kind}' = 'bootstrap' - and ${column("result_json")}#>>'{executionRecovery,providerWorkStarted}' = 'false')))`; + or ${setupFailureBeforeProviderWorkSql(alias)}))`; } diff --git a/server/src/services/recovery/assigned-work-sweep.ts b/server/src/services/recovery/assigned-work-sweep.ts index 52e7e4c9f7c..4c8a61b77d2 100644 --- a/server/src/services/recovery/assigned-work-sweep.ts +++ b/server/src/services/recovery/assigned-work-sweep.ts @@ -42,7 +42,9 @@ import { automaticRunCreationHeldUntil, readAutomaticWorkStatus, reserveAutomati import { isReattachPhaseActive, reattachPhaseRecheckAt } from "../heartbeat/run-admission.js"; import { wakeBecameFreshContinuation } from "./wake-became-fresh-continuation.js"; import { continueSweepTaskFromSavedWork } from "./sweep-saved-work-continuation.js"; -import { STRANDED_CONTINUATION_MAX_AGE_MS, STRANDED_KIND, strandedHoldContinuesAutomatically, type StrandedHoldRun } from "./stranded-hold-continuation.js"; +import { setupFailureBeforeProviderWorkSql } from "../continuation-cause.js"; +import { STRANDED_CONTINUATION_MAX_AGE_MS, STRANDED_KIND, STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS, strandedHoldContinuesAutomatically, + type StrandedHoldRun } from "./stranded-hold-continuation.js"; import { continuationActivityMessage, continuationAllowance, @@ -570,7 +572,9 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { -- except a recent board escalation, which the predicate judges by its failed run's cause and not (ra.kind = ${STRANDED_KIND} and ra.owner_type = 'board' and exists (select 1 from heartbeat_runs sr where sr.company_id = ra.company_id and sr.id::text = ra.evidence->>'latestRunId' - and sr.finished_at > ${new Date(at.getTime() - STRANDED_CONTINUATION_MAX_AGE_MS).toISOString()}::timestamptz)) + and (sr.finished_at > ${new Date(at.getTime() - STRANDED_CONTINUATION_MAX_AGE_MS).toISOString()}::timestamptz + or (sr.finished_at > ${new Date(at.getTime() - STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS).toISOString()}::timestamptz + and ${setupFailureBeforeProviderWorkSql("sr")})))) and not (${issues.status} = 'blocked' and ra.cause not in ('configuration_incomplete', 'ownership_owner_unprovable') and ${latestRunRefusedAtDispatch(at)}))`, // An assignee that cannot take work (paused, being set up, held) is diff --git a/server/src/services/recovery/stranded-hold-continuation.ts b/server/src/services/recovery/stranded-hold-continuation.ts index d23d67fcd4f..c63a0ec6b05 100644 --- a/server/src/services/recovery/stranded-hold-continuation.ts +++ b/server/src/services/recovery/stranded-hold-continuation.ts @@ -1,6 +1,14 @@ -import { continuesAutomatically } from "../continuation-cause.js"; +import { continuesAutomatically, isSetupFailureBeforeProviderWork } from "../continuation-cause.js"; +import { STALE_BLOCK_MS } from "./assigned-work-invariant.js"; export const STRANDED_CONTINUATION_MAX_AGE_MS = 24 * 60 * 60_000; +/** + * A task blocked by a setup failure before any provider work never started, + * so continuing it days later repeats nothing: it stays eligible for as long + * as the sweep continues blocks at all (STALE_BLOCK_MS), so tasks blocked + * before a release that fixed the cause continue after its deploy. + */ +export const STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS = STALE_BLOCK_MS; export const STRANDED_KIND = "stranded_assigned_issue"; export type StrandedHoldRun = { @@ -24,7 +32,9 @@ export function strandedHoldContinuesAutomatically( ): boolean { if (hold.kind !== STRANDED_KIND || hold.ownerType !== "board") return false; if (!run || !assigneeAgentId || run.agentId !== assigneeAgentId || !run.finishedAt) return false; - if (now.getTime() - run.finishedAt.getTime() > STRANDED_CONTINUATION_MAX_AGE_MS) return false; + const maxAge = isSetupFailureBeforeProviderWork({ errorCode: run.errorCode, resultJson: { executionRecovery: run.executionRecovery } }) + ? STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS : STRANDED_CONTINUATION_MAX_AGE_MS; + if (now.getTime() - run.finishedAt.getTime() > maxAge) return false; return strandedRunCauseIsTemporary(run); }