Merge remote-tracking branch 'fork/fix/reject-terminal-run-checkouts' into fix/reject-terminal-run-checkouts
# Conflicts: # server/src/__tests__/heartbeat-process-recovery.test.ts # server/src/services/heartbeat.ts
This commit is contained in:
commit
bfeef2ee10
|
|
@ -106,7 +106,6 @@ import {
|
|||
redactDetectedSuccessfulRunProgressSummaryForBoard,
|
||||
redactSuccessfulRunHandoffEvidence,
|
||||
} from "../services/heartbeat.ts";
|
||||
import { recoveryService } from "../services/recovery/service.ts";
|
||||
import {
|
||||
readHotRestartIntent,
|
||||
resolveLegacyHotRestartIntentPath,
|
||||
|
|
@ -575,45 +574,6 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
|||
return { companyId, agentId, runId, wakeupRequestId, issueId };
|
||||
}
|
||||
|
||||
async function holdIssueRowLock(issueId: string) {
|
||||
let signalLocked!: () => void;
|
||||
let releaseLock!: () => void;
|
||||
const locked = new Promise<void>((resolve) => {
|
||||
signalLocked = resolve;
|
||||
});
|
||||
const release = new Promise<void>((resolve) => {
|
||||
releaseLock = resolve;
|
||||
});
|
||||
const transaction = db.transaction(async (tx) => {
|
||||
await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, issueId)).for("update");
|
||||
signalLocked();
|
||||
await release;
|
||||
});
|
||||
await locked;
|
||||
return async () => {
|
||||
releaseLock();
|
||||
await transaction;
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForIssueRowLockWait() {
|
||||
for (let attempt = 0; attempt < 80; attempt += 1) {
|
||||
const [waiting] = await db.execute<{ waiting: boolean }>(sql`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM pg_stat_activity
|
||||
WHERE state = 'active'
|
||||
AND wait_event_type = 'Lock'
|
||||
AND query ILIKE '%from "issues"%'
|
||||
AND query ILIKE '%for update%'
|
||||
) AS waiting
|
||||
`);
|
||||
if (waiting?.waiting) return true;
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function seedEnvironmentLeaseFixture(input: {
|
||||
companyId: string;
|
||||
runId: string;
|
||||
|
|
@ -1374,125 +1334,78 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
|||
expect(checkoutReleasedIssue?.checkoutRunId).toBeNull();
|
||||
});
|
||||
|
||||
it("serializes a process-loss retry before successful-run recovery can block the issue", async () => {
|
||||
let releaseRetryExecution!: () => void;
|
||||
const retryExecutionCanFinish = new Promise<void>((resolve) => {
|
||||
releaseRetryExecution = resolve;
|
||||
});
|
||||
mockAdapterExecute.mockImplementationOnce(async () => {
|
||||
await retryExecutionCanFinish;
|
||||
return {
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
errorMessage: null,
|
||||
summary: "Recovered the process-loss continuation.",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
};
|
||||
});
|
||||
|
||||
const { companyId, agentId, runId, issueId } = await seedRunFixture({
|
||||
it("does not publish a process-loss retry after concurrent recovery wins the issue lock", async () => {
|
||||
const { agentId, runId, issueId } = await seedRunFixture({
|
||||
agentStatus: "idle",
|
||||
processPid: 999_999_999,
|
||||
});
|
||||
const sourceIssue = await db
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
.then((rows) => rows[0]!);
|
||||
const heartbeat = heartbeatService(db);
|
||||
const recovery = recoveryService(db, { enqueueWakeup: vi.fn(async () => null) });
|
||||
const releaseInitialLock = await holdIssueRowLock(issueId);
|
||||
|
||||
const reapPromise = heartbeat.reapOrphanedRuns();
|
||||
const publisherWaiting = await waitForIssueRowLockWait();
|
||||
expect(publisherWaiting).toBe(true);
|
||||
|
||||
const recoveryPromise = recovery.escalateStrandedAssignedIssue({
|
||||
issue: sourceIssue,
|
||||
previousStatus: "in_progress",
|
||||
latestRun: {
|
||||
id: randomUUID(),
|
||||
agentId,
|
||||
status: "succeeded",
|
||||
error: null,
|
||||
errorCode: null,
|
||||
contextSnapshot: { issueId },
|
||||
livenessState: "needs_followup",
|
||||
},
|
||||
recoveryCause: "successful_run_missing_state",
|
||||
successfulRunHandoffEvidence: {
|
||||
sourceRunId: runId,
|
||||
correctiveRunId: null,
|
||||
missingDisposition: "clear_next_step",
|
||||
handoffAttempt: 0,
|
||||
maxHandoffAttempts: 1,
|
||||
handoffDenialReason: "corrective wake was not durably queued",
|
||||
},
|
||||
let releaseRecoveryLock!: () => void;
|
||||
const recoveryMayCommit = new Promise<void>((resolve) => {
|
||||
releaseRecoveryLock = resolve;
|
||||
});
|
||||
let recoveryLocked!: () => void;
|
||||
const recoveryHasLock = new Promise<void>((resolve) => {
|
||||
recoveryLocked = resolve;
|
||||
});
|
||||
const activeAction = await waitForValue(() =>
|
||||
db
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(and(eq(issueRecoveryActions.sourceIssueId, issueId), eq(issueRecoveryActions.status, "active")))
|
||||
.then((rows) => rows[0] ?? null)
|
||||
);
|
||||
expect(activeAction).not.toBeNull();
|
||||
|
||||
await releaseInitialLock();
|
||||
const [reapResult, escalationResult] = await Promise.all([reapPromise, recoveryPromise]);
|
||||
expect(reapResult).toEqual({ reaped: 1, runIds: [runId] });
|
||||
expect(escalationResult).toBeNull();
|
||||
const recoveryTransition = db.transaction(async (tx) => {
|
||||
await tx
|
||||
.select({ id: issues.id })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
.for("update");
|
||||
recoveryLocked();
|
||||
await recoveryMayCommit;
|
||||
await tx
|
||||
.update(issues)
|
||||
.set({
|
||||
status: "blocked",
|
||||
checkoutRunId: null,
|
||||
executionRunId: null,
|
||||
executionAgentNameKey: null,
|
||||
executionLockedAt: null,
|
||||
updatedAt: new Date("2026-03-19T00:01:00.000Z"),
|
||||
})
|
||||
.where(eq(issues.id, issueId));
|
||||
});
|
||||
await recoveryHasLock;
|
||||
|
||||
const retryRun = await db
|
||||
const reap = heartbeat.reapOrphanedRuns();
|
||||
await waitForValue(async () => db
|
||||
.select({ status: heartbeatRuns.status })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, runId))
|
||||
.then((rows) => rows[0]?.status === "failed" ? true : null));
|
||||
releaseRecoveryLock();
|
||||
|
||||
await recoveryTransition;
|
||||
await expect(reap).resolves.toEqual({ reaped: 1, runIds: [runId] });
|
||||
|
||||
const retryRuns = await db
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
expect(retryRun).toMatchObject({
|
||||
agentId,
|
||||
retryOfRunId: runId,
|
||||
processLossRetryCount: 1,
|
||||
});
|
||||
if (!retryRun) throw new Error("Expected a durable process-loss retry run");
|
||||
const retryWake = await db
|
||||
.where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.retryOfRunId, runId)));
|
||||
expect(retryRuns).toHaveLength(0);
|
||||
const retryWakeups = await db
|
||||
.select()
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, retryRun.wakeupRequestId!))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
expect(retryWake).toMatchObject({
|
||||
runId: retryRun.id,
|
||||
reason: "process_lost_retry",
|
||||
});
|
||||
expect(["queued", "claimed"]).toContain(retryWake?.status);
|
||||
|
||||
.where(and(
|
||||
eq(agentWakeupRequests.agentId, agentId),
|
||||
eq(agentWakeupRequests.reason, "process_lost_retry"),
|
||||
));
|
||||
expect(retryWakeups).toHaveLength(0);
|
||||
const currentIssue = await db
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
expect(currentIssue).toMatchObject({
|
||||
status: "in_progress",
|
||||
executionRunId: retryRun.id,
|
||||
status: "blocked",
|
||||
executionRunId: null,
|
||||
checkoutRunId: null,
|
||||
});
|
||||
|
||||
const [recoveryAction] = await db
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
||||
expect(recoveryAction).toMatchObject({
|
||||
id: activeAction?.id,
|
||||
status: "resolved",
|
||||
outcome: "restored",
|
||||
resolutionNote: "concurrent_source_path_restored",
|
||||
});
|
||||
|
||||
await db.update(issues).set({ status: "done", completedAt: new Date() }).where(eq(issues.id, issueId));
|
||||
releaseRetryExecution();
|
||||
await waitForRunToSettle(heartbeat, retryRun.id, 5_000);
|
||||
}, 15_000);
|
||||
});
|
||||
|
||||
it("restores one lost monitor dispatch before escalating a second process loss", async () => {
|
||||
const { companyId, agentId, runId, issueId } = await seedRunFixture({
|
||||
|
|
|
|||
|
|
@ -671,6 +671,112 @@ describeEmbeddedPostgres("issue recovery actions", () => {
|
|||
},
|
||||
);
|
||||
|
||||
it("keeps a concurrently published process-loss retry active and resolves provisional handoff recovery", async () => {
|
||||
const { companyId, coderId, sourceIssueId, sourceIssue } = await seedCompany();
|
||||
const recovery = recoveryService(db, { enqueueWakeup: vi.fn(async () => null) });
|
||||
const sourceRunId = randomUUID();
|
||||
const retryRunId = randomUUID();
|
||||
const wakeupRequestId = randomUUID();
|
||||
let publishRetry!: () => void;
|
||||
const retryMayPublish = new Promise<void>((resolve) => {
|
||||
publishRetry = resolve;
|
||||
});
|
||||
let retryLocked!: () => void;
|
||||
const retryHasLock = new Promise<void>((resolve) => {
|
||||
retryLocked = resolve;
|
||||
});
|
||||
|
||||
const retryPublication = db.transaction(async (tx) => {
|
||||
await tx
|
||||
.select({ id: issues.id })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, sourceIssueId))
|
||||
.for("update");
|
||||
retryLocked();
|
||||
await retryMayPublish;
|
||||
await tx.insert(agentWakeupRequests).values({
|
||||
id: wakeupRequestId,
|
||||
companyId,
|
||||
agentId: coderId,
|
||||
source: "automation",
|
||||
triggerDetail: "system",
|
||||
reason: "process_lost_retry",
|
||||
payload: { issueId: sourceIssueId, retryOfRunId: sourceRunId },
|
||||
status: "queued",
|
||||
});
|
||||
await tx.insert(heartbeatRuns).values({
|
||||
id: retryRunId,
|
||||
companyId,
|
||||
agentId: coderId,
|
||||
invocationSource: "automation",
|
||||
triggerDetail: "system",
|
||||
status: "queued",
|
||||
wakeupRequestId,
|
||||
retryOfRunId: sourceRunId,
|
||||
contextSnapshot: {
|
||||
issueId: sourceIssueId,
|
||||
wakeReason: "process_lost_retry",
|
||||
retryOfRunId: sourceRunId,
|
||||
},
|
||||
});
|
||||
await tx
|
||||
.update(agentWakeupRequests)
|
||||
.set({ runId: retryRunId })
|
||||
.where(eq(agentWakeupRequests.id, wakeupRequestId));
|
||||
await tx
|
||||
.update(issues)
|
||||
.set({
|
||||
executionRunId: retryRunId,
|
||||
executionAgentNameKey: "coder",
|
||||
executionLockedAt: new Date("2026-05-13T18:01:00.000Z"),
|
||||
updatedAt: new Date("2026-05-13T18:01:00.000Z"),
|
||||
})
|
||||
.where(eq(issues.id, sourceIssueId));
|
||||
});
|
||||
await retryHasLock;
|
||||
|
||||
const escalation = recovery.escalateStrandedAssignedIssue({
|
||||
issue: sourceIssue,
|
||||
previousStatus: "in_progress",
|
||||
latestRun: {
|
||||
id: sourceRunId,
|
||||
agentId: coderId,
|
||||
status: "succeeded",
|
||||
error: null,
|
||||
errorCode: null,
|
||||
contextSnapshot: { issueId: sourceIssueId },
|
||||
livenessState: "needs_followup",
|
||||
},
|
||||
recoveryCause: "successful_run_missing_state",
|
||||
successfulRunHandoffEvidence: {
|
||||
sourceRunId,
|
||||
correctiveRunId: null,
|
||||
missingDisposition: "clear_next_step",
|
||||
handoffAttempt: 0,
|
||||
maxHandoffAttempts: 1,
|
||||
handoffDenialReason: "corrective wake was not durably queued",
|
||||
},
|
||||
});
|
||||
|
||||
publishRetry();
|
||||
await retryPublication;
|
||||
await expect(escalation).resolves.toBeNull();
|
||||
|
||||
const [currentIssue] = await db.select().from(issues).where(eq(issues.id, sourceIssueId));
|
||||
expect(currentIssue).toMatchObject({
|
||||
status: "in_progress",
|
||||
executionRunId: retryRunId,
|
||||
});
|
||||
const activeActions = await db
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(and(
|
||||
eq(issueRecoveryActions.sourceIssueId, sourceIssueId),
|
||||
eq(issueRecoveryActions.status, "active"),
|
||||
));
|
||||
expect(activeActions).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("stands down while the latest run was cancelled by a board operator", async () => {
|
||||
const { companyId, coderId, sourceIssueId } = await seedCompany();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
|
|
|
|||
|
|
@ -460,7 +460,6 @@ const CANCELLABLE_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retr
|
|||
const HEARTBEAT_RUN_TERMINAL_STATUSES = ["succeeded", "interrupted", "failed", "cancelled", "timed_out"] as const;
|
||||
const UNSUCCESSFUL_HEARTBEAT_RUN_TERMINAL_STATUSES = ["failed", "cancelled", "timed_out"] as const;
|
||||
const TIMER_ACTIONABLE_ISSUE_STATUSES = ["todo", "in_progress"] as const;
|
||||
const PROCESS_LOSS_RETRY_ISSUE_STATUSES = ["todo", "in_progress", "in_review"] as const;
|
||||
export {
|
||||
ACTIVE_RUN_OUTPUT_CONTINUE_REARM_MS,
|
||||
ACTIVE_RUN_OUTPUT_CRITICAL_THRESHOLD_MS,
|
||||
|
|
@ -10357,48 +10356,33 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
|
|||
|
||||
const queued = await db.transaction(async (tx) => {
|
||||
if (issueId) {
|
||||
// Successful-run recovery holds this same row lock from its final path
|
||||
// scan through the blocked transition. Publish the process-loss retry
|
||||
// behind that boundary so recovery cannot miss a newly durable wake and
|
||||
// then overwrite the issue with a stale blocked disposition.
|
||||
const lockedIssue = await tx
|
||||
.select()
|
||||
// Serialize retry publication with recovery transitions for this issue.
|
||||
// Recovery holds this same row lock while it scans for durable paths and
|
||||
// decides whether to block. Taking the lock before inserting either the
|
||||
// wake or run prevents those rows from becoming provisionally durable
|
||||
// while their issue mutation is still waiting behind recovery.
|
||||
const currentIssue = await tx
|
||||
.select({ status: issues.status, executionRunId: issues.executionRunId })
|
||||
.from(issues)
|
||||
.where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId)))
|
||||
.for("update")
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
// A recovery/terminal transition that won the lock must remain
|
||||
// authoritative. In particular, do not attach a newly queued retry to
|
||||
// an issue that recovery just blocked or whose execution ownership has
|
||||
// already moved away from the lost run.
|
||||
if (
|
||||
!lockedIssue ||
|
||||
!PROCESS_LOSS_RETRY_ISSUE_STATUSES.includes(
|
||||
lockedIssue.status as (typeof PROCESS_LOSS_RETRY_ISSUE_STATUSES)[number],
|
||||
) ||
|
||||
(lockedIssue.executionRunId !== null && lockedIssue.executionRunId !== run.id) ||
|
||||
(lockedIssue.checkoutRunId !== null && lockedIssue.checkoutRunId !== run.id)
|
||||
!currentIssue ||
|
||||
currentIssue.status === "blocked" ||
|
||||
currentIssue.status === "done" ||
|
||||
currentIssue.status === "cancelled" ||
|
||||
currentIssue.executionRunId !== run.id
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sourceState = await collectDispositionRepairSourceState(tx as unknown as Db, {
|
||||
issue: lockedIssue,
|
||||
excludeRunId: run.id,
|
||||
});
|
||||
if (sourceState.hasActiveExecutionPath || sourceState.hasDurableWaitingPath) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// The optimistic lookup above avoids taking the issue lock for the common
|
||||
// already-retried case. Recheck while holding the publication boundary so
|
||||
// concurrent reapers cannot create duplicate process-loss continuations.
|
||||
const concurrentRetry = await tx
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.retryOfRunId, run.id)))
|
||||
.orderBy(asc(heartbeatRuns.createdAt))
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (concurrentRetry) return concurrentRetry;
|
||||
|
||||
const wakeupRequest = await tx
|
||||
.insert(agentWakeupRequests)
|
||||
.values({
|
||||
|
|
@ -10462,7 +10446,18 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
|
|||
return retryRun;
|
||||
});
|
||||
|
||||
if (!queued) return null;
|
||||
if (!queued) {
|
||||
await appendRunEvent(run, await nextRunEventSeq(run.id), {
|
||||
eventType: "lifecycle",
|
||||
stream: "system",
|
||||
level: "warn",
|
||||
message: "Process-loss retry suppressed because issue recovery or execution ownership changed first",
|
||||
payload: {
|
||||
issueId: issueId ?? null,
|
||||
},
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
publishLiveEvent({
|
||||
companyId: queued.companyId,
|
||||
|
|
|
|||
Loading…
Reference in New Issue