mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
fix: continue interrupted task conversations with bounded retries (#13237)
## Thinking Path > - Paperclip manages AI agents and their tasks. > - A task can outlive a provider process or a server restart. > - Legacy recovery treated unknown tool outcomes as a permanent execution hold. > - That hold could also reject a later user message. > - A conversation turn can use prior history without replaying prior tool calls. > - This pull request lets supported conversation adapters continue within the existing retry budget. > - Users can send a new message after automatic attempts stop. ## Linked Issues or Issue Description **What happened?** A server restart could interrupt a local ACP run and leave its task behind a permanent recovery hold. A later user message could be cancelled before the provider answered. The immediate recovery path could also create a successor outside the durable failure counter. **Expected behavior** Continue with a bounded new conversation turn. Preserve a compatible provider session or use full task context when it is unavailable. Do not replay recorded tools. When automatic attempts stop, allow a new user request through the normal execution gates. **Steps to reproduce** 1. Start a task with a local conversation adapter. 2. Restart the server while the provider is working. 3. Let the previous run become interrupted. 4. Send a follow-up message and observe the recovery hold on the old behavior. Related work: Refs #13075 for durable task recovery. Refs #12946 for retry-limit and checkout-lock handling. This change routes conversation recovery through the existing bounded scheduler. ## What Changed - Mark supported local conversation failures for continuation. Keep native-runner and non-conversation recovery rules. - Carry an interruption notice into the next turn. Retain stopped ACP session history even when a write outcome is unknown. - Clear unavailable ACP sessions so the next bounded attempt can use full task context. - Route immediate failure recovery through the same durable scheduler as process-loss recovery. Release only the predecessor checkout when its retry takes ownership. - Retire obsolete conversation holds using immutable run evidence, in bounded batches with an activity record. Preserve outcome evidence and do not wake historical tasks. - Block actual admission and Resume while a predecessor process or environment lease is still active. Keep the original interruption notice after a rejected wake. Preserve the upstream blocked-wake waiting contract: bounded retry planning can happen during cleanup, while deferred messages and execution remain gated. - Add subprocess and database regression tests. Update the execution contract. - Add the current thread-status field to the native recovery provider fixture so its damaged-journal test reaches the intended boundary. Tolerate an already-exited fixture process during test cleanup while still asserting both processes terminate. ## Verification - Workspace typecheck passed: `pnpm -r typecheck`. - Build passed: `pnpm build`. - Module boundaries passed: `pnpm check:module-boundaries`. - Focused tests passed: 293 recovery/session/dispatch tests, 66 retry and response-gate tests, and 37 native-session tests. Some suites overlap. - Tests cover interrupted writes, missing sessions, concurrent retries, restart persistence, pending questions and approvals, execution gates, and historical holds. - Built the Rust test executables with `pnpm --filter @paperclipai/paperclip-runner build:rust` for native-runner verification. - Full Vitest coverage verified locally using the repository’s general and serialized shards, with focused reruns for failures and files not reached after a shard stopped. The ownership-gate regression is fixed and the complete affected server shard passes (1,390 tests). Local parallel runs also hit temporary-directory, resource, and timing failures; those suites pass with canonical temporary paths and sequential reruns. No test timeouts were increased. - Final merged-branch regression run: 577 tests pass across process recovery, retry scheduling, liveness, durable chat, wake-queue application/adapter, dispatch, continuation, native sessions, and task chat. Earlier focused verification also passed 19 native control tests. Token gates and whitespace validation pass. - Browser verification passed all three ACP Stop/continue/pause scenarios, including a rerun after merging the upstream waiting behavior: `PAPERCLIP_E2E_PORT=3397 pnpm test:e2e tests/e2e/acp-stop-continuation.spec.ts`. The interrupted-write case verifies that follow-up completes without a repeated write. - Final-head [CI run 34625037394](https://github.com/paperclipai/paperclip/actions/runs/34625037394) passed on `06ac4bd9d150f8b209a96e5fd609c696958794a0`: all 31 reported checks are green, including server/workspace suites, all browser shards, native runner verification, build, typecheck, release dry run, and aggregate gates. The two conditional Storybook checks were skipped. Greptile reviewed this exact commit at 5/5; all review threads are resolved. ## Risks - A new model turn can choose to repeat an action. Paperclip does not replay recorded tool calls and does not certify unknown action outcomes. - Conversation adapters now stop after their retry budget instead of requiring action reconciliation. Explicit Stop, pause, dependency, approval, budget, and ownership gates remain in force. - No schema migration or dependency changes. Historical holds are folded without changing task status or waking work. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools, code execution, and test execution. The session does not expose a more specific model build ID or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
42a4f5b15b
commit
b1efd65edc
32 files changed
+696
-168
No files matched your search
@@ -650,7 +650,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
async function seedRunFixture(input?: {
|
||||
adapterType?: string;
|
||||
agentStatus?: "paused" | "idle" | "running";
|
||||
runStatus?: "running" | "queued" | "failed";
|
||||
runStatus?: "running" | "queued" | "failed" | "interrupted";
|
||||
processPid?: number | null;
|
||||
processGroupId?: number | null;
|
||||
processLossRetryCount?: number;
|
||||
@@ -719,10 +719,14 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
...(input?.runtimeMode ? { runtimeMode: input.runtimeMode } : {}),
|
||||
errorCode: input?.runErrorCode ?? null,
|
||||
error: input?.runError ?? null,
|
||||
nextEventSeq: 2,
|
||||
startedAt: now,
|
||||
updatedAt: new Date("2026-03-19T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId,
|
||||
seq: 1, eventType: "adapter.invoke", payload: { adapterType: input?.adapterType ?? "codex_local" } });
|
||||
|
||||
if (input?.includeIssue !== false) {
|
||||
await db.insert(issues).values({
|
||||
id: issueId,
|
||||
@@ -1459,7 +1463,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
return { companyId, agentId, runId, wakeupRequestId, issueId };
|
||||
}
|
||||
|
||||
it("persists the normalized failure and exposes an operator recovery action", async () => {
|
||||
it("persists the normalized failure without permanently blocking the conversation", async () => {
|
||||
mockAdapterExecute.mockResolvedValueOnce({
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
@@ -1483,12 +1487,6 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
.from(agentRuntimeState)
|
||||
.where(eq(agentRuntimeState.agentId, agentId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
const agent = await db
|
||||
.select({ status: agents.status, errorReason: agents.errorReason })
|
||||
.from(agents)
|
||||
.where(eq(agents.id, agentId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
const recoveryRun = await db
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
@@ -1497,16 +1495,8 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
|
||||
expect(run).toMatchObject({ status: "failed", error: "Adapter failed" });
|
||||
expect(runtime?.lastError).toBe("Adapter failed");
|
||||
expect(recoveryRun).toBeNull();
|
||||
const [action] = await db
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
||||
expect(action).toMatchObject({
|
||||
cause: "legacy_execution_requires_reconciliation",
|
||||
ownerType: "board",
|
||||
returnOwnerAgentId: agentId,
|
||||
});
|
||||
expect(recoveryRun).toMatchObject({ retryOfRunId: runId, scheduledRetryAttempt: 1 });
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
||||
const missingCommentWakeups = await db
|
||||
.select({ id: agentWakeupRequests.id })
|
||||
.from(agentWakeupRequests)
|
||||
@@ -1517,7 +1507,6 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
),
|
||||
);
|
||||
expect(missingCommentWakeups).toHaveLength(0);
|
||||
expect(agent?.status).not.toBe("running");
|
||||
});
|
||||
|
||||
it("does not immediately continue a low-trust preflight setup failure", async () => {
|
||||
@@ -1624,11 +1613,71 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
expect(recoveryRuns).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("does not relabel a lost process run when its agent changes to a conversation adapter", async () => {
|
||||
const { companyId, agentId, runId } = await seedRunFixture({ adapterType: "process", processPid: 99999999 });
|
||||
await db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, agentId));
|
||||
await heartbeatService(db).reapOrphanedRuns();
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
expect(run.status).toBe("failed");
|
||||
expect(run.resultJson?.conversationContinuation).toBeUndefined();
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.each([false, true])("waits for a live terminal predecessor before a new turn (historical hold: %s)", async withHold => {
|
||||
const child = spawnAliveProcess();
|
||||
childProcesses.add(child);
|
||||
const { runId, issueId, companyId } = await seedRunFixture({
|
||||
agentStatus: "idle", runStatus: "interrupted", runErrorCode: "server_shutdown_interrupted", processPid: child.pid!,
|
||||
});
|
||||
await db.update(heartbeatRuns).set({ resultJson: { conversationContinuation: "continue_conversation_v1" } }).where(eq(heartbeatRuns.id, runId));
|
||||
if (withHold) await db.insert(issueRecoveryActions).values({
|
||||
companyId, sourceIssueId: issueId, kind: "active_run_watchdog", status: "active", ownerType: "board",
|
||||
cause: "legacy_execution_requires_reconciliation", fingerprint: runId,
|
||||
evidence: { runId, automaticRecovery: { replay: "blocked" } }, nextAction: "Wait for the previous execution to stop.",
|
||||
});
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId, cause: "execution_owner_active" });
|
||||
// Scheduling itself has no execution authority. Actual queued admission
|
||||
// must still block while the predecessor owns a process or lease.
|
||||
const queuedId = randomUUID();
|
||||
const previous = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!;
|
||||
await db.insert(heartbeatRuns).values({ id: queuedId, companyId, agentId: previous.agentId,
|
||||
status: "queued", contextSnapshot: { issueId, wakeReason: "issue_commented" } });
|
||||
const { createPostgresRunDispatchAdapter } = await import("../modules/run-dispatch/adapters/postgres.js");
|
||||
expect(await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
|
||||
expectedStatus: "queued", now: new Date() })).toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
|
||||
const { settleUnrecoverableExecutions } = await import("../services/execution-recovery-resolution.js");
|
||||
await settleUnrecoverableExecutions(db);
|
||||
if (withHold) expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId)))[0].status).toBe("active");
|
||||
expect(isPidAlive(child.pid!)).toBe(true);
|
||||
child.kill("SIGTERM");
|
||||
await waitForPidExit(child.pid!);
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
||||
});
|
||||
|
||||
it("waits for a terminal predecessor's environment lease to be released", async () => {
|
||||
const { companyId, issueId, runId } = await seedRunFixture({ agentStatus: "idle", runStatus: "interrupted" });
|
||||
await db.update(heartbeatRuns).set({ resultJson: { conversationContinuation: "continue_conversation_v1" } }).where(eq(heartbeatRuns.id, runId));
|
||||
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId, status: "active" }).returning();
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ runId, cause: "execution_owner_active" });
|
||||
// Scheduling itself has no execution authority. Actual queued admission
|
||||
// must still block while the predecessor owns a process or lease.
|
||||
const queuedId = randomUUID();
|
||||
const previous = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!;
|
||||
await db.insert(heartbeatRuns).values({ id: queuedId, companyId, agentId: previous.agentId,
|
||||
status: "queued", contextSnapshot: { issueId, wakeReason: "issue_commented" } });
|
||||
const { createPostgresRunDispatchAdapter } = await import("../modules/run-dispatch/adapters/postgres.js");
|
||||
expect(await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({ companyId, runId: queuedId,
|
||||
expectedStatus: "queued", now: new Date() })).toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
|
||||
await db.update(environmentLeases).set({ releasedAt: new Date(), status: "released" }).where(eq(environmentLeases.id, lease!.id));
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps an unsafe Stop blocked when recovery sees a deferred human comment", async () => {
|
||||
const { companyId, agentId, issueId, runId } = await seedStrandedIssueFixture({
|
||||
status: "in_progress", runStatus: "cancelled",
|
||||
resultJson: { executionCancellation: { state: "acknowledged" } },
|
||||
});
|
||||
await db.update(agents).set({ adapterType: "process" }).where(eq(agents.id, agentId));
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
await terminalizeLegacyExecution({ db, run, status: "cancelled" });
|
||||
const wakeId = randomUUID();
|
||||
@@ -2296,7 +2345,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
expect(runs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("holds an unknown dead-provider outcome for reconciliation", async () => {
|
||||
it("schedules one conversation continuation after losing the provider", async () => {
|
||||
const { agentId, runId, issueId } = await seedRunFixture({
|
||||
agentStatus: "idle",
|
||||
processPid: 999_999_999,
|
||||
@@ -2317,11 +2366,11 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.agentId, agentId));
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs).toHaveLength(2);
|
||||
|
||||
const failedRun = runs.find((row) => row.id === runId);
|
||||
const retryRuns = runs.filter((row) => row.retryOfRunId === runId);
|
||||
expect(retryRuns).toHaveLength(0);
|
||||
expect(retryRuns).toHaveLength(1);
|
||||
const retryRun = retryRuns[0];
|
||||
expect(failedRun?.status).toBe("failed");
|
||||
expect(failedRun?.errorCode).toBe("process_lost");
|
||||
@@ -2336,18 +2385,15 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
||||
expect(action).toMatchObject({
|
||||
cause: "legacy_execution_requires_reconciliation",
|
||||
returnOwnerAgentId: agentId,
|
||||
ownerType: "board",
|
||||
});
|
||||
expect(action).toBeUndefined();
|
||||
expect(retryRun).toMatchObject({ status: "scheduled_retry", scheduledRetryAttempt: 1 });
|
||||
await heartbeat.reapOrphanedRuns();
|
||||
expect(
|
||||
await db
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.agentId, agentId)),
|
||||
).toHaveLength(1);
|
||||
).toHaveLength(2);
|
||||
|
||||
const issue = await waitForValue(async () =>
|
||||
db
|
||||
@@ -2769,7 +2815,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
[runId],
|
||||
);
|
||||
expect(drain.interruptedRunIds).toEqual([runId]);
|
||||
expect(drain.retryRunIds).toHaveLength(0);
|
||||
expect(drain.retryRunIds).toHaveLength(1);
|
||||
await waitForPidExit(child.pid!);
|
||||
|
||||
const reconciliation = await heartbeat.reconcileHotRestartAdoption(
|
||||
@@ -2791,7 +2837,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
status: "interrupted",
|
||||
errorCode: "server_shutdown_interrupted",
|
||||
});
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs).toHaveLength(2);
|
||||
|
||||
const report = JSON.parse(
|
||||
await fs.readFile(resolveHotRestartReportPath(home), "utf8"),
|
||||
@@ -3390,6 +3436,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
|
||||
it("terminalizes an unsupported legacy session on shutdown without speculative replay", async () => {
|
||||
const { agentId, runId, issueId, wakeupRequestId } = await seedRunFixture({
|
||||
adapterType: "process",
|
||||
agentStatus: "running",
|
||||
});
|
||||
const result = await heartbeatService(db).drainRunningRunsForShutdown(
|
||||
@@ -3541,6 +3588,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
|
||||
it("does not duplicate a legacy reconciliation action across repeated shutdowns", async () => {
|
||||
const { agentId, runId, issueId } = await seedRunFixture({
|
||||
adapterType: "process",
|
||||
agentStatus: "running",
|
||||
});
|
||||
const heartbeat = heartbeatService(db);
|
||||
@@ -3587,12 +3635,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId)),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
cause: "legacy_execution_requires_reconciliation",
|
||||
evidence: expect.objectContaining({ attempt: 3 }),
|
||||
}),
|
||||
]);
|
||||
).toEqual([]);
|
||||
const run = await heartbeatService(db).getRun(runId);
|
||||
expect(await getExecutionBlocker(db, run!.companyId, issueId)).toBeNull();
|
||||
});
|
||||
|
||||
it("releases active environment leases when an orphaned run is reaped", async () => {
|
||||
@@ -3658,6 +3703,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
|
||||
it("does not bypass unknown process outcomes through immediate continuation recovery", async () => {
|
||||
const { agentId, runId, issueId } = await seedRunFixture({
|
||||
adapterType: "process",
|
||||
agentStatus: "idle",
|
||||
processPid: 999_999_999,
|
||||
processLossRetryCount: 1,
|
||||
@@ -3688,6 +3734,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
it("blocks failed recovery work in place during immediate terminal-run cleanup", async () => {
|
||||
const sourceIssueId = randomUUID();
|
||||
const { companyId, agentId, runId, issueId } = await seedRunFixture({
|
||||
adapterType: "process",
|
||||
agentStatus: "idle",
|
||||
processPid: 999_999_999,
|
||||
processLossRetryCount: 1,
|
||||
@@ -3824,7 +3871,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
expect(comments).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("does not treat a transient remote-compaction failure as evidence of safe replay", async () => {
|
||||
it("allows conversation continuation after a transient remote-compaction failure", async () => {
|
||||
mockAdapterExecute.mockResolvedValueOnce({
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
@@ -3845,33 +3892,22 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
|
||||
await heartbeat.resumeQueuedRuns();
|
||||
await waitForRunToSettle(heartbeat, runId);
|
||||
await heartbeat.waitForRunExecutionDrain(runId);
|
||||
|
||||
expect(
|
||||
await db
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.agentId, agentId)),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
id: runId,
|
||||
status: "failed",
|
||||
errorCode: "adapter_failed",
|
||||
resultJson: expect.objectContaining({
|
||||
errorFamily: "transient_upstream",
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId));
|
||||
expect(runs).toHaveLength(2);
|
||||
expect(runs.find(run => run.id === runId)).toMatchObject({
|
||||
status: "failed", errorCode: "adapter_failed", resultJson: { errorFamily: "transient_upstream" },
|
||||
});
|
||||
expect(runs.find(run => run.retryOfRunId === runId)).toMatchObject({
|
||||
status: "scheduled_retry", scheduledRetryAttempt: 1,
|
||||
});
|
||||
expect(
|
||||
await db
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId)),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
cause: "legacy_execution_requires_reconciliation",
|
||||
ownerType: "board",
|
||||
}),
|
||||
]);
|
||||
).toEqual([]);
|
||||
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -7611,7 +7647,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
const events = await db
|
||||
.select()
|
||||
.from(heartbeatRunEvents)
|
||||
.where(eq(heartbeatRunEvents.runId, runId));
|
||||
.where(and(eq(heartbeatRunEvents.runId, runId), eq(heartbeatRunEvents.eventType, "lifecycle")));
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({
|
||||
eventType: "lifecycle",
|
||||
|
||||
@@ -3,6 +3,9 @@ import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
approvals,
|
||||
issueApprovals,
|
||||
issueThreadInteractions,
|
||||
agentRuntimeState,
|
||||
agentWakeupRequests,
|
||||
activityLog,
|
||||
@@ -164,6 +167,7 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
|
||||
await db.delete(environmentLeases);
|
||||
await db.delete(issueRelations);
|
||||
await db.delete(issues);
|
||||
await db.delete(approvals);
|
||||
await db.delete(executionWorkspaces);
|
||||
await db.delete(projects);
|
||||
await cleanupHeartbeatRunDependents();
|
||||
@@ -445,6 +449,87 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
|
||||
return { companyId, agentId, issueId, runId, now };
|
||||
}
|
||||
|
||||
it("bounds interrupted conversations across restarts and concurrent scheduling", async () => {
|
||||
const { companyId, issueId, runId, now } = await seedMaxTurnFixture();
|
||||
const resultJson = { conversationContinuation: "continue_conversation_v1" };
|
||||
await db.update(heartbeatRuns).set({ status: "interrupted", errorCode: "server_shutdown_interrupted", resultJson })
|
||||
.where(eq(heartbeatRuns.id, runId));
|
||||
let predecessor = runId;
|
||||
for (const attempt of [1, 2]) {
|
||||
const restarted = heartbeatService(db);
|
||||
const outcomes = await Promise.all([
|
||||
restarted.scheduleBoundedRetry(predecessor, { now, random: () => 0 }),
|
||||
restarted.scheduleBoundedRetry(predecessor, { now, random: () => 0 }),
|
||||
]);
|
||||
expect(outcomes.every(outcome => outcome.outcome === "scheduled")).toBe(true);
|
||||
const children = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, predecessor));
|
||||
expect(children).toHaveLength(1);
|
||||
expect(children[0]).toMatchObject({ scheduledRetryAttempt: attempt });
|
||||
predecessor = children[0]!.id;
|
||||
await db.update(heartbeatRuns).set({ status: "interrupted", finishedAt: now, resultJson })
|
||||
.where(eq(heartbeatRuns.id, predecessor));
|
||||
}
|
||||
expect(await heartbeatService(db).scheduleBoundedRetry(predecessor, { now }))
|
||||
.toMatchObject({ outcome: "retry_exhausted" });
|
||||
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId))).toHaveLength(3);
|
||||
// Exhaustion leaves the task available to a new explicit request.
|
||||
const { getExecutionBlocker } = await import("../services/execution-blocker.js");
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["dependency", "disabled", "reassigned"])("respects the %s gate for interrupted conversations", async gate => {
|
||||
const { companyId, agentId, issueId, runId, now } = await seedMaxTurnFixture();
|
||||
await db.update(heartbeatRuns).set({ status: "interrupted", errorCode: "process_lost",
|
||||
resultJson: { conversationContinuation: "continue_conversation_v1" } }).where(eq(heartbeatRuns.id, runId));
|
||||
if (gate === "dependency") {
|
||||
const blockerId = randomUUID();
|
||||
await db.insert(issues).values({ id: blockerId, companyId, title: "Required work", status: "todo" });
|
||||
await db.insert(issueRelations).values({ companyId, issueId: blockerId, relatedIssueId: issueId, type: "blocks" });
|
||||
} else if (gate === "disabled") {
|
||||
await db.update(agents).set({ runtimeConfig: { heartbeat: { wakeOnDemand: false } } }).where(eq(agents.id, agentId));
|
||||
} else {
|
||||
await db.update(issues).set({ assigneeAgentId: null }).where(eq(issues.id, issueId));
|
||||
}
|
||||
expect(await heartbeat.scheduleBoundedRetry(runId, { now })).toMatchObject({ outcome: "not_scheduled" });
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["interaction", false], ["approval", false], ["interaction", true], ["approval", true],
|
||||
] as const)("waits for a pending %s before continuing (already scheduled: %s)", async (kind, alreadyScheduled) => {
|
||||
const { companyId, issueId, runId, now } = await seedMaxTurnFixture();
|
||||
await db.update(heartbeatRuns).set({ status: "interrupted", errorCode: "process_lost",
|
||||
resultJson: { conversationContinuation: "continue_conversation_v1" } }).where(eq(heartbeatRuns.id, runId));
|
||||
let retryRunId = runId;
|
||||
if (alreadyScheduled) {
|
||||
const scheduled = await heartbeat.scheduleBoundedRetry(runId, { now, random: () => 0 });
|
||||
expect(scheduled.outcome).toBe("scheduled");
|
||||
if (scheduled.outcome !== "scheduled") throw new Error("Expected a retry");
|
||||
retryRunId = scheduled.run.id;
|
||||
}
|
||||
if (kind === "interaction") {
|
||||
await db.insert(issueThreadInteractions).values({ companyId, issueId, kind: "ask_user_questions",
|
||||
status: "pending", payload: { version: 1, questions: [] } });
|
||||
} else {
|
||||
const approvalId = randomUUID();
|
||||
await db.insert(approvals).values({ id: approvalId, companyId, type: "hire_agent", status: "pending", payload: {} });
|
||||
await db.insert(issueApprovals).values({ companyId, issueId, approvalId });
|
||||
}
|
||||
if (alreadyScheduled) {
|
||||
const adapter = createPostgresRunDispatchAdapter(db);
|
||||
expect(await adapter.promoteOrCancelDueRetry({ companyId, runId: retryRunId, now: new Date(now.getTime() + 60_000) }))
|
||||
.toMatchObject({ outcome: "gate_suppressed", errorCode: "issue_waiting_for_response" });
|
||||
const stopped = await heartbeat.getRun(retryRunId);
|
||||
expect(stopped?.status).toBe("cancelled");
|
||||
const { legacyExecutionNeedsReconciliation } = await import("../services/legacy-execution-recovery.js");
|
||||
expect(legacyExecutionNeedsReconciliation(stopped!)).toBe(false);
|
||||
} else {
|
||||
expect(await heartbeat.scheduleBoundedRetry(runId, { now }))
|
||||
.toMatchObject({ outcome: "not_scheduled", errorCode: "issue_waiting_for_response" });
|
||||
}
|
||||
});
|
||||
|
||||
it("schedules a retry with durable metadata and only promotes it when due", async () => {
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
|
||||
@@ -19,6 +19,8 @@ const mockTreeControlService = vi.hoisted(() => ({
|
||||
|
||||
const mockReplayBlocks = vi.hoisted(() => vi.fn());
|
||||
const mockReplayWhere = vi.hoisted(() => vi.fn());
|
||||
const mockExecutionBlocker = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../services/execution-blocker.js", () => ({ getExecutionBlocker: mockExecutionBlocker }));
|
||||
|
||||
const mockLogActivity = vi.hoisted(() => vi.fn());
|
||||
const mockHeartbeatService = vi.hoisted(() => ({
|
||||
@@ -47,7 +49,7 @@ async function createApp(actor: Record<string, unknown>) {
|
||||
const query = {
|
||||
from: () => query,
|
||||
innerJoin: () => query,
|
||||
where: (predicate: unknown) => { mockReplayWhere(predicate); return query; },
|
||||
where: (predicate: unknown) => { mockReplayWhere(predicate); return mockReplayBlocks(); },
|
||||
limit: mockReplayBlocks,
|
||||
};
|
||||
app.use("/api", issueTreeControlRoutes({ select: () => query } as any));
|
||||
@@ -59,6 +61,7 @@ describe("issue tree control routes", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockReplayBlocks.mockResolvedValue([]);
|
||||
mockExecutionBlocker.mockResolvedValue(null);
|
||||
mockTreeControlService.getHold.mockResolvedValue(null);
|
||||
mockIssueService.getById.mockResolvedValue({
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
@@ -229,7 +232,9 @@ describe("issue tree control routes", () => {
|
||||
mode: "pause",
|
||||
members: [{ issueId: rootId }],
|
||||
});
|
||||
mockReplayBlocks.mockResolvedValue([{ identifier: "TEST-1" }]);
|
||||
mockReplayBlocks.mockResolvedValue([{ id: rootId, identifier: "TEST-1" }]);
|
||||
mockExecutionBlocker.mockResolvedValue({ nextAction: "Resume without waking agents until the previous execution stops.",
|
||||
recoveryActionId: null, cause: "execution_owner_active", runId: "previous-run", agentId: "agent-1" });
|
||||
const app = await createApp({
|
||||
type: "board",
|
||||
userId: "user-1",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
companies,
|
||||
createDb,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { createPostgresRunDispatchAdapter } from "./postgres.js";
|
||||
import { settleUnrecoverableExecutions } from "../../../services/execution-recovery-resolution.js";
|
||||
import { getExecutionBlocker } from "../../../services/execution-blocker.js";
|
||||
|
||||
// Proves the DB-to-facts mapping this adapter owns for each state the two
|
||||
@@ -49,6 +51,7 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
|
||||
}, 20_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(activityLog);
|
||||
await db.delete(issueDocuments);
|
||||
await db.delete(documentRevisions);
|
||||
await db.delete(documents);
|
||||
@@ -770,6 +773,59 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
|
||||
await expect(adapter.cancelStaleQueuedRun({ companyId, runId, expectedStatus: "queued", now: new Date() })).resolves.toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
|
||||
});
|
||||
|
||||
it.each(["active", "resolved"])("allows a new message through a historical %s interruption hold", async status => {
|
||||
const { companyId, agentId } = await seedCompanyAndAgent();
|
||||
await db.update(agents).set({ adapterType: "process" }).where(eq(agents.id, agentId));
|
||||
const issueId = randomUUID(), previousRunId = randomUUID(), runId = randomUUID();
|
||||
await seedIssue({ companyId, issueId, status: "blocked", assigneeAgentId: agentId });
|
||||
await db.insert(heartbeatRuns).values([
|
||||
{ id: previousRunId, companyId, agentId, status: "interrupted", errorCode: "server_shutdown_interrupted", contextSnapshot: { issueId } },
|
||||
{ id: runId, companyId, agentId, status: "queued", contextSnapshot: { issueId, wakeReason: "issue_commented" } },
|
||||
]);
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId: previousRunId,
|
||||
seq: 1, eventType: "adapter.invoke", payload: { adapterType: "codex_local" } });
|
||||
const [action] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId,
|
||||
kind: "active_run_watchdog", ownerType: "board", cause: "legacy_execution_requires_reconciliation", status,
|
||||
evidence: { runId: previousRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } },
|
||||
fingerprint: previousRunId, nextAction: "Automatic recovery stopped.",
|
||||
}).returning();
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull();
|
||||
const adapter = createPostgresRunDispatchAdapter(db);
|
||||
expect(await adapter.cancelStaleQueuedRun({ companyId, runId, expectedStatus: "queued", now: new Date() })).toMatchObject({ outcome: "not_stale" });
|
||||
await settleUnrecoverableExecutions(db);
|
||||
const [resolved] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action!.id));
|
||||
expect(resolved).toMatchObject({ status: "resolved", outcome: "cancelled", evidence: { runId: previousRunId } });
|
||||
expect(resolved.evidence.automaticRecovery).toMatchObject({ replay: "conversation_continuation", actionOutcome: "unknown" });
|
||||
await settleUnrecoverableExecutions(db);
|
||||
const audit = await db.select().from(activityLog).where(eq(activityLog.entityId, issueId));
|
||||
expect(audit).toHaveLength(1);
|
||||
expect(audit[0]).toMatchObject({ companyId, action: "issue.execution_recovery_settled" });
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, previousRunId))).toHaveLength(0);
|
||||
// The upgrade does not silently resume historical blocked work.
|
||||
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("blocked");
|
||||
});
|
||||
|
||||
it.each(["process", "http", null])("keeps a historical %s hold after switching to a conversation adapter", async historicalAdapter => {
|
||||
const { companyId, agentId } = await seedCompanyAndAgent();
|
||||
await db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, agentId));
|
||||
const issueId = randomUUID(), previousRunId = randomUUID();
|
||||
await seedIssue({ companyId, issueId, status: "blocked", assigneeAgentId: agentId });
|
||||
await db.insert(heartbeatRuns).values({ id: previousRunId, companyId, agentId,
|
||||
status: "interrupted", errorCode: "server_shutdown_interrupted", contextSnapshot: { issueId } });
|
||||
if (historicalAdapter) await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId: previousRunId,
|
||||
seq: 1, eventType: "adapter.invoke", payload: { adapterType: historicalAdapter } });
|
||||
const [action] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId,
|
||||
kind: "active_run_watchdog", ownerType: "board", cause: "legacy_execution_requires_reconciliation", status: "active",
|
||||
evidence: { runId: previousRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } },
|
||||
fingerprint: previousRunId, nextAction: "Inspect previous execution.",
|
||||
}).returning();
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ recoveryActionId: action!.id });
|
||||
await settleUnrecoverableExecutions(db);
|
||||
expect(await getExecutionBlocker(db, companyId, issueId)).toMatchObject({ recoveryActionId: action!.id });
|
||||
const [retained] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action!.id));
|
||||
expect(retained.evidence.automaticRecovery).toMatchObject({ replay: "blocked", actionOutcome: "unknown" });
|
||||
});
|
||||
|
||||
it("links the stopped run's agent instead of its return owner, within the same company", async () => {
|
||||
const { companyId, agentId: ownerId } = await seedCompanyAndAgent();
|
||||
const reviewerId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { hasConversationContinuationPolicy } from "../../../services/conversation-continuation.js";
|
||||
import { getExecutionBlocker } from "../../../services/execution-blocker.js";
|
||||
import { and, asc, eq, gte, inArray, lte, or, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agentWakeupRequests,
|
||||
agents,
|
||||
approvals,
|
||||
issueApprovals,
|
||||
issueThreadInteractions,
|
||||
heartbeatRuns,
|
||||
issueRecoveryActions,
|
||||
issues,
|
||||
@@ -61,6 +65,7 @@ import { RunDispatchApplicationError } from "../application/types.js";
|
||||
|
||||
type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
|
||||
type LoadGateFactsInput = {
|
||||
conversationContinuation: boolean;
|
||||
runId: string;
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
@@ -338,6 +343,21 @@ export function createPostgresRunDispatchAdapter(
|
||||
facts.issueAssigneeAgentId = issue.assigneeAgentId;
|
||||
facts.issueExecutionRunId = issue.executionRunId;
|
||||
facts.issueCheckoutRunId = issue.checkoutRunId;
|
||||
if (input.conversationContinuation) {
|
||||
const [interactions, linkedApprovals] = await Promise.all([
|
||||
dbOrTx.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, input.companyId),
|
||||
eq(issueThreadInteractions.issueId, issueId), eq(issueThreadInteractions.status, "pending"),
|
||||
)).limit(1),
|
||||
dbOrTx.select({ id: approvals.id }).from(issueApprovals).innerJoin(approvals, and(
|
||||
eq(approvals.id, issueApprovals.approvalId), eq(approvals.companyId, issueApprovals.companyId),
|
||||
)).where(and(
|
||||
eq(issueApprovals.companyId, input.companyId), eq(issueApprovals.issueId, issueId),
|
||||
inArray(approvals.status, ["pending", "revision_requested"]),
|
||||
)).limit(1),
|
||||
]);
|
||||
facts.pendingResponse = interactions.length > 0 ? "interaction" : linkedApprovals.length > 0 ? "approval" : null;
|
||||
}
|
||||
facts.reviewParticipant = buildReviewParticipantFacts({
|
||||
isInReview: issue.status === "in_review",
|
||||
executionState: parseIssueExecutionState(issue.executionState),
|
||||
@@ -402,6 +422,7 @@ export function createPostgresRunDispatchAdapter(
|
||||
runId: run.id,
|
||||
companyId: run.companyId,
|
||||
agentId: run.agentId,
|
||||
conversationContinuation: run.runtimeMode === "legacy" && hasConversationContinuationPolicy(run.resultJson),
|
||||
contextSnapshot: parseObject(run.contextSnapshot),
|
||||
scheduledRetryReason: run.scheduledRetryReason,
|
||||
retryReasonOverride: input.retryReasonOverride,
|
||||
@@ -685,6 +706,7 @@ export function createPostgresRunDispatchAdapter(
|
||||
runId: run.id,
|
||||
companyId: run.companyId,
|
||||
agentId: run.agentId,
|
||||
conversationContinuation: run.runtimeMode === "legacy" && hasConversationContinuationPolicy(run.resultJson),
|
||||
contextSnapshot: parseObject(run.contextSnapshot),
|
||||
scheduledRetryReason: run.scheduledRetryReason,
|
||||
retryReasonOverride: run.scheduledRetryReason,
|
||||
@@ -723,6 +745,7 @@ export function createPostgresRunDispatchAdapter(
|
||||
// issue suppresses a max-turn continuation, but every other retry
|
||||
// reason proceeds to promotion anyway.
|
||||
const isLegacyMissingIssueException =
|
||||
!hasConversationContinuationPolicy(run.resultJson) &&
|
||||
!gate.allowed &&
|
||||
gate.errorCode === "issue_not_found" &&
|
||||
factsResult.facts.retryReasonKind !== "max_turn_continuation" &&
|
||||
|
||||
@@ -60,7 +60,8 @@ export type ScheduledRetryGateErrorCode =
|
||||
| "issue_review_participant_changed"
|
||||
| "issue_paused"
|
||||
| "issue_dependencies_blocked"
|
||||
| "issue_disposition_repair_superseded";
|
||||
| "issue_disposition_repair_superseded"
|
||||
| "issue_waiting_for_response";
|
||||
|
||||
export type GateDecision =
|
||||
| { allowed: true }
|
||||
@@ -100,6 +101,8 @@ export type ScheduledRetryFacts = {
|
||||
|
||||
/** Present only when retryReasonKind is "disposition_repair". */
|
||||
dispositionRepair: DispositionRepairFacts | null;
|
||||
/** A conversation retry must wait for unresolved questions and approvals. */
|
||||
pendingResponse?: "interaction" | "approval" | null;
|
||||
};
|
||||
|
||||
export type QueuedRunStalenessErrorCode =
|
||||
@@ -456,6 +459,16 @@ export function decideScheduledRetryGate(
|
||||
};
|
||||
}
|
||||
|
||||
if (facts.pendingResponse) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: "Conversation retry is waiting for a response to a pending question or approval",
|
||||
errorCode: "issue_waiting_for_response",
|
||||
issueId: facts.issueId,
|
||||
details: { waitingFor: facts.pendingResponse },
|
||||
};
|
||||
}
|
||||
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
createWakeAdmissionWriter,
|
||||
} from "./postgres.js";
|
||||
import type { WakeQueuePostgresAdapterDeps } from "./postgres.js";
|
||||
import { createReleaseIssueExecution } from "../application/use-cases.js";
|
||||
import type { TransactionScope } from "../application/ports.js";
|
||||
|
||||
// Proves the atomicity and company-scope properties the security review
|
||||
@@ -163,6 +164,38 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
return id;
|
||||
}
|
||||
|
||||
for (const hasDeferredMessage of [false, true]) {
|
||||
it(`plans conversation recovery during owner cleanup without draining messages (queued=${hasDeferredMessage})`, async () => {
|
||||
const companyId = await seedCompany();
|
||||
const agentId = await seedAgent({ companyId });
|
||||
const issueId = await seedIssue({ companyId, assigneeAgentId: agentId });
|
||||
const runId = await seedRun({ companyId, agentId, status: "failed", contextSnapshot: { issueId } });
|
||||
await db.update(heartbeatRuns).set({
|
||||
processPid: process.pid,
|
||||
resultJson: { conversationContinuation: "continue_conversation_v1" },
|
||||
}).where(eq(heartbeatRuns.id, runId));
|
||||
const wakeId = hasDeferredMessage ? await seedDeferredWake({ companyId, agentId, issueId }) : null;
|
||||
const release = createReleaseIssueExecution({
|
||||
issueLock: createPostgresWakeQueueAdapter(db, stubDeps),
|
||||
recovery: {
|
||||
escalateStrandedAssignedIssue: async () => { throw new Error("unexpected escalation"); },
|
||||
escalateStrandedRecoveryIssueInPlace: async () => { throw new Error("unexpected escalation"); },
|
||||
},
|
||||
});
|
||||
const result = await release({ companyId, runId, now: new Date() });
|
||||
expect(result.outcome.kind).toBe("released");
|
||||
expect(result.postCommitEffects.every((effect) => effect.kind === "conversation_retry_requested")).toBe(true);
|
||||
if (!wakeId) expect(result.postCommitEffects).toEqual([
|
||||
{ kind: "conversation_retry_requested", companyId, runId, reviewParticipant: false },
|
||||
]);
|
||||
if (wakeId) {
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId));
|
||||
expect(wake.status).toBe("deferred_issue_execution");
|
||||
}
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId))).toHaveLength(1);
|
||||
});
|
||||
}
|
||||
|
||||
it("leaves deferred work untouched until the effective execution hold clears", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const agentId = await seedAgent({ companyId });
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
issues,
|
||||
nativeRunFinalizations,
|
||||
} from "@paperclipai/db";
|
||||
import { hasConversationContinuationPolicy } from "../../../services/conversation-continuation.js";
|
||||
import { legacyExecutionNeedsReconciliation } from "../../../services/legacy-execution-recovery.js";
|
||||
import {
|
||||
authorizeFailedChatRunRetryWake,
|
||||
@@ -85,6 +86,7 @@ function toRunSnapshot(row: HeartbeatRunRow): RunSnapshot {
|
||||
agentId: row.agentId,
|
||||
status: row.status,
|
||||
runtimeMode: row.runtimeMode,
|
||||
conversationContinuation: row.runtimeMode === "legacy" && hasConversationContinuationPolicy(row.resultJson),
|
||||
errorCode: row.errorCode,
|
||||
responsibleUserId: row.responsibleUserId,
|
||||
contextSnapshot: parseObject(row.contextSnapshot),
|
||||
@@ -1061,12 +1063,18 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd
|
||||
return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot };
|
||||
}
|
||||
|
||||
// A release must leave deferred messages intact while replay is held.
|
||||
if (await getExecutionBlocker(tx, issueRow.companyId, issueRow.id)) {
|
||||
// A release must leave deferred messages intact while execution is held.
|
||||
// The finishing conversation may still own its lease until finally cleanup.
|
||||
// Allow only bounded retry planning in that case; admission stays gated.
|
||||
const executionBlocker = await getExecutionBlocker(tx, issueRow.companyId, issueRow.id);
|
||||
const recoveryOnly = Boolean(executionBlocker &&
|
||||
executionBlocker.cause === "execution_owner_active" && executionBlocker.runId === run.id &&
|
||||
runSnapshot.conversationContinuation && ["failed", "timed_out", "interrupted"].includes(run.status));
|
||||
if (executionBlocker && !recoveryOnly) {
|
||||
return { outcome: { kind: "released" }, postCommitEffects: [], run: runSnapshot };
|
||||
}
|
||||
|
||||
const locked: LockedIssueExecution = { primaryIssue: toIssueSnapshot(issueRow), run: runSnapshot };
|
||||
const locked: LockedIssueExecution = { primaryIssue: toIssueSnapshot(issueRow), run: runSnapshot, recoveryOnly };
|
||||
const result = await fn(locked, { host: buildHost(tx, deps), transaction: buildTransaction(tx, deps, db, run) });
|
||||
return { ...result, run: runSnapshot };
|
||||
});
|
||||
|
||||
@@ -12,6 +12,8 @@ export type { InvokableAgentSnapshot, IssueSnapshot, ReleaseRecoveryBlockedNotic
|
||||
|
||||
/** The primary issue a locked release resolves to, plus the finishing run the lock step already loaded. */
|
||||
export type LockedIssueExecution = {
|
||||
/** Plan bounded recovery without draining messages while the finishing owner cleans up. */
|
||||
recoveryOnly?: boolean;
|
||||
primaryIssue: IssueSnapshot;
|
||||
run: RunSnapshot;
|
||||
};
|
||||
|
||||
@@ -21,6 +21,8 @@ export type RunSnapshot = {
|
||||
contextSnapshot: Record<string, unknown>;
|
||||
/** `resultJson.configurationIncomplete`, already parsed; non-null only on a configuration-incomplete failed run. */
|
||||
configurationIncompletePayload: Record<string, unknown> | null;
|
||||
/** The host schedules failed conversation turns with its durable retry budget. */
|
||||
conversationContinuation?: boolean;
|
||||
};
|
||||
|
||||
export type IssueSnapshot = {
|
||||
@@ -67,7 +69,12 @@ export type IssueReopenedEffect = {
|
||||
};
|
||||
|
||||
/** Explicit post-commit work a caller applies only after the release transaction commits. */
|
||||
export type PostCommitEffect = RunQueuedEffect | IssueReopenedEffect;
|
||||
export type PostCommitEffect = RunQueuedEffect | IssueReopenedEffect | {
|
||||
kind: "conversation_retry_requested";
|
||||
companyId: string;
|
||||
runId: string;
|
||||
reviewParticipant: boolean;
|
||||
};
|
||||
|
||||
export type ReleaseOutcome =
|
||||
| { kind: "released" }
|
||||
|
||||
@@ -139,6 +139,10 @@ async function runReleaseDrain(
|
||||
const issue = locked.primaryIssue;
|
||||
const postCommitEffects: PostCommitEffect[] = [];
|
||||
|
||||
if (locked.recoveryOnly) {
|
||||
return runReleaseRecoveryTail(issue, run, ports.host, ports.transaction, input, postCommitEffects);
|
||||
}
|
||||
|
||||
// Each `continue` path below leaves the wake row off the
|
||||
// `deferred_issue_execution` status, so the next queue read cannot
|
||||
// return that same row again. That invariant is what ends this loop.
|
||||
@@ -554,6 +558,19 @@ async function runReleaseRecoveryTail(
|
||||
"wake-queue: queued a recovery run with no invokable recovery agent",
|
||||
);
|
||||
|
||||
if (run.conversationContinuation && ["failed", "timed_out", "interrupted"].includes(run.status)) {
|
||||
// Do not create an uncounted immediate successor inside the issue lock.
|
||||
// The host's idempotent scheduler claims it after commit with the same
|
||||
// retry counter used by restart and process-loss recovery.
|
||||
postCommitEffects.push({
|
||||
kind: "conversation_retry_requested",
|
||||
companyId: run.companyId,
|
||||
runId: run.id,
|
||||
reviewParticipant: decision.kind === "queue_review_participant_recovery",
|
||||
});
|
||||
return { outcome: { kind: "released" }, postCommitEffects };
|
||||
}
|
||||
|
||||
const sessionBefore = await host.resolveSessionBeforeForWakeup({
|
||||
companyId: issue.companyId,
|
||||
agentId: recoveryAgent.id,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { Router } from "express";
|
||||
import type { Request } from "express";
|
||||
import {
|
||||
issueRecoveryActions,
|
||||
issues as issueRows,
|
||||
type Db,
|
||||
} from "@paperclipai/db";
|
||||
import { and, eq, inArray, isNotNull } from "drizzle-orm";
|
||||
import { executionBlockerPredicate } from "../services/execution-blocker.js";
|
||||
import { getExecutionBlocker } from "../services/execution-blocker.js";
|
||||
import { conflict } from "../errors.js";
|
||||
import {
|
||||
createIssueTreeHoldSchema,
|
||||
@@ -387,30 +386,15 @@ export function issueTreeControlRoutes(db: Db) {
|
||||
.map((member) => member.issueId)
|
||||
: [];
|
||||
if (issueIds.length > 0) {
|
||||
const [blocked] = await db
|
||||
.select({ identifier: issueRows.identifier })
|
||||
.from(issueRecoveryActions)
|
||||
.innerJoin(
|
||||
issueRows,
|
||||
and(
|
||||
eq(issueRows.id, issueRecoveryActions.sourceIssueId),
|
||||
eq(issueRows.companyId, root.companyId),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(issueRecoveryActions.companyId, root.companyId),
|
||||
inArray(issueRecoveryActions.sourceIssueId, issueIds),
|
||||
inArray(issueRows.status, RESUME_EXECUTABLE_STATUSES),
|
||||
isNotNull(issueRows.assigneeAgentId),
|
||||
executionBlockerPredicate(),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (blocked)
|
||||
throw conflict(
|
||||
`Cannot wake ${blocked.identifier ?? "this task"} until its stopped execution is reconciled. Resume without waking agents, or review the stopped run first.`,
|
||||
);
|
||||
const candidates = await db.select({ id: issueRows.id, identifier: issueRows.identifier })
|
||||
.from(issueRows).where(and(
|
||||
eq(issueRows.companyId, root.companyId), inArray(issueRows.id, issueIds),
|
||||
inArray(issueRows.status, RESUME_EXECUTABLE_STATUSES), isNotNull(issueRows.assigneeAgentId),
|
||||
));
|
||||
for (const task of candidates) {
|
||||
const blocked = await getExecutionBlocker(db, root.companyId, task.id);
|
||||
if (blocked) throw conflict(`Cannot wake ${task.identifier ?? "this task"}: ${blocked.nextAction}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { and, desc, eq, inArray, isNotNull, or, sql } from "drizzle-orm";
|
||||
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db";
|
||||
import { readProcessStartedAt } from "./hot-restart.js";
|
||||
|
||||
// These adapters accept a conversation turn. Retrying a process or webhook can
|
||||
// replay the action itself, so those adapters retain their recovery contract.
|
||||
export const CONVERSATION_ADAPTER_TYPES = [
|
||||
"claude_local", "codex_local", "cursor", "gemini_local", "opencode_local",
|
||||
"pi_local", "grok_local", "kimi_local", "hermes_local",
|
||||
] as const;
|
||||
|
||||
export function isConversationAdapter(adapterType: string): boolean {
|
||||
return (CONVERSATION_ADAPTER_TYPES as readonly string[]).includes(adapterType);
|
||||
}
|
||||
|
||||
export const CONVERSATION_CONTINUATION_POLICY = "continue_conversation_v1";
|
||||
|
||||
export function hasConversationContinuationPolicy(result: Record<string, unknown> | null | undefined): boolean {
|
||||
return result?.conversationContinuation === CONVERSATION_CONTINUATION_POLICY;
|
||||
}
|
||||
|
||||
function conversationRunPredicate() {
|
||||
return or(
|
||||
sql`${heartbeatRuns.resultJson}->>'conversationContinuation' = ${CONVERSATION_CONTINUATION_POLICY}`,
|
||||
sql`exists (
|
||||
select 1 from ${heartbeatRunEvents}
|
||||
where ${heartbeatRunEvents.companyId} = ${heartbeatRuns.companyId}
|
||||
and ${heartbeatRunEvents.runId} = ${heartbeatRuns.id}
|
||||
and ${heartbeatRunEvents.eventType} = 'adapter.invoke'
|
||||
and ${inArray(sql`${heartbeatRunEvents.payload}->>'adapterType'`, [...CONVERSATION_ADAPTER_TYPES])}
|
||||
)`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Recovery must not infer the old adapter from the agent's mutable settings. */
|
||||
export async function runUsedConversationAdapter(db: Db, run: typeof heartbeatRuns.$inferSelect): Promise<boolean> {
|
||||
if (hasConversationContinuationPolicy(run.resultJson)) return true;
|
||||
const [invocation] = await db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents)
|
||||
.where(and(eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
|
||||
eq(heartbeatRunEvents.eventType, "adapter.invoke")))
|
||||
.orderBy(desc(heartbeatRunEvents.seq)).limit(1);
|
||||
const adapterType = invocation?.payload?.adapterType;
|
||||
return typeof adapterType === "string" && isConversationAdapter(adapterType);
|
||||
}
|
||||
|
||||
/** Only immutable run evidence can retire a historical conversation hold.
|
||||
* An agent's current adapter can differ from the one that executed this run.
|
||||
* Missing evidence retains the hold; the current agent is never a fallback.
|
||||
*/
|
||||
export function conversationRecoveryActionPredicate() {
|
||||
return and(
|
||||
eq(issueRecoveryActions.cause, "legacy_execution_requires_reconciliation"),
|
||||
sql`exists (
|
||||
select 1 from ${heartbeatRuns}
|
||||
where ${heartbeatRuns.companyId} = ${issueRecoveryActions.companyId}
|
||||
and ${heartbeatRuns.id}::text = ${issueRecoveryActions.evidence}->>'runId'
|
||||
and coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueRecoveryActions.sourceIssueId}::text
|
||||
and ${heartbeatRuns.runtimeMode} = 'legacy'
|
||||
and ${inArray(heartbeatRuns.status, ['failed', 'timed_out', 'interrupted', 'cancelled'])}
|
||||
and ${conversationRunPredicate()}
|
||||
and ${or(
|
||||
sql`${heartbeatRuns.resultJson}->>'conversationContinuation' = ${CONVERSATION_CONTINUATION_POLICY}`,
|
||||
eq(heartbeatRuns.status, "interrupted"),
|
||||
inArray(heartbeatRuns.errorCode, ["process_lost", "server_shutdown_interrupted", "execution_reconciliation_required"]),
|
||||
and(eq(heartbeatRuns.status, "cancelled"), sql`${heartbeatRuns.resultJson}->'executionCancellation'->>'state' = 'acknowledged'`),
|
||||
)}
|
||||
)`,
|
||||
);
|
||||
}
|
||||
|
||||
/** OS liveness probes do not signal or stop the process. Unknown ownership holds. */
|
||||
function processMayBeAlive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code !== "ESRCH";
|
||||
}
|
||||
}
|
||||
|
||||
/** A terminal conversation row does not prove that its execution authority ended.
|
||||
* Other adapters keep their existing bootstrap and ownership protocols.
|
||||
*/
|
||||
export async function getConversationOwnershipBlocker(db: Db, companyId: string, issueId: string) {
|
||||
const activeLease = sql`exists (select 1 from ${environmentLeases}
|
||||
where ${environmentLeases.companyId} = "heartbeat_runs"."company_id"
|
||||
and ${environmentLeases.heartbeatRunId} = "heartbeat_runs"."id"
|
||||
and ${environmentLeases.releasedAt} is null)`;
|
||||
const candidates = await db.select({ run: heartbeatRuns, activeLease }).from(heartbeatRuns)
|
||||
.where(and(
|
||||
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.runtimeMode, "legacy"),
|
||||
conversationRunPredicate(),
|
||||
sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`,
|
||||
inArray(heartbeatRuns.status, ["failed", "timed_out", "interrupted", "cancelled"]),
|
||||
or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId), activeLease),
|
||||
)).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id));
|
||||
for (const { run, activeLease: leaseHeld } of candidates) {
|
||||
let pidAlive = run.processPid !== null && processMayBeAlive(run.processPid);
|
||||
if (pidAlive && run.processStartedAt) {
|
||||
// A recycled PID cannot keep an old task blocked. An unreadable identity
|
||||
// stays conservative; the original process may still own execution.
|
||||
const observed = await readProcessStartedAt(run.processPid!).catch(() => null);
|
||||
if (observed && new Date(observed).getTime() !== run.processStartedAt.getTime()) pidAlive = false;
|
||||
}
|
||||
const groupAlive = run.processGroupId !== null && processMayBeAlive(-run.processGroupId);
|
||||
if (pidAlive || groupAlive || leaseHeld) {
|
||||
return {
|
||||
runId: run.id,
|
||||
agentId: run.agentId,
|
||||
cause: "execution_owner_active",
|
||||
nextAction: pidAlive || groupAlive
|
||||
? "The previous provider process is still running. Stop it before continuing this task."
|
||||
: "The previous execution has not released its environment lease. Wait for cleanup before continuing this task.",
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { and, desc, eq, inArray, or, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, inArray, not, or, sql } from "drizzle-orm";
|
||||
import { conversationRecoveryActionPredicate, getConversationOwnershipBlocker } from "./conversation-continuation.js";
|
||||
import { z } from "zod";
|
||||
import { heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db";
|
||||
import { EXECUTION_RECONCILIATION_CAUSES, type ExecutionBlocker } from "@paperclipai/shared";
|
||||
@@ -6,6 +7,7 @@ import { EXECUTION_RECONCILIATION_CAUSES, type ExecutionBlocker } from "@papercl
|
||||
/** Resolved recovery bookkeeping can still carry an effective no-replay hold. */
|
||||
export function executionBlockerPredicate() {
|
||||
return and(
|
||||
not(conversationRecoveryActionPredicate()!),
|
||||
inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]),
|
||||
or(inArray(issueRecoveryActions.status, ["active", "escalated"]),
|
||||
sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`),
|
||||
@@ -13,6 +15,8 @@ export function executionBlockerPredicate() {
|
||||
}
|
||||
|
||||
export async function getExecutionBlocker(db: Db, companyId: string, issueId: string): Promise<ExecutionBlocker | null> {
|
||||
const ownership = await getConversationOwnershipBlocker(db, companyId, issueId);
|
||||
if (ownership) return { ...ownership, recoveryActionId: null };
|
||||
const [action] = await db.select().from(issueRecoveryActions).where(and(
|
||||
eq(issueRecoveryActions.companyId, companyId),
|
||||
eq(issueRecoveryActions.sourceIssueId, issueId),
|
||||
|
||||
@@ -133,6 +133,41 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
summary: "Notion read completed.",
|
||||
exposeLowTrustRaw: false,
|
||||
});
|
||||
it("cancelled admission must not hide the interrupted execution", async () => {
|
||||
const rejectedId = randomUUID();
|
||||
await db.update(heartbeatRuns).set({ status: "interrupted", errorCode: "server_shutdown_interrupted", createdAt: new Date("2026-09-08T10:00:00Z") }).where(eq(heartbeatRuns.id, runId));
|
||||
await db.insert(heartbeatRuns).values({ id: rejectedId, companyId, agentId,
|
||||
status: "cancelled", errorCode: "execution_reconciliation_required",
|
||||
contextSnapshot: { issueId }, createdAt: new Date("2026-09-08T11:00:00Z") });
|
||||
try {
|
||||
const envelope = await build();
|
||||
expect(envelope.interruptedRunId).toBe(runId);
|
||||
} finally {
|
||||
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, rejectedId));
|
||||
await db.update(heartbeatRuns).set({ status: "failed", errorCode: null }).where(eq(heartbeatRuns.id, runId));
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves the latest user request and adds an interruption notice to fresh and resumed turns", async () => {
|
||||
await db.update(heartbeatRuns).set({ status: "interrupted", errorCode: "server_shutdown_interrupted" }).where(eq(heartbeatRuns.id, runId));
|
||||
try {
|
||||
const envelope = await buildExecutionContinuation({ db, companyId, issueId, agentId,
|
||||
context: { retryOfRunId: runId, wakeReason: "retry_failed_run" },
|
||||
summary: "Deployment completed. Verification remains.", exposeLowTrustRaw: false });
|
||||
expect(envelope.interruptedRunId).toBe(runId);
|
||||
expect(envelope.objective).toBe("Focus the Gmail summary on launch decisions.");
|
||||
expect(envelope.messages.map(message => message.id)).toContain(gmailId);
|
||||
for (const resumedSession of [true, false]) {
|
||||
const prompt = renderPaperclipWakePrompt({ executionContinuation: envelope }, { resumedSession });
|
||||
expect(prompt).toContain("Your previous run was interrupted. Continue from where you left off");
|
||||
expect(prompt).toContain("Prior tool calls are history, not commands to replay");
|
||||
expect(prompt).toContain("Deployment completed. Verification remains.");
|
||||
}
|
||||
} finally {
|
||||
await db.update(heartbeatRuns).set({ status: "failed", errorCode: null }).where(eq(heartbeatRuns.id, runId));
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps Local CLI run-authored comments as history without promoting them to human direction", async () => {
|
||||
const id = randomUUID();
|
||||
await db.insert(issueComments).values({ id, companyId, issueId, authorType: "user",
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "@paperclipai/db";
|
||||
import type { ExecutionContinuationEnvelope } from "@paperclipai/shared";
|
||||
import { sanitizeQuarantinedCommentForHigherTrust } from "./source-trust.js";
|
||||
import { hasConversationContinuationPolicy } from "./conversation-continuation.js";
|
||||
|
||||
const object = (v: unknown): Record<string, unknown> =>
|
||||
v && typeof v === "object" && !Array.isArray(v)
|
||||
@@ -208,7 +209,7 @@ export async function buildExecutionContinuation(input: {
|
||||
row.authorType === "user" && !row.createdByRunId && !row.deleted && row.body.trim().length > 0,
|
||||
);
|
||||
const priorRuns = await db
|
||||
.select({ id: heartbeatRuns.id, result: heartbeatRuns.resultJson })
|
||||
.select({ id: heartbeatRuns.id, result: heartbeatRuns.resultJson, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
|
||||
.from(heartbeatRuns)
|
||||
.where(
|
||||
and(
|
||||
@@ -249,7 +250,16 @@ export async function buildExecutionContinuation(input: {
|
||||
eq(issueRecoveryActions.status, "resolved"),
|
||||
),
|
||||
);
|
||||
const lastTerminal = priorRuns.findLast((run) =>
|
||||
["succeeded", "failed", "timed_out", "interrupted", "cancelled"].includes(run.status) &&
|
||||
!(run.status === "cancelled" && run.errorCode === "execution_reconciliation_required"),
|
||||
);
|
||||
const interruptedRunId = lastTerminal && lastTerminal.status !== "succeeded" &&
|
||||
(hasConversationContinuationPolicy(lastTerminal.result) ||
|
||||
lastTerminal.status === "interrupted" || lastTerminal.errorCode === "process_lost")
|
||||
? lastTerminal.id : undefined;
|
||||
return {
|
||||
...(interruptedRunId ? { interruptedRunId } : {}),
|
||||
...(resumeDelta ? { resumeDelta } : {}),
|
||||
recoveryOutcomes: reconciliations
|
||||
.filter((row) => row.evidence.executionReconciliation)
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { conversationRecoveryActionPredicate, getConversationOwnershipBlocker } from "./conversation-continuation.js";
|
||||
import { persistActivity } from "./activity-log.js";
|
||||
import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, isNull, not, or, sql } from "drizzle-orm";
|
||||
import {
|
||||
chatActions,
|
||||
environmentLeases,
|
||||
@@ -305,8 +306,47 @@ export async function settleUnrecoverableExecutions(
|
||||
now = new Date(),
|
||||
options: { failpoint?: (phase: "persisted") => void } = {},
|
||||
) {
|
||||
// Fold obsolete conversation holds without waking historical work on upgrade.
|
||||
// Keep their evidence and record the policy change in the task's activity log.
|
||||
const obsoleteConversationHold = and(
|
||||
conversationRecoveryActionPredicate(),
|
||||
or(
|
||||
inArray(issueRecoveryActions.status, ["active", "escalated"]),
|
||||
sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`,
|
||||
),
|
||||
);
|
||||
await db.transaction(async tx => {
|
||||
const foldable = await tx.select().from(issueRecoveryActions).where(obsoleteConversationHold)
|
||||
.limit(25).for("update", { skipLocked: true });
|
||||
for (const candidate of foldable) {
|
||||
if (await getConversationOwnershipBlocker(tx as unknown as Db, candidate.companyId, candidate.sourceIssueId)) continue;
|
||||
const [action] = await tx.update(issueRecoveryActions).set({
|
||||
status: "resolved",
|
||||
outcome: "cancelled",
|
||||
resolvedAt: now,
|
||||
updatedAt: now,
|
||||
nextAction: "Automatic attempts stopped. Send a new message to continue the conversation.",
|
||||
resolutionNote: "Conversation continuation does not replay prior tool calls.",
|
||||
wakePolicy: null,
|
||||
monitorPolicy: null,
|
||||
evidence: sql`case when ${issueRecoveryActions.evidence} ? 'automaticRecovery'
|
||||
then jsonb_set(${issueRecoveryActions.evidence}, '{automaticRecovery,replay}', '"conversation_continuation"'::jsonb)
|
||||
else ${issueRecoveryActions.evidence} end`,
|
||||
}).where(and(obsoleteConversationHold, eq(issueRecoveryActions.id, candidate.id))).returning();
|
||||
if (!action) continue;
|
||||
await persistActivity(tx as unknown as Db, {
|
||||
companyId: action.companyId,
|
||||
actorType: "system",
|
||||
actorId: "execution-recovery",
|
||||
action: "issue.execution_recovery_settled",
|
||||
entityType: "issue",
|
||||
entityId: action.sourceIssueId,
|
||||
details: { recoveryActionId: action.id, outcome: "cancelled", continuation: "conversation" },
|
||||
});
|
||||
}
|
||||
});
|
||||
// Filter eligibility before applying the batch limit. A queue of sessions
|
||||
// still awaiting safe replacement must not starve settled incidents behind it.
|
||||
// awaiting replacement must not starve settled incidents behind it.
|
||||
const candidates = await db
|
||||
.select({ action: issueRecoveryActions })
|
||||
.from(issueRecoveryActions)
|
||||
@@ -327,6 +367,7 @@ export async function settleUnrecoverableExecutions(
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
not(conversationRecoveryActionPredicate()!),
|
||||
inArray(issueRecoveryActions.status, ["active", "escalated"]),
|
||||
eq(issueRecoveryActions.kind, "active_run_watchdog"),
|
||||
inArray(issueRecoveryActions.cause, [
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getExecutionBlocker } from "./execution-blocker.js";
|
||||
import { CONVERSATION_CONTINUATION_POLICY, runUsedConversationAdapter, hasConversationContinuationPolicy, isConversationAdapter } from "./conversation-continuation.js";
|
||||
import { recordExecutionWait } from "./execution-wait.js";
|
||||
import {
|
||||
legacyExecutionNeedsReconciliation,
|
||||
@@ -9420,7 +9421,18 @@ export function heartbeatService(
|
||||
// issue's activity entry.
|
||||
async function applyWakeQueuePostCommitEffects(effects: WakeQueuePostCommitEffect[]) {
|
||||
for (const effect of effects) {
|
||||
if (effect.kind === "run_queued") {
|
||||
if (effect.kind === "conversation_retry_requested") {
|
||||
const [source] = await db.select().from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, effect.companyId), eq(heartbeatRuns.id, effect.runId),
|
||||
));
|
||||
const agent = source ? await getAgent(source.agentId) : null;
|
||||
if (source && agent && agent.companyId === source.companyId) {
|
||||
await scheduleBoundedRetryForRun(source, agent, effect.reviewParticipant ? {
|
||||
retryReason: EXECUTION_REVIEW_PARTICIPANT_RECOVERY_RETRY_REASON,
|
||||
wakeReason: EXECUTION_REVIEW_PARTICIPANT_RECOVERY_WAKE_REASON,
|
||||
} : undefined);
|
||||
}
|
||||
} else if (effect.kind === "run_queued") {
|
||||
publishLiveEvent({
|
||||
companyId: effect.run.companyId,
|
||||
type: "heartbeat.run.queued",
|
||||
@@ -14472,7 +14484,7 @@ export function heartbeatService(
|
||||
restartSuspendedRunIds.push(run.id);
|
||||
continue;
|
||||
}
|
||||
const message = `Interrupted by graceful server shutdown (${signal}); recovery requires verified provider continuity`;
|
||||
const message = `Interrupted by graceful server shutdown (${signal})`;
|
||||
const running = runningProcesses.get(run.id);
|
||||
try {
|
||||
if (run.runtimeMode === "native") {
|
||||
@@ -14510,6 +14522,7 @@ export function heartbeatService(
|
||||
errorCode: "server_shutdown_interrupted",
|
||||
signal,
|
||||
resultJson: mergeRunStopMetadataForAgent(agent, "interrupted", {
|
||||
conversationContinuationEligible: await runUsedConversationAdapter(db, run),
|
||||
resultJson: persistedCancellationResult,
|
||||
errorCode: "server_shutdown_interrupted",
|
||||
errorMessage: message,
|
||||
@@ -14732,6 +14745,7 @@ export function heartbeatService(
|
||||
: baseSchedule;
|
||||
|
||||
const requiresIssueGate =
|
||||
hasConversationContinuationPolicy(run.resultJson) ||
|
||||
retryReason === MAX_TURN_CONTINUATION_RETRY_REASON ||
|
||||
retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON;
|
||||
if (requiresIssueGate) {
|
||||
@@ -15179,6 +15193,8 @@ export function heartbeatService(
|
||||
status: "scheduled_retry",
|
||||
wakeupRequestId: wakeupRequest.id,
|
||||
contextSnapshot: retryContextSnapshot,
|
||||
...(hasConversationContinuationPolicy(run.resultJson)
|
||||
? { resultJson: { conversationContinuation: CONVERSATION_CONTINUATION_POLICY } } : {}),
|
||||
responsibleUserId,
|
||||
sessionIdBefore: sessionBefore,
|
||||
retryOfRunId: run.id,
|
||||
@@ -15302,6 +15318,7 @@ export function heartbeatService(
|
||||
.update(issues)
|
||||
.set({
|
||||
executionRunId: scheduledRun.id,
|
||||
checkoutRunId: sql`case when ${issues.checkoutRunId} = ${run.id} then null else ${issues.checkoutRunId} end`,
|
||||
executionAgentNameKey: normalizeAgentNameKey(agent.name),
|
||||
executionLockedAt: now,
|
||||
...(detachWorkspaceFromIssue
|
||||
@@ -17213,6 +17230,7 @@ export function heartbeatService(
|
||||
outcome: "succeeded" | "interrupted" | "failed" | "cancelled" | "timed_out",
|
||||
options?: {
|
||||
resultJson?: Record<string, unknown> | null;
|
||||
conversationContinuationEligible?: boolean;
|
||||
errorCode?: string | null;
|
||||
errorMessage?: string | null;
|
||||
},
|
||||
@@ -17224,10 +17242,17 @@ export function heartbeatService(
|
||||
errorCode: options?.errorCode ?? null,
|
||||
errorMessage: options?.errorMessage ?? null,
|
||||
});
|
||||
return mergeHeartbeatRunStopMetadata(
|
||||
const result = mergeHeartbeatRunStopMetadata(
|
||||
options?.resultJson ?? null,
|
||||
stopMetadata,
|
||||
);
|
||||
const cancellationAcknowledged =
|
||||
parseObject(result?.executionCancellation).state === "acknowledged";
|
||||
return options?.conversationContinuationEligible !== false && outcome !== "succeeded" &&
|
||||
(outcome !== "cancelled" || cancellationAcknowledged) &&
|
||||
isConversationAdapter(agent.adapterType)
|
||||
? { ...result, conversationContinuation: CONVERSATION_CONTINUATION_POLICY }
|
||||
: result;
|
||||
}
|
||||
|
||||
function countValue(value: unknown) {
|
||||
@@ -18246,6 +18271,7 @@ export function heartbeatService(
|
||||
(!!run.processPid || !!run.processGroupId)) ||
|
||||
monitorDispatchLostWithoutFutureWake);
|
||||
const baseMessage = buildProcessLossMessage(run);
|
||||
const conversationContinuationEligible = await runUsedConversationAdapter(db, run);
|
||||
|
||||
const failureWrite = await setRunStatusFromLive(
|
||||
run.id,
|
||||
@@ -18260,6 +18286,7 @@ export function heartbeatService(
|
||||
{ adapterType, adapterConfig },
|
||||
"failed",
|
||||
{
|
||||
conversationContinuationEligible,
|
||||
resultJson: parseObject(run.resultJson),
|
||||
errorCode: "process_lost",
|
||||
errorMessage: shouldRetry
|
||||
|
||||
@@ -29,3 +29,12 @@ it("retains the hold until the provider actually acknowledges cancellation", ()
|
||||
...stopped.resultJson, executionCancellation: { state: "requested" },
|
||||
} })).toBe(true);
|
||||
});
|
||||
|
||||
it("continues a conversation without requiring receipts, even after automatic attempts are exhausted", () => {
|
||||
for (const status of ["failed", "timed_out", "interrupted", "cancelled"]) {
|
||||
expect(legacyExecutionNeedsReconciliation({
|
||||
runtimeMode: "legacy", status, errorCode: "process_lost", scheduledRetryAttempt: 2,
|
||||
resultJson: { conversationContinuation: "continue_conversation_v1" },
|
||||
})).toBe(false);
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { normalizeMaxTurnStopReason } from "./heartbeat-stop-metadata.js";
|
||||
import { hasConversationContinuationPolicy } from "./conversation-continuation.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { heartbeatRuns, issueRecoveryActions, issues, type Db } from "@paperclipai/db";
|
||||
@@ -18,6 +19,9 @@ export function legacyExecutionNeedsReconciliation(
|
||||
!["failed", "timed_out", "interrupted", "cancelled"].includes(run.status)
|
||||
)
|
||||
return false;
|
||||
// A fresh conversation turn lets the agent decide what remains. The retry
|
||||
// scheduler, not an action-outcome hold, owns the automatic attempt limit.
|
||||
if (hasConversationContinuationPolicy(run.resultJson)) return false;
|
||||
// Productive turn-budget continuation is not a failed provider session.
|
||||
if (normalizeMaxTurnStopReason(run.resultJson?.stopReason) ?? normalizeMaxTurnStopReason(run.errorCode)) return false;
|
||||
const evidence = run.resultJson?.executionRecovery as
|
||||
|
||||
Reference in new issue
Block a user