diff --git a/server/src/__tests__/assigned-work-invariant.test.ts b/server/src/__tests__/assigned-work-invariant.test.ts index 398afef8c42..12fec20f5c1 100644 --- a/server/src/__tests__/assigned-work-invariant.test.ts +++ b/server/src/__tests__/assigned-work-invariant.test.ts @@ -306,6 +306,73 @@ describePostgres("assigned-work invariant sweep", () => { expect(queue.calls).toHaveLength(1); }, 60_000); + it("continues a chat-channel task blocked by a legacy setup failure before provider work, with or without a hold", 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."; + // The shape two GitHub review tasks on staging were left in: the task's only + // run, legacy, failed in setup about 43 hours earlier, before provider work. + async function blockedReviewTask(input: { hold: boolean; providerWorkStarted?: boolean; endedAgoMs?: number }) { + const endedAgoMs = input.endedAgoMs ?? 43 * HOUR; + const blockedAt = new Date(Date.now() - endedAgoMs + 1_000); + const issueId = await f.issue({ status: "blocked", originKind: "chat_channel", responsibleUserId: "owner-user", blockedTransitionAt: blockedAt, updatedAt: blockedAt }); + const run = await f.run(issueId, { status: "failed", runtimeMode: "legacy", errorCode: "setup_failed", livenessState: "failed", + error: qualification, resultJson: { stopReason: "adapter_failed", failureCause: "lease_acquire_failed", timeoutFired: false, + timeoutSource: null, timeoutConfigured: false, effectiveTimeoutSec: 0, + executionRecovery: { kind: "bootstrap", providerWorkStarted: input.providerWorkStarted ?? false } }, + startedAt: new Date(Date.now() - endedAgoMs - 60_000), finishedAt: new Date(Date.now() - endedAgoMs), + createdAt: new Date(Date.now() - endedAgoMs - 60_000) }); + if (input.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 }); + } + 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; + } + const held = await blockedReviewTask({ hold: true }); + const unheld = await blockedReviewTask({ hold: false }); + const workStarted = await blockedReviewTask({ hold: false, providerWorkStarted: true }); + const waitingForMessage = await f.issue({ status: "in_progress", originKind: "chat_channel" }); + 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).toEqual(expect.arrayContaining([held, unheld])); + expect(suspects).not.toContain(workStarted); + expect(suspects).not.toContain(waitingForMessage); + + for (const issueId of [held, unheld]) { + expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId })) + .toMatchObject({ outcome: "repaired", verdict: { reason: "recovery_block" } }); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).not.toBe("blocked"); + } + expect(queue.calls.map(call => call.issueId).sort()).toEqual([held, unheld].sort()); + // A chat task whose agent may have started work still waits for its conversation. + expect(await recovery.assignedWork.checkIssue({ companyId: f.companyId, issueId: workStarted })) + .toMatchObject({ outcome: "ok", verdict: { clause: "waiting", reason: "conversation" } }); + expect(queue.calls).toHaveLength(2); + + // With the real wake queue, the continuation of such a chat task is admitted as a new run. + const real = await blockedReviewTask({ hold: true }); + const heartbeat = heartbeatService(db); + try { + expect(await heartbeat.checkAssignedWorkInvariant({ companyId: f.companyId, issueId: real })) + .toMatchObject({ outcome: "repaired" }); + const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), + sqlTag`${heartbeatRuns.contextSnapshot}->>'issueId' = ${real}`)); + expect(runs).toHaveLength(2); + expect(runs.find(row => row.errorCode !== "setup_failed")?.contextSnapshot) + .toMatchObject({ wakeReason: "issue_continuation_needed", issueId: real }); + } finally { + await heartbeat.drainActiveRunExecutions(); + } + }, 120_000); + it("leaves a task blocked under an active recovery hold to the hold's owner and reports it", async () => { const f = await seedCompany(); const issueId = await f.issue({ status: "blocked", blockedTransitionAt: new Date(Date.now() - 2 * HOUR) }); diff --git a/server/src/services/recovery/assigned-work-sweep.ts b/server/src/services/recovery/assigned-work-sweep.ts index 4c8a61b77d2..f96dd78a446 100644 --- a/server/src/services/recovery/assigned-work-sweep.ts +++ b/server/src/services/recovery/assigned-work-sweep.ts @@ -42,7 +42,7 @@ 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 { setupFailureBeforeProviderWorkSql } from "../continuation-cause.js"; +import { isSetupFailureBeforeProviderWork, 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 { @@ -91,6 +91,13 @@ type IssueRow = Pick; +/** TS twin of `latestRunFailedBeforeProviderWork` for the loaded facts. */ +function chatFailedBeforeProviderWork(latest: RunRow | null, issue: Pick, at: Date): boolean { + if (!latest || latest.status !== "failed" || latest.agentId !== issue.assigneeAgentId || !latest.finishedAt) return false; + if (at.getTime() - new Date(latest.finishedAt).getTime() > STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS) return false; + return isSetupFailureBeforeProviderWork({ errorCode: latest.errorCode, resultJson: latest.resultJson }); +} + type RunRow = Pick & { issueId: string }; @@ -223,7 +230,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { r.finished_at as "finishedAt", r.scheduled_retry_at as "scheduledRetryAt", r.controller_boot_id as "controllerBootId", r.controller_lease_expires_at as "controllerLeaseExpiresAt", r.controller_process as "controllerProcess", - jsonb_build_object('cancelledByActorType', r.result_json->'cancelledByActorType') as "resultJson" + jsonb_build_object('cancelledByActorType', r.result_json->'cancelledByActorType', + 'executionRecovery', r.result_json->'executionRecovery') as "resultJson" from heartbeat_runs r where r.company_id = ${companyId} and (r.context_snapshot->>'issueId') = requested.id order by r.created_at desc limit 1 @@ -431,7 +439,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { createdAt: issue.createdAt, unblockOwner: (issue.unblockDescriptor?.owner ?? null) as AssignedWorkFacts["issue"]["unblockOwner"], monitorNextCheckAt: issue.monitorNextCheckAt, - isConversation: Boolean(issue.conversationAgentId) || issue.originKind === "chat_channel", + isConversation: Boolean(issue.conversationAgentId) + || (issue.originKind === "chat_channel" && !(issue.status === "blocked" && chatFailedBeforeProviderWork(latest, issue, at))), awaitingFirstMessage: onboardingIds.has(issue.id), }, activeRuns: ownedRuns, @@ -498,9 +507,21 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { * The cheap, indexed pre-filter the sweep reconstructs from: open assigned * tasks with no run that is plainly live, no pending wake and no pending * question. Everything it lets through is judged by the full predicate. - * Chat conversations and blocks older than the stale window are left out: + * Chat conversations (except a blocked chat task whose run failed before + * provider work) and blocks older than the stale window are left out: * the first wait on a person's message, the second is only reported. */ + /** A chat task whose latest run, its assignee's, failed in setup before any + * provider work: the agent never received the message, so the task waits on + * the system, not on the person's next message. */ + function latestRunFailedBeforeProviderWork(at: Date) { + return sql`coalesce((select lr.status = 'failed' and lr.agent_id = ${issues.assigneeAgentId} + and lr.finished_at > ${new Date(at.getTime() - STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS).toISOString()}::timestamptz + and ${setupFailureBeforeProviderWorkSql("lr")} + from heartbeat_runs lr where lr.company_id = ${issues.companyId} and (lr.context_snapshot->>'issueId') = ${issues.id}::text + order by lr.created_at desc limit 1), false)`; + } + function latestRunRefusedAtDispatch(at: Date) { return sql`coalesce((select lr.status = 'cancelled' and lr.started_at is null and lr.error_code = 'execution_reconciliation_required' and lr.finished_at > ${new Date(at.getTime() - STRANDED_CONTINUATION_MAX_AGE_MS).toISOString()}::timestamptz @@ -535,7 +556,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { isNull(issues.assigneeUserId), isNull(issues.hiddenAt), isNull(issues.conversationAgentId), - sql`coalesce(${issues.originKind}, '') <> 'chat_channel'`, + sql`(coalesce(${issues.originKind}, '') <> 'chat_channel' + or (${issues.status} = 'blocked' and ${latestRunFailedBeforeProviderWork(at)}))`, sql`(${issues.status} <> 'blocked' or coalesce(${issues.blockedTransitionAt}, ${issues.updatedAt}) > ${new Date(at.getTime() - STALE_BLOCK_MS).toISOString()}::timestamptz)`, sql`(${issues.monitorNextCheckAt} is null or ${issues.monitorNextCheckAt} <= ${at.toISOString()}::timestamptz)`, // A legacy run whose controller lease lapsed may have lost its owner;