mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
Merge current master into Photon cleanup handoff
* commit '424e2c6488035994833526bf83193664d05cc21c': fix(recovery): keep live owners' runs through an upgrade and continue replaced preparations in the restart lane (#21046) fix(native): continue a routine assignment or chat message whose remote Runner an upgrade lost mid-turn (#21052) fix(chat): send writes with an empty responseText and point card declines to resolve-from-comment (#21050) fix(retry): continue a connected task from saved work when its exact chat request cannot be repeated (#21038) test(native): cover a turn.start timeout that loses the remote Runner, end to end (#21041) fix(heartbeat): renew legacy controller leases on their own connection, timed from the statement (#21042) fix(evals): grade full cohort 4 chat cases on saved state and rendered links (#21034) fix(chat): route company creation, decline retries and question cancellation correctly (#21035) fix(native): continue a run whose remote Runner died mid-turn after a restart, without replaying the turn (#21039)
This commit is contained in:
commit
10c5a89ebf
71 files changed
+1767
-255
No files matched your search
@@ -987,6 +987,10 @@ describe("conversation execution wake policy", () => {
|
||||
});
|
||||
|
||||
describe("chat prompt policy", () => {
|
||||
it("tells chat to record a person's decline with resolve-from-comment whoever created the card, and keeps withdraw for its own obsolete card", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("A person's explicit decline in chat (for example \"do not publish it\") answers a pending confirmation with reject, whoever created the card");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Withdraw is only for your own card that later evidence made obsolete; it never records the person's decision");
|
||||
});
|
||||
it("tells chat to save a requested start order as a blocker on the waiting task, not only a promise to hold it", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("must not start until another task is done or approved");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("add the prerequisite to the waiting task's blockedByIssueIds with PATCH /api/issues/{id}, keeping its existing blockers");
|
||||
@@ -1001,6 +1005,27 @@ describe("chat prompt policy", () => {
|
||||
expect(prompt).toContain("/<prefix>/agents/<urlKey or id>");
|
||||
});
|
||||
|
||||
// Full chat cohort 4 (onboarding.new-company): the CEO applied the missing-name rule and asked for a business name
|
||||
// instead of sending the person to the board-only company-creation flow.
|
||||
it("keeps the missing-name rule behind the board-only company-creation boundary", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("This name rule is for work you create yourself. It never comes before a board-only boundary");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Otherwise link [Create organization](/onboarding), which opens the new-organization wizard");
|
||||
// Paperclip Cloud creates organizations in the Cloud portfolio; a bare /onboarding there opens the existing company's agent step.
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("when its response has a cloud field, this is a Paperclip Cloud stack, organizations are created in the person's Paperclip Cloud portfolio rather than in this app, so say that and do not link /onboarding");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("/onboarding takes no company prefix; /<prefix>/onboarding only adds an agent to this company");
|
||||
const nameRule = AGENT_CHAT_DIRECTIVE.indexOf("Only when none of these gives a name, ask for it before starting");
|
||||
expect(nameRule).toBeGreaterThan(-1);
|
||||
expect(AGENT_CHAT_DIRECTIVE.indexOf("It never comes before a board-only boundary")).toBeGreaterThan(nameRule);
|
||||
});
|
||||
// Full chat cohort 4 (app-permissions.ask-before-action): after a decline, the repeated request got "tell me to resubmit".
|
||||
it("treats a repeated request after a declined approval card as an explicit retry that posts a fresh card", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("the new message is an explicit retry, not an ambiguous request: make the same call again so Paperclip posts a fresh approval card");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Do not ask them to confirm the retry, tell them to resubmit, or treat the earlier decline as final.");
|
||||
});
|
||||
// Full chat cohort 4 (tasks.ambiguous-task): the clarification card named both candidates in plain option labels.
|
||||
it("puts candidate links in a clarification card's description, which renders links", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("If you ask with a question card instead, put the candidate links in the card's description");
|
||||
});
|
||||
it("tells chat that instruction saves keep no history, so an undo with no listed revision asks instead of reconstructing", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Saving instructions does not record earlier versions");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("an empty history means no earlier text is retained");
|
||||
|
||||
@@ -65482,9 +65482,14 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
expect((await readHeartbeatRunsByCompanyId(companyId)).filter(run => run.retryOfRunId === f.runId)).toHaveLength(1);
|
||||
} else {
|
||||
expect([202, 409], JSON.stringify(response.body)).toContain(response.status);
|
||||
if (response.status === 202) {
|
||||
if (response.status === 202 && response.body.chatActionId) {
|
||||
const outcome = await f.service.processFailedChatRunRetry(response.body.chatActionId);
|
||||
expect(outcome.status).not.toBe("queued");
|
||||
} else if (response.status === 202) {
|
||||
const [intent] = await readAgentWakeupRequestsById(response.body.requestId);
|
||||
expect(intent).toMatchObject({ reason: "task_retry", requestedByActorId: "owner-user",
|
||||
payload: { issueId, taskRetry: { sourceRunId: f.runId } } });
|
||||
expect((intent.payload!.taskRetry as Record<string, unknown>).chatActionId).toBeUndefined();
|
||||
}
|
||||
expect((await readHeartbeatRunsByCompanyId(companyId)).filter(run => run.retryOfRunId === f.runId)).toHaveLength(0);
|
||||
}
|
||||
@@ -66301,7 +66306,12 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
}
|
||||
const response = await send();
|
||||
if (["principal_revoked", "accepted_result"].includes(mode)) {
|
||||
expect(response.status).toBe(409);
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(202);
|
||||
expect(response.body.chatActionId).toBeUndefined();
|
||||
const [intent] = await readAgentWakeupRequestsById(response.body.requestId);
|
||||
expect(intent).toMatchObject({ reason: "task_retry", requestedByActorId: "owner-user",
|
||||
payload: { issueId, taskRetry: { sourceRunId: f.runId } } });
|
||||
expect((intent.payload!.taskRetry as Record<string, unknown>).chatActionId).toBeUndefined();
|
||||
} else {
|
||||
expect(response.status).toBe(202);
|
||||
if (mode === "source_edited") await db.update(issueComments).set({ body: "Changed after Retry acceptance" }).where(eq(issueComments.id, String(f.action.payload.commentId)));
|
||||
@@ -66389,11 +66399,26 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
const denySource = async (apply: () => Promise<unknown>, restore: () => Promise<unknown>, stale = false) => {
|
||||
try {
|
||||
await apply();
|
||||
const denied = await request(app).post(`/api/issues/${issueId}/retry`).send({ idempotencyKey: randomUUID(), observedRunId: current!.id }).expect(stale ? 200 : 409);
|
||||
if (stale) expect(denied.body).toMatchObject({ accepted: false, stale: true });
|
||||
expect(await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry")))).toHaveLength(0);
|
||||
} finally { await restore(); }
|
||||
const denied = await request(app).post(`/api/issues/${issueId}/retry`).send({ idempotencyKey: randomUUID(), observedRunId: current!.id }).expect(stale ? 200 : 202);
|
||||
const retries = await db.select().from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry")));
|
||||
if (stale) {
|
||||
expect(denied.body).toMatchObject({ accepted: false, stale: true });
|
||||
expect(retries).toHaveLength(0);
|
||||
} else {
|
||||
expect(denied.body.chatActionId).toBeUndefined();
|
||||
expect(retries).toHaveLength(1);
|
||||
expect(retries[0]).toMatchObject({ id: denied.body.requestId, requestedByActorId: "owner-user",
|
||||
payload: { issueId, taskRetry: { sourceRunId: current!.id } } });
|
||||
const taskRetry = retries[0].payload!.taskRetry as Record<string, unknown>;
|
||||
expect(taskRetry.boardMessageOrigin).toBeUndefined();
|
||||
expect(taskRetry.chatActionId).toBeUndefined();
|
||||
}
|
||||
} finally {
|
||||
await db.delete(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
|
||||
eq(agentWakeupRequests.reason, "task_retry")));
|
||||
await restore();
|
||||
}
|
||||
};
|
||||
await denySource(() => db.update(issueComments).set({ body: "Edited after acceptance", updatedAt: new Date() }).where(eq(issueComments.id, comment.id)),
|
||||
() => db.update(issueComments).set({ body: comment.body, updatedAt: sql`${issueComments.createdAt}` }).where(eq(issueComments.id, comment.id)));
|
||||
@@ -66504,17 +66529,26 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
const [firstRetry] = await readHeartbeatRunsById(successor.id);
|
||||
const nextRequest = () => request(app).post(`/api/issues/${issueId}/retry`).send({
|
||||
idempotencyKey: randomUUID(), observedRunId: firstRetry.id });
|
||||
const continueWithoutReplay = async () => {
|
||||
const continued = await nextRequest().expect(202);
|
||||
expect(continued.body.chatActionId).toBeUndefined();
|
||||
const [intent] = await readAgentWakeupRequestsById(continued.body.requestId);
|
||||
expect(intent).toMatchObject({ reason: "task_retry", requestedByActorId: "owner-user",
|
||||
payload: { issueId, taskRetry: { sourceRunId: firstRetry.id } } });
|
||||
expect((intent.payload!.taskRetry as Record<string, unknown>).boardMessageOrigin).toBeUndefined();
|
||||
await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.id, intent.id));
|
||||
};
|
||||
await db.update(heartbeatRuns).set({ sessionIdAfter: "contradictory-provider-session" }).where(eq(heartbeatRuns.id, firstRetry.id));
|
||||
await nextRequest().expect(409);
|
||||
await continueWithoutReplay();
|
||||
await db.update(heartbeatRuns).set({ sessionIdAfter: null }).where(eq(heartbeatRuns.id, firstRetry.id));
|
||||
await db.update(issueComments).set({ body: "Changed original accepted message", updatedAt: new Date() }).where(eq(issueComments.id, comment.id));
|
||||
await nextRequest().expect(409);
|
||||
await continueWithoutReplay();
|
||||
await db.update(issueComments).set({ body: comment.body, updatedAt: sql`${issueComments.createdAt}` }).where(eq(issueComments.id, comment.id));
|
||||
const [firstIntent] = await readAgentWakeupRequestsById(retry.id);
|
||||
await db.update(agentWakeupRequests).set({ payload: { ...firstIntent.payload,
|
||||
taskRetry: { ...(firstIntent.payload!.taskRetry as object), sourceRunId: firstRetry.id } } }).where(eq(agentWakeupRequests.id, firstIntent.id));
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { ...firstRetry.contextSnapshot, previousRunId: firstRetry.id } }).where(eq(heartbeatRuns.id, firstRetry.id));
|
||||
await nextRequest().expect(409);
|
||||
await continueWithoutReplay();
|
||||
await db.update(agentWakeupRequests).set({ payload: firstIntent.payload }).where(eq(agentWakeupRequests.id, firstIntent.id));
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: firstRetry.contextSnapshot }).where(eq(heartbeatRuns.id, firstRetry.id));
|
||||
const second = await nextRequest().expect(202);
|
||||
@@ -66555,7 +66589,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("distinguishes an inherited GitHub requester from permission to replay a committed provider failure", async () => {
|
||||
it("continues an inherited GitHub task from its recorded result instead of replaying the committed provider failure", async () => {
|
||||
const f = await failedChatRetryFixture("github", "42", true, false, true);
|
||||
try {
|
||||
const companyId = f.fixture.companyId, agentId = f.fixture.assignedAgentId, issueId = f.issue.id;
|
||||
@@ -66604,19 +66638,30 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
app.use((req, _res, next) => { req.actor = boardActor(companyId); next(); });
|
||||
app.use("/api", issueRoutes(db, createStorageService().storage, { chatRunRetries: f.service }));
|
||||
app.use(errorHandler);
|
||||
const denied = await request(app).post(`/api/issues/${issueId}/retry`).send({
|
||||
const continued = await request(app).post(`/api/issues/${issueId}/retry`).send({
|
||||
idempotencyKey: input.idempotencyKey, observedRunId: input.observedRunId,
|
||||
}).expect(409);
|
||||
expect(denied.body).toMatchObject({ error: "This attempt already recorded a result. Send a new message on the task to continue from the saved work.",
|
||||
details: { code: "chat_failed_run_retry_not_authorized", reason: "accepted_result_without_new_input" } });
|
||||
// Isolate the later accepted-result guard using only owned fixture data.
|
||||
// Resolving inherited provenance cannot by itself authorize replay.
|
||||
}).expect(202);
|
||||
expect(continued.body).toMatchObject({ accepted: true, stale: false, observedRunId: resumed!.id });
|
||||
expect(continued.body.chatActionId).toBeUndefined();
|
||||
const assertBoardContinuation = async (requestId: string) => {
|
||||
const [intent] = await readAgentWakeupRequestsById(requestId);
|
||||
expect(intent).toMatchObject({ reason: "task_retry", requestedByActorType: "user", requestedByActorId: "owner-user",
|
||||
payload: { issueId, taskRetry: { sourceRunId: resumed!.id, actorId: "owner-user" } } });
|
||||
expect((intent.payload!.taskRetry as Record<string, unknown>).chatActionId).toBeUndefined();
|
||||
expect(await db.select().from(chatActions).where(and(eq(chatActions.companyId, companyId),
|
||||
eq(chatActions.kind, "failed_run_retry")))).toHaveLength(0);
|
||||
await db.update(agentWakeupRequests).set({ status: "failed", finishedAt: new Date() }).where(eq(agentWakeupRequests.id, requestId));
|
||||
};
|
||||
await assertBoardContinuation(continued.body.requestId);
|
||||
// The later accepted-result guard also continues from the saved result
|
||||
// instead of repeating the exact chat request.
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { ...failedResume.contextSnapshot,
|
||||
source: "chat:github", wakeCommentId: f.action.payload.commentId, wakeCommentIds: [f.action.payload.commentId] } })
|
||||
.where(eq(heartbeatRuns.id, failedResume.id));
|
||||
try {
|
||||
await expect(requestTaskRetry({ ...input, idempotencyKey: randomUUID() })).rejects.toMatchObject({ details: {
|
||||
code: "chat_failed_run_retry_not_authorized", reason: "accepted_result_without_new_input" } });
|
||||
const receipt = await requestTaskRetry({ ...input, idempotencyKey: randomUUID() });
|
||||
expect(receipt).toMatchObject({ accepted: true, chatActionId: undefined });
|
||||
await assertBoardContinuation(receipt.requestId!);
|
||||
} finally { await db.update(heartbeatRuns).set({ contextSnapshot: failedResume.contextSnapshot }).where(eq(heartbeatRuns.id, failedResume.id)); }
|
||||
expect((await readHeartbeatRunsByCompanyId(companyId)).filter(run => run.retryOfRunId === resumed!.id)).toHaveLength(0);
|
||||
} finally { await f.service.shutdown(); }
|
||||
@@ -67175,9 +67220,12 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
} finally { unsubscribes.forEach(unsubscribe => unsubscribe()); }
|
||||
}
|
||||
if (mode !== "committed_board_existing" && mode !== "committed_board_existing_coalesced" && mode !== "committed_board_existing_identity_contended" && mode !== "committed_board_existing_identity_expired") {
|
||||
await expect(requestTaskRetry(nextInput)).rejects.toMatchObject({
|
||||
details: { code: "chat_failed_run_retry_not_authorized" },
|
||||
});
|
||||
const continued = await requestTaskRetry(nextInput);
|
||||
expect(continued).toMatchObject({ accepted: true, chatActionId: undefined });
|
||||
const [intent] = await readAgentWakeupRequestsById(continued.requestId!);
|
||||
expect(intent).toMatchObject({ reason: "task_retry", requestedByActorId: "owner-user",
|
||||
payload: { taskRetry: { sourceRunId: failed.id } } });
|
||||
expect((intent.payload!.taskRetry as Record<string, unknown>).chatActionId).toBeUndefined();
|
||||
expect(await db.select().from(agentWakeupRequests).where(inArray(agentWakeupRequests.id, inputIds)).orderBy(asc(agentWakeupRequests.id)))
|
||||
.toEqual(before);
|
||||
return;
|
||||
|
||||
@@ -36,6 +36,7 @@ import { requestTaskRetry } from "../services/task-retry.js";
|
||||
import { adapterExecutionControls, createAdapterExecutionControl } from "../services/adapter-execution-control.js";
|
||||
import { execFileSync, spawn, spawnSync, type ChildProcess } from "node:child_process";
|
||||
import { currentControllerProcessStamp } from "../services/controller-process-identity.js";
|
||||
import { registerControllerInstanceDb, resetControllerInstanceLeaseForTests } from "../services/controller-instance-lease.js";
|
||||
import { settleUnrecoverableExecutions } from "../services/execution-recovery-resolution.js";
|
||||
import { createOwnershipReportState, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js";
|
||||
import fs from "node:fs/promises";
|
||||
@@ -55,6 +56,7 @@ import {
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
controllerInstances,
|
||||
agentTaskSessions,
|
||||
agentRuntimeState,
|
||||
agentWakeupRequests,
|
||||
@@ -3733,15 +3735,19 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
/** A conversation-adapter run in progress. `alreadyRetried` makes it the
|
||||
* second automatic retry of a chain whose real failures spent the budget. */
|
||||
async function seedInterruptibleRun(input: { alreadyRetried: boolean; owner: "this_server" | "replaced_server";
|
||||
accounting?: Record<string, unknown> }) {
|
||||
const fixture = await seedRunFixture({ adapterType: "codex_local", agentStatus: "running", runtimeMode: "legacy",
|
||||
contextSnapshot: { wakeReason: "issue_monitor_due" } });
|
||||
accounting?: Record<string, unknown>; adapterType?: string; executionStage?: "preparing" | "dispatching";
|
||||
controllerBootId?: string; controllerProcess?: Record<string, unknown>; leaseExpiredSeconds?: number }) {
|
||||
const fixture = await seedRunFixture({ adapterType: input.adapterType ?? "codex_local", agentStatus: "running",
|
||||
runtimeMode: "legacy", contextSnapshot: { wakeReason: "issue_monitor_due" } });
|
||||
const [seeded] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
await db.update(heartbeatRuns).set({
|
||||
controllerBootId: input.owner === "this_server" ? controllerLeases.legacyControllerBootId : randomUUID(),
|
||||
controllerBootId: input.owner === "this_server" ? controllerLeases.legacyControllerBootId
|
||||
: input.controllerBootId ?? randomUUID(),
|
||||
...(input.controllerProcess ? { controllerProcess: input.controllerProcess } : {}),
|
||||
controllerLeaseExpiresAt: input.owner === "this_server"
|
||||
? sql`clock_timestamp() + interval '1 minute'` : sql`clock_timestamp() - interval '1 second'`,
|
||||
executionStage: "dispatching",
|
||||
? sql`clock_timestamp() + interval '1 minute'`
|
||||
: sql`clock_timestamp() - make_interval(secs => ${input.leaseExpiredSeconds ?? 1})`,
|
||||
executionStage: input.executionStage ?? "dispatching",
|
||||
...(input.alreadyRetried ? { scheduledRetryReason: "transient_failure", scheduledRetryAttempt: 2 } : {}),
|
||||
contextSnapshot: {
|
||||
...(seeded!.contextSnapshot ?? {}),
|
||||
@@ -3878,6 +3884,84 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
scheduledRetryReason: "server_restart", scheduledRetryAttempt: 1 })]);
|
||||
});
|
||||
|
||||
// Production shape (staging, 2026-11-12): every run the replacement server
|
||||
// reaped was a Runner run still preparing (no process recorded), so the
|
||||
// reaper marked it bootstrap/providerWorkStarted=false. Those successors
|
||||
// went to the charged transient_failure lane instead of server_restart.
|
||||
it.each([
|
||||
{ name: "a first attempt", alreadyRetried: false },
|
||||
{ name: "a run that was already the last automatic retry", alreadyRetried: true },
|
||||
])("continues $name that a replaced server left preparing, in the restart lane", async ({ alreadyRetried }) => {
|
||||
// The replaced server stamped its process on the claim. It is in another
|
||||
// container and has no live server lease, so it is not proven alive.
|
||||
const bootId = randomUUID();
|
||||
const fixture = await seedInterruptibleRun({ alreadyRetried, owner: "replaced_server",
|
||||
adapterType: "paperclip_runner", executionStage: "preparing", controllerBootId: bootId,
|
||||
controllerProcess: { bootId, pid: 3, hostHash: "replaced-server-container",
|
||||
processStartedAt: new Date(Date.now() - 60 * 60_000).toISOString() } });
|
||||
|
||||
await Promise.all([heartbeatService(db).reapOrphanedRuns(), heartbeatService(db).reapOrphanedRuns()]);
|
||||
|
||||
const [lost] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
expect(lost).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
||||
expect(lost!.resultJson).toMatchObject({ executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
||||
processLossDiagnostic: { controllerReplaced: true, retryEligible: true } });
|
||||
await expectOneRestartContinuation(fixture, alreadyRetried ? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS : 0);
|
||||
await heartbeatService(db).reconcileStrandedAssignedIssues();
|
||||
expect(await successorsOf(fixture.companyId, fixture.runId)).toHaveLength(1);
|
||||
});
|
||||
|
||||
describe("while the server that owns the run is still serving", () => {
|
||||
const oldBootId = randomUUID();
|
||||
const oldServer = { bootId: oldBootId, pid: 3, hostHash: "old-server-container",
|
||||
processStartedAt: new Date(Date.now() - 60 * 60_000).toISOString() };
|
||||
|
||||
beforeEach(async () => {
|
||||
// The old server's own process lease is live: it is alive and serving.
|
||||
await db.insert(controllerInstances).values({ bootId: oldBootId, processSpace: oldServer.hostHash, pid: oldServer.pid,
|
||||
leaseExpiresAt: new Date(Date.now() + 60_000) });
|
||||
registerControllerInstanceDb(db);
|
||||
});
|
||||
afterEach(async () => {
|
||||
resetControllerInstanceLeaseForTests();
|
||||
await db.delete(controllerInstances);
|
||||
});
|
||||
|
||||
it.each(["preparing", "dispatching"] as const)(
|
||||
"leaves a %s run whose lease lapsed with its owner, then recovers it once the owner stops", async (executionStage) => {
|
||||
// A slow database held the owner's renewal past the 60 s lease while
|
||||
// the new server was already running its recovery sweeps.
|
||||
const fixture = await seedInterruptibleRun({ alreadyRetried: false, owner: "replaced_server",
|
||||
adapterType: "paperclip_runner", executionStage, controllerBootId: oldBootId, controllerProcess: oldServer });
|
||||
|
||||
await Promise.all([heartbeatService(db).reapOrphanedRuns(), heartbeatService(db).reapOrphanedRuns()]);
|
||||
|
||||
const [kept] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
expect(kept).toMatchObject({ status: "running", controllerBootId: oldBootId, errorCode: null });
|
||||
expect(await successorsOf(fixture.companyId, fixture.runId)).toEqual([]);
|
||||
|
||||
// The old server shut down: its process lease is stopped, so the run is lost now.
|
||||
await db.update(controllerInstances).set({ stoppedAt: new Date() }).where(eq(controllerInstances.bootId, oldBootId));
|
||||
await heartbeatService(db).reapOrphanedRuns();
|
||||
|
||||
const [lost] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
expect(lost).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
||||
if (executionStage === "preparing") await expectOneRestartContinuation(fixture, 0);
|
||||
});
|
||||
|
||||
it("recovers the run when its live owner has not settled it within the grace", async () => {
|
||||
const fixture = await seedInterruptibleRun({ alreadyRetried: false, owner: "replaced_server",
|
||||
adapterType: "paperclip_runner", executionStage: "preparing", controllerBootId: oldBootId,
|
||||
controllerProcess: oldServer, leaseExpiredSeconds: controllerLeases.LEGACY_LIVE_OWNER_SETTLE_GRACE_MS / 1000 + 1 });
|
||||
|
||||
await heartbeatService(db).reapOrphanedRuns();
|
||||
|
||||
const [lost] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
expect(lost).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
||||
await expectOneRestartContinuation(fixture, 0);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the failure budget for a run that failed on its own", async () => {
|
||||
const fixture = await seedInterruptibleRun({ alreadyRetried: true, owner: "this_server" });
|
||||
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "adapter_failed", error: "Adapter failed",
|
||||
|
||||
@@ -271,6 +271,38 @@ suite("held interrupted preparations on the shared ownership path", () => {
|
||||
expect(successors[0]).toMatchObject({ scheduledRetryReason: "interrupted_preparation" });
|
||||
});
|
||||
|
||||
// Staging upgrade shape: a replaced server's Runner preparation was reaped as
|
||||
// process_lost while it was the last automatic retry (failure budget spent).
|
||||
// An older release held it for reconciliation ("Automatic recovery stopped").
|
||||
it.each([
|
||||
["its lease still names the old controller", false],
|
||||
// The real reaped shape: revocation swapped in a random boot id and kept the process stamp.
|
||||
["the orphan reaper revoked its lease", true],
|
||||
] as const)("releases an older release's hold on a preparation a server replacement stopped with its failure budget spent when %s", async (_label, revoked) => {
|
||||
heartbeatService(db);
|
||||
const finishedAt = new Date(Date.now() - 10_000);
|
||||
const f = await interruptedPreparation({ run: { status: "failed", errorCode: "process_lost",
|
||||
error: "Process lost -- server may have restarted", scheduledRetryAttempt: 2,
|
||||
resultJson: { stopReason: "process_lost", executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
||||
processLossDiagnostic: { pidRecorded: false, groupRecorded: false, localCheck: "no_identifiers",
|
||||
retryEligible: false, controllerReplaced: true } },
|
||||
contextSnapshot: undefined, finishedAt } });
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId,
|
||||
executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 0 } },
|
||||
...(revoked ? { controllerBootId: randomUUID() } : {}) })
|
||||
.where(eq(heartbeatRuns.id, f.runId));
|
||||
expect(await getExecutionBlocker(db, companyId, f.issueId)).toMatchObject({ cause: "legacy_execution_requires_reconciliation" });
|
||||
|
||||
expect(await pass()).toMatchObject({ inProgress: 1, settled: 1 });
|
||||
|
||||
expect(await hold(f.holdId)).toMatchObject({ status: "resolved", outcome: "false_positive" });
|
||||
expect(await getExecutionBlocker(db, companyId, f.issueId)).toBeNull();
|
||||
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toMatchObject({ status: "in_progress" });
|
||||
const successors = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, f.runId));
|
||||
expect(successors).toEqual([expect.objectContaining({ scheduledRetryReason: "server_restart", scheduledRetryAttempt: 1 })]);
|
||||
expect(successors[0]!.contextSnapshot?.executionRetryAccounting).toMatchObject({ failureRetries: 2, serverRestarts: 1 });
|
||||
});
|
||||
|
||||
it("clears the saved-files gate of a lost-lease preparation that an older release blocked, so one Retry continues it", async () => {
|
||||
const heartbeat = heartbeatService(db);
|
||||
const f = await leaseLostSavedFilesHold({ keepStatusReceipt: false });
|
||||
@@ -337,6 +369,36 @@ suite("held interrupted preparations on the shared ownership path", () => {
|
||||
expect(receipt).toMatchObject({ accepted: true });
|
||||
}, 120_000);
|
||||
|
||||
// The scheduler gives a settled lost preparation the interrupted_preparation
|
||||
// lane; the synchronous budget check reads the server-restart bound of the
|
||||
// replaced owner. When only the preparation bound is spent, the sweep must
|
||||
// still report the exhaustion instead of leaving the task in_progress.
|
||||
it("blocks the task when a replaced preparation's lane is spent even though the restart bound is not", async () => {
|
||||
const heartbeat = heartbeatService(db);
|
||||
const controller = await deadController();
|
||||
const issueId = randomUUID(), runId = randomUUID();
|
||||
const finishedAt = new Date(Date.now() - 30 * 60_000);
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Replaced preparation", status: "todo",
|
||||
assigneeAgentId: agentId, statusVersion: 2 });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "automation",
|
||||
responsibleUserId: "local-board", issueId, status: "failed", errorCode: "process_lost",
|
||||
error: "Process lost -- server may have restarted", runtimeMode: "legacy", executionStage: "preparing",
|
||||
startedAt: new Date(finishedAt.getTime() - 2_000), finishedAt, nextEventSeq: 1,
|
||||
controllerBootId: controller.bootId, controllerProcess: controller.process,
|
||||
scheduledRetryAttempt: 12, scheduledRetryReason: "interrupted_preparation",
|
||||
runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } },
|
||||
contextSnapshot: { issueId, retryReason: "interrupted_preparation", executionRetryAccounting: { version: 1,
|
||||
failureRetries: 0, maxTurnContinuations: 0, interruptedPreparations: 12 } },
|
||||
resultJson: { stopReason: "process_lost", executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
||||
processLossDiagnostic: { pidRecorded: false, groupRecorded: false, localCheck: "no_identifiers",
|
||||
retryEligible: true, controllerReplaced: true } } });
|
||||
|
||||
await heartbeat.reconcileStrandedAssignedIssues({ companyId, issueId });
|
||||
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toEqual([]);
|
||||
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "blocked" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["provider work started", { kind: "bootstrap", providerWorkStarted: true }],
|
||||
["it has no no-provider-work certificate", undefined],
|
||||
|
||||
@@ -410,6 +410,29 @@ describe("openapi routes", () => {
|
||||
for (const code of ["200", "401", "403"]) expect(operation.responses[code]).toBeDefined();
|
||||
});
|
||||
|
||||
// Full chat cohort 4: search_api listed the cancel route as open to agents, so an agent tried it and got 403.
|
||||
it("documents question cancellation as board-only and points agents to withdraw", () => {
|
||||
const spec = buildOpenApiSpec() as any;
|
||||
const cancel = spec.paths["/api/issues/{id}/interactions/{interactionId}/cancel"].post;
|
||||
expect(cancel["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
||||
expect(cancel.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
||||
expect(cancel.summary).toContain("POST /api/issues/{id}/interactions/{interactionId}/withdraw");
|
||||
expect(spec.paths["/api/issues/{id}/interactions/{interactionId}/withdraw"].post["x-paperclip-authorization"]).toEqual({ actor: "board_or_agent" });
|
||||
});
|
||||
|
||||
it("points agents to resolve-from-comment to record a person's decline and keeps withdraw for their own obsolete card", () => {
|
||||
const spec = buildOpenApiSpec() as any;
|
||||
const interaction = "/api/issues/{id}/interactions/{interactionId}";
|
||||
for (const summary of [spec.paths[`${interaction}/cancel`].post.summary, spec.paths[`${interaction}/withdraw`].post.summary]) {
|
||||
expect(summary).toContain("only for the agent's own obsolete card");
|
||||
expect(summary).toContain(`POST ${interaction}/resolve-from-comment`);
|
||||
expect(summary).toContain("when the card's resolver policy allows");
|
||||
expect(summary).toContain("to accept or decline a confirmation card on the person's explicit instruction");
|
||||
expect(summary).toContain("not for question forms or governed approvals");
|
||||
}
|
||||
expect(spec.paths[`${interaction}/resolve-from-comment`].post.summary).toContain("including a decline of a card the person created");
|
||||
});
|
||||
|
||||
it("documents the owned pending-question read as canonical attention items without client scope overrides", () => {
|
||||
const spec = buildOpenApiSpec() as any;
|
||||
const operation = spec.paths["/api/issues/{id}/pending-questions"].get;
|
||||
@@ -806,7 +829,7 @@ describe("openapi routes", () => {
|
||||
expect(
|
||||
res.body.paths["/api/issues/{id}/interactions/{interactionId}/withdraw"]
|
||||
.post.summary,
|
||||
).toBe("Withdraw a pending issue thread interaction");
|
||||
).toMatch(/^Withdraw a pending issue thread interaction\. /);
|
||||
const createInteraction =
|
||||
res.body.paths["/api/issues/{id}/interactions"].post;
|
||||
expect(createInteraction.description).toContain(
|
||||
|
||||
@@ -226,6 +226,7 @@ import { chatInboundWakeNoticeWork } from "./services/chat-inbound-wake-notice-w
|
||||
import { chatFailedRetryNoticeWork } from "./services/chat-failed-retry-notice-work.js";
|
||||
import { chatRunMilestoneWork } from "./services/chat-run-milestone-work.js";
|
||||
import { heartbeatService } from "./services/heartbeat.js";
|
||||
import { registerInterruptedTurnChatRetry } from "./services/heartbeat/restart-interrupted-turn.js";
|
||||
import { pluginLifecycleManager } from "./services/plugin-lifecycle.js";
|
||||
import { registerPluginLifecycleDelivery } from "./services/plugin-lifecycle-delivery.js";
|
||||
import { createPluginJobCoordinator } from "./services/plugin-job-coordinator.js";
|
||||
@@ -603,6 +604,8 @@ export async function createApp(
|
||||
storage: opts.storageService,
|
||||
});
|
||||
if (opts.budgetResumeDelivery) opts.budgetResumeDelivery.prepareChatRetry = chatChannels.prepareFailedChatRunRetry;
|
||||
// A restart's automatic Retry of a connected conversation needs the same callback.
|
||||
registerInterruptedTurnChatRetry(chatChannels.prepareFailedChatRunRetry);
|
||||
// Voice capabilities are verified by the signed callback route, not by
|
||||
// board/agent bearer authentication. Mount before actorMiddleware so its
|
||||
// per-session Bearer cannot be mistaken for an agent API key.
|
||||
|
||||
@@ -1462,6 +1462,9 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"POST /api/companies/{companyId}/attention/{sourceKind}/{sourceId}/transfer",
|
||||
"POST /api/approvals/{id}/cancel",
|
||||
"POST /api/issues/{id}/interactions/{interactionId}/dismiss",
|
||||
// Cancelling a question is board-only (routes/issues.ts rejects agent actors). Withdraw is not listed here: its
|
||||
// route admits the card's creator agent and the task's assignee, so agents withdraw their own pending card there.
|
||||
"POST /api/issues/{id}/interactions/{interactionId}/cancel",
|
||||
"POST /api/issues/{id}/retry",
|
||||
"GET /api/companies/{companyId}/prompt-injection-prevention",
|
||||
"PUT /api/companies/{companyId}/prompt-injection-prevention",
|
||||
@@ -1557,7 +1560,6 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"POST /api/issues/{id}/interactions/{interactionId}/reject",
|
||||
"POST /api/issues/{id}/interactions/{interactionId}/respond",
|
||||
"POST /api/issues/{id}/interactions/{interactionId}/skip",
|
||||
"POST /api/issues/{id}/interactions/{interactionId}/withdraw",
|
||||
"POST /api/companies/{companyId}/tools/examples/{id}/smoke",
|
||||
"POST /api/agents/me/connections/{connectionId}/token",
|
||||
"GET /api/tools/oauth/callback",
|
||||
@@ -8676,7 +8678,7 @@ registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/issues/{id}/interactions/{interactionId}/resolve-from-comment",
|
||||
tags: ["issues"],
|
||||
summary: "Record a user's conversational confirmation answer",
|
||||
summary: "Record a user's conversational confirmation answer, including a decline of a card the person created",
|
||||
description: "An eligible active agent run resolves a confirmation on its own task using the latest user comment. Resolver permissions, target staleness and conversation reset boundaries remain enforced. Matching retries are idempotent. No new wake is scheduled.",
|
||||
request: {
|
||||
params: z.object({ id: z.string(), interactionId: z.string() }),
|
||||
@@ -8758,7 +8760,7 @@ registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/issues/{id}/interactions/{interactionId}/withdraw",
|
||||
tags: ["issues"],
|
||||
summary: "Withdraw a pending issue thread interaction",
|
||||
summary: "Withdraw a pending issue thread interaction. For agents, withdraw is only for the agent's own obsolete card; to accept or decline a confirmation card on the person's explicit instruction, an agent records the person's comment with POST /api/issues/{id}/interactions/{interactionId}/resolve-from-comment when the card's resolver policy allows (not for question forms or governed approvals)",
|
||||
request: {
|
||||
params: z.object({ id: z.string(), interactionId: z.string() }),
|
||||
body: jsonBody(withdrawIssueThreadInteractionSchema),
|
||||
@@ -11489,7 +11491,7 @@ registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/issues/{id}/interactions/{interactionId}/cancel",
|
||||
tags: ["issues"],
|
||||
summary: "Cancel an issue question interaction",
|
||||
summary: "Cancel an issue question interaction (board users only). Agents: POST /api/issues/{id}/interactions/{interactionId}/withdraw is only for the agent's own obsolete card; to accept or decline a confirmation card on the person's explicit instruction, an agent records the person's comment with POST /api/issues/{id}/interactions/{interactionId}/resolve-from-comment when the card's resolver policy allows (not for question forms or governed approvals)",
|
||||
body: cancelIssueThreadInteractionSchema,
|
||||
});
|
||||
|
||||
@@ -11512,7 +11514,7 @@ registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/issues/{id}/interactions/{interactionId}/withdraw",
|
||||
tags: ["issues"],
|
||||
summary: "Withdraw a pending issue thread interaction",
|
||||
summary: "Withdraw a pending issue thread interaction. For agents, withdraw is only for the agent's own obsolete card; to accept or decline a confirmation card on the person's explicit instruction, an agent records the person's comment with POST /api/issues/{id}/interactions/{interactionId}/resolve-from-comment when the card's resolver policy allows (not for question forms or governed approvals)",
|
||||
body: withdrawIssueThreadInteractionSchema,
|
||||
});
|
||||
|
||||
|
||||
@@ -90,7 +90,9 @@ export function isConversationReset(body: string): boolean {
|
||||
return body.trim() === "/new";
|
||||
}
|
||||
|
||||
export const AGENT_CHAT_DIRECTIVE = `You are in an ongoing conversation with the user. Help them clarify the outcome they want. Ask focused questions when missing information materially affects the task; when the request is already clear, do not require a ritual confirmation. When a request to change one record matches several records you can access and nothing in the conversation selects one, ask which one before changing any of them: link each candidate, name what distinguishes them (such as project or status), and restate the requested change. Do not pick the first match, change every match, or keep searching for a hidden answer; asking in your reply is enough, and you finish the change when the person answers. When the person asks you to build or hand off something that must carry a name, such as the product or brand name shown on a landing page, use the name their request, this conversation or the work's saved brief gives; a project the person names in the request counts, so "Start a Launch project and build its landing page" carries the name Launch and needs no question. Only when none of these gives a name, ask for it before starting: use request_human_input with interactionKind: "questions" and one required free-text question, then end your turn. Do not take the name from unrelated records such as other existing projects or the company name. Do not build, delegate or brief the work with an invented or placeholder name; when the answer arrives, put it in the brief of the work you create.
|
||||
export const AGENT_CHAT_DIRECTIVE = `You are in an ongoing conversation with the user. Help them clarify the outcome they want. Ask focused questions when missing information materially affects the task; when the request is already clear, do not require a ritual confirmation. When a request to change one record matches several records you can access and nothing in the conversation selects one, ask which one before changing any of them: link each candidate, name what distinguishes them (such as project or status), and restate the requested change. Do not pick the first match, change every match, or keep searching for a hidden answer; asking in your reply is enough, and you finish the change when the person answers. If you ask with a question card instead, put the candidate links in the card's description: its option labels show as plain text, without links. When the person asks you to build or hand off something that must carry a name, such as the product or brand name shown on a landing page, use the name their request, this conversation or the work's saved brief gives; a project the person names in the request counts, so "Start a Launch project and build its landing page" carries the name Launch and needs no question. Only when none of these gives a name, ask for it before starting: use request_human_input with interactionKind: "questions" and one required free-text question, then end your turn. Do not take the name from unrelated records such as other existing projects or the company name. Do not build, delegate or brief the work with an invented or placeholder name; when the answer arrives, put it in the brief of the work you create. This name rule is for work you create yourself. It never comes before a board-only boundary: creating a new company (organization) is a person's action that no agent credential can take, so do not ask for its name or other details first. Reply now: tell the person where they create it and repeat the business details they gave so they can enter them there. Where depends on the deployment, which GET /api/health shows: when its response has a cloud field, this is a Paperclip Cloud stack, organizations are created in the person's Paperclip Cloud portfolio rather than in this app, so say that and do not link /onboarding. Otherwise link [Create organization](/onboarding), which opens the new-organization wizard (also Create organization in the company switcher). /onboarding takes no company prefix; /<prefix>/onboarding only adds an agent to this company.
|
||||
|
||||
When the person declined an approval card for an action and then asks for that same action again in a later message, the new message is an explicit retry, not an ambiguous request: make the same call again so Paperclip posts a fresh approval card for them to decide. Do not ask them to confirm the retry, tell them to resubmit, or treat the earlier decline as final.
|
||||
|
||||
When changing defaults or policy for new or future work, update the resource that owns those defaults. Leave existing items and active work unchanged unless the user explicitly includes them in the requested change. This boundary includes metadata and association changes, even when they seem harmless or helpful. Do not broaden the request to align related existing items. Explain which subsequent work inherits the saved defaults and whether existing work changed.
|
||||
|
||||
@@ -110,7 +112,7 @@ When a tool or save receipt rejects an action, tell the user which action failed
|
||||
|
||||
When the user asks to approve a plan before handoff, publish the plan and create a revision-bound approval card before ending the turn. With native tools, call request_human_input using interactionKind: "confirmation", targetRevisionId from the saved document's latestRevisionId, a revision-specific idempotencyKey, and continuationPolicy: "wake_assignee". Set payload.target to { type: "issue_document", key: "plan", revisionId: latestRevisionId }. Through the HTTP API, POST the equivalent request_confirmation interaction to /api/issues/{issueId}/interactions. A written request to approve in your reply does not create an approval card. After requested revisions, create a fresh card for the newly saved revision. This applies to explicitly requested plan approval; ordinary conversation replies and draft planning do not need confirmation. In Ask mode, discuss the plan without creating or revising documents or approval cards.
|
||||
|
||||
When a user answers a pending confirmation in chat, read the latest cards and user comments, identify the specific proposal and decision, and persist it before acting: POST /api/issues/{issueId}/interactions/{interactionId}/resolve-from-comment with { commentId: the user message ID, decision: "accept" or "reject" }. Use call_api on native runners. For a checkbox confirmation, also send selectedOptionIds for the choices the user actually approved; defaults alone are not consent. An ambiguous "yes" with multiple pending proposals requires clarification, not approving all of them. A requested revision is not acceptance. Do not use this endpoint for question forms or governed tool/secret approvals. Respect resolver-policy denials. If saving the decision fails, re-read the card and retry the same decision when appropriate before doing the approved work; never leave it pending and proceed anyway. If a card is already resolved, use its recorded outcome. Do not ask the user to clear a card after recording their answer.
|
||||
When a user answers a pending confirmation in chat, read the latest cards and user comments, identify the specific proposal and decision, and persist it before acting: POST /api/issues/{issueId}/interactions/{interactionId}/resolve-from-comment with { commentId: the user message ID, decision: "accept" or "reject" }. Use call_api on native runners. For a checkbox confirmation, also send selectedOptionIds for the choices the user actually approved; defaults alone are not consent. An ambiguous "yes" with multiple pending proposals requires clarification, not approving all of them. A requested revision is not acceptance. Do not use this endpoint for question forms or governed tool/secret approvals. Respect resolver-policy denials. A person's explicit decline in chat (for example "do not publish it") answers a pending confirmation with reject, whoever created the card: record it with resolve-from-comment when the card's resolver policy allows, then do the revised work. Withdraw is only for your own card that later evidence made obsolete; it never records the person's decision. If saving the decision fails, re-read the card and retry the same decision when appropriate before doing the approved work; never leave it pending and proceed anyway. If a card is already resolved, use its recorded outcome. Do not ask the user to clear a card after recording their answer.
|
||||
|
||||
Before handing off work, inspect available projects and repositories. Every task you create from this chat must belong to a suitable project. Reuse an appropriate existing project; otherwise use create_project. Consider all relevant available repositories and pass repositoryIds for one or multiple repositories when the work spans them. For existing GitHub repositories you can access that are absent from the catalog, pass their HTTPS repositoryUrls; this registers them with the project without creating remote GitHub repositories. You may combine known IDs and URLs and attach multiple repositories. The direct HTTP equivalent is POST /api/companies/{companyId}/projects with name, repositoryIds and/or repositoryUrls arrays, and an idempotencyKey. Include all selected repositories in that creation; do not combine these arrays with workspace. Never invent repository IDs or substitute inaccessible repositories. Ask when the choice is materially ambiguous or required access is missing. Non-code projects may need no repository.
|
||||
|
||||
|
||||
@@ -102,6 +102,9 @@ type DbOrTransaction = Db | Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
type DeliveryRow = typeof chatDeliveries.$inferSelect;
|
||||
type RetryRuntimeFence = { credentialFingerprint: string; generation: number };
|
||||
const FAILED_RUN_RETRY_IDENTITY_CONTENTION_MS = 60_000;
|
||||
const FAILED_CHAT_RETRY_DIAGNOSTIC = "This chat request can't be repeated exactly as it was sent. Retry continues the task from its saved work instead.";
|
||||
const FAILED_CHAT_RETRY_DIAGNOSTICS = [FAILED_CHAT_RETRY_DIAGNOSTIC,
|
||||
"The exact failed chat request can no longer be retried safely. Check its current connection, access, and recovery state."];
|
||||
export type ChatFailedRetrySource = Awaited<ReturnType<ReturnType<typeof createChatFailedRunRetry>["failedChatRetrySource"]>>;
|
||||
|
||||
type ChatFailedRunRetryOptions = {
|
||||
@@ -139,8 +142,8 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
|
||||
"prior_result_publication" | "prior_interaction" | "source_authorization", authorityReason?: ChatWakeAuthorityReason) =>
|
||||
conflict(
|
||||
reason === "accepted_result_without_new_input"
|
||||
? "This attempt already recorded a result. Send a new message on the task to continue from the saved work."
|
||||
: "The exact failed chat request can no longer be retried safely. Check its current connection, access, and recovery state.",
|
||||
? "This attempt already saved its result, so it is not repeated. Retry continues from that saved result."
|
||||
: FAILED_CHAT_RETRY_DIAGNOSTIC,
|
||||
{ code: "chat_failed_run_retry_not_authorized", ...(reason ? { reason } : {}), ...(reason === "source_authorization" && authorityReason ? { authorityReason } : {}) },
|
||||
);
|
||||
class FailedChatRetryPublicationReadError extends Error {
|
||||
@@ -227,8 +230,9 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
|
||||
run: typeof heartbeatRuns.$inferSelect,
|
||||
allowWorkspacePreparation = false,
|
||||
): Promise<boolean> {
|
||||
const retryDiagnostic = "The exact failed chat request can no longer be retried safely. Check its current connection, access, and recovery state.";
|
||||
const failedRetry = run.errorCode === "chat_failed_run_retry_not_authorized" && run.error === retryDiagnostic;
|
||||
const failedRetry = run.errorCode === "chat_failed_run_retry_not_authorized" &&
|
||||
FAILED_CHAT_RETRY_DIAGNOSTICS.includes(run.error ?? "");
|
||||
const retryDiagnostic = failedRetry ? run.error : null;
|
||||
const validation = run.resultJson?.workspaceValidation as Record<string, unknown> | undefined;
|
||||
const recovery = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
|
||||
const workspaceValidation = run.errorCode === "workspace_validation_failed" &&
|
||||
|
||||
@@ -1019,7 +1019,7 @@ export function heartbeatService(
|
||||
// Bound at call time: the heartbeat recovery module is created below.
|
||||
settleLostRunProcess: scope => recoverActiveExecutions(scope),
|
||||
settleExplicitContinuationRetry: releaseIssueExecutionAndPromote,
|
||||
scheduleRecoveryRetry: async (runId) => {
|
||||
scheduleRecoveryRetry: async (runId, outcome) => {
|
||||
const [run] = await db
|
||||
.select()
|
||||
.from(heartbeatRuns)
|
||||
@@ -1028,6 +1028,10 @@ export function heartbeatService(
|
||||
const agent = await getAgent(run.agentId);
|
||||
if (!agent || agent.companyId !== run.companyId) return null;
|
||||
const result = await scheduleBoundedRetryForRun(run, agent);
|
||||
// The scheduler's own lane verdict, so the sweep reports exhaustion even
|
||||
// when its lane (for example interrupted_preparation after cleanup)
|
||||
// differs from the synchronous budget check below.
|
||||
if (outcome && result.outcome === "retry_exhausted") outcome.retryExhausted = true;
|
||||
return result.outcome === "scheduled" ? result.run : null;
|
||||
},
|
||||
// Mirrors scheduleBoundedRetryForRun's transient budget check: a failed
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
pendingCleanupMetadataObjectSql,
|
||||
recoveredOrphanFirstAttemptSql,
|
||||
} from "../environment-cleanup-state.js";
|
||||
import { currentControllerProcess } from "../controller-process-identity.js";
|
||||
import { currentControllerProcess, readControllerProcess } from "../controller-process-identity.js";
|
||||
import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js";
|
||||
import { startNativeSessionExecutionLeaseRenewal, type NativeExecutionLeaseRenewal } from "../native-runtime/native-execution-lease.js";
|
||||
import type { WorkspaceWorkers } from "../plugin-workspaces.js";
|
||||
@@ -40,9 +40,10 @@ import { discoverSettledNativeRunProcesses, PROCESS_IDENTITY_RECORDED, PROCESS_S
|
||||
import { pendingCaseHandoffForRun } from "./case-handoff-lifecycle.js";
|
||||
import { retireInheritedRemoteRunnerIdentity } from "../native-runtime/native-inherited-runner-retry.js";
|
||||
import {
|
||||
LEGACY_LIVE_OWNER_SETTLE_GRACE_MS,
|
||||
legacyControllerBootId,
|
||||
legacyControllerProvenGone,
|
||||
liveLegacyControllerExpiresAt,
|
||||
proveLegacyController,
|
||||
revokeExpiredLegacyControllerWithState,
|
||||
} from "../legacy-controller-lease.js";
|
||||
import { remoteTerminationReceipt } from "../remote-execution-termination.js";
|
||||
@@ -2533,13 +2534,28 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
}
|
||||
// The shared prover (Phase 2): a controller of another boot whose
|
||||
// recorded process is proven gone holds no lease and needs no age guard.
|
||||
const legacyControllerGone = run.runtimeMode === "legacy" && run.controllerBootId !== legacyControllerBootId
|
||||
&& await legacyControllerProvenGone(run);
|
||||
const legacyControllerProof = run.runtimeMode === "legacy" && run.controllerBootId !== legacyControllerBootId
|
||||
? await proveLegacyController(run) : null;
|
||||
const legacyControllerGone = legacyControllerProof?.verdict === "gone";
|
||||
const legacyLease = await liveLegacyControllerExpiresAt(db, run);
|
||||
if (legacyLease && !(legacyControllerGone
|
||||
&& (await settleOwnableKind(db, "legacy_controller_lease", { runIds: [run.id] })).length > 0)) {
|
||||
scope.onDeferredDeadline?.(legacyLease.getTime()); continue;
|
||||
}
|
||||
// The lease lapsed, but its owner is another server process that is
|
||||
// proven alive: two servers serve together during every upgrade, and a
|
||||
// slow database can hold a renewal past the lease. The owner stops and
|
||||
// settles its own run (controller_lease_lost, in the uncharged
|
||||
// preparation lane). Declaring it lost here would race that owner and
|
||||
// charge the failure budget. Recover it only once the owner is gone, or
|
||||
// when it has not settled the run within the grace.
|
||||
if (!legacyLease && legacyControllerProof?.verdict === "alive" && run.controllerLeaseExpiresAt) {
|
||||
const ownerSettlesBy = run.controllerLeaseExpiresAt.getTime() + LEGACY_LIVE_OWNER_SETTLE_GRACE_MS;
|
||||
if (now.getTime() < ownerSettlesBy) {
|
||||
scope.onDeferredDeadline?.(Math.min(ownerSettlesBy, Date.now() + 30_000));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// A legacy controller proves it is alive only by renewing its lease, and
|
||||
// the check above found no live lease (a missing expiry also lands here;
|
||||
@@ -2690,7 +2706,11 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
// A conversation run that a restart ended draws on the server-restart
|
||||
// bound only. Other adapters keep the failure budget: a spent one
|
||||
// holds them for reconciliation (legacyExecutionNeedsReconciliation).
|
||||
!(controllerReplaced && conversationContinuationEligible
|
||||
// A setup that a restart stopped before dispatch did no provider work,
|
||||
// so it continues in the same lane whatever the adapter, when the row
|
||||
// names its owner process (isReplacedPreparation).
|
||||
!(controllerReplaced && (conversationContinuationEligible
|
||||
|| restartInterruptedBeforeDispatch && readControllerProcess(run.controllerProcess) !== null)
|
||||
? serverRestartBudgetSpent(run, now) : failedRunRetryBudgetSpent(run)) &&
|
||||
((tracksLegacyLocalChild &&
|
||||
(!!run.processPid || !!run.processGroupId)) ||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { agentWakeupRequests, heartbeatRunEvents, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db";
|
||||
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
||||
import type { NativeRestartRecoveryClaim } from "../native-runtime/native-restart-recovery.js";
|
||||
import { isUserCommentContinuationReason } from "../explicit-native-continuation.js";
|
||||
import { requestTaskRetry } from "../task-retry.js";
|
||||
import { EXTERNAL_CHAT_MESSAGE_WAKE_REASON } from "../queued-comment-delivery.js";
|
||||
import { HttpError } from "../../errors.js";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import { NATIVE_REMOTE_RECOVERY_LEASE_MISMATCH } from "../native-runtime/remote-recovery-lease-mismatch.js";
|
||||
@@ -40,40 +42,110 @@ export function isProvenTurnSettlement(event: { eventType: string; payload: unkn
|
||||
const PROVIDER_TURN_ACTIVITY_EVENTS = [...TURN_STARTED_EVENTS, ...TURN_SETTLED_EVENTS,
|
||||
"tool.execution.started", "tool.execution.completed"];
|
||||
|
||||
async function provenRunnerExit(db: Db, run: { companyId: string; id: string }) {
|
||||
const [refusal] = await db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
|
||||
eq(heartbeatRunEvents.eventType, "native.remote_runner_recovery_failed"),
|
||||
)).orderBy(desc(heartbeatRunEvents.seq)).limit(1);
|
||||
const proof = asRecord(asRecord(refusal?.payload).remoteRunnerRecovery);
|
||||
return proof.stage === "process_verification" && proof.reason === "process_not_running" ? proof : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The run's last refused reattachment proved its Runner process gone and its
|
||||
* controller journal proved that no turn command was ever issued
|
||||
* (`providerTurnIssued: false`, recorded by the executor). No turn or tool
|
||||
* event may exist either.
|
||||
*/
|
||||
async function hasProvenNoProviderTurn(db: Db, run: { companyId: string; id: string }) {
|
||||
async function hasProvenNoProviderTurn(db: Db, run: { companyId: string; id: string }, runnerExit: Record<string, unknown> | null) {
|
||||
if (runnerExit?.providerTurnIssued !== false) return false;
|
||||
const [activity] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
|
||||
inArray(heartbeatRunEvents.eventType, PROVIDER_TURN_ACTIVITY_EVENTS))).limit(1);
|
||||
if (activity) return false;
|
||||
const [refusal] = await db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(
|
||||
return !activity;
|
||||
}
|
||||
|
||||
export const INTERRUPTED_TURN_OUTCOME_UNKNOWN_EVENT = "native.interrupted_turn_outcome_unknown";
|
||||
|
||||
async function recordUnknownTurnOutcome(db: Db, run: { companyId: string; id: string; agentId: string },
|
||||
lastTurn: { eventType: string; payload: unknown }, runnerExit: Record<string, unknown>) {
|
||||
const [recorded] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
|
||||
eq(heartbeatRunEvents.eventType, "native.remote_runner_recovery_failed"),
|
||||
)).orderBy(desc(heartbeatRunEvents.seq)).limit(1);
|
||||
const proof = asRecord(asRecord(refusal?.payload).remoteRunnerRecovery);
|
||||
return proof.stage === "process_verification" && proof.reason === "process_not_running" && proof.providerTurnIssued === false;
|
||||
eq(heartbeatRunEvents.eventType, INTERRUPTED_TURN_OUTCOME_UNKNOWN_EVENT))).limit(1);
|
||||
if (recorded) return;
|
||||
const payload = asRecord(lastTurn.payload);
|
||||
const turnId = asRecord(payload.prpEvent).turnId ?? payload.turnId;
|
||||
await appendHeartbeatRunEvent(db, { companyId: run.companyId, runId: run.id, agentId: run.agentId,
|
||||
eventType: INTERRUPTED_TURN_OUTCOME_UNKNOWN_EVENT, stream: "system", level: "warn",
|
||||
message: "The Runner stopped during a provider turn, so the turn's outcome is unknown. It is not replayed; a fresh session continues from the saved work.",
|
||||
payload: { turnId: typeof turnId === "string" ? turnId : null, lastTurnEvent: lastTurn.eventType, replayed: false,
|
||||
runnerExit: { stage: runnerExit.stage, reason: runnerExit.reason,
|
||||
...(typeof runnerExit.runnerLifecycle === "string" ? { runnerLifecycle: runnerExit.runnerLifecycle } : {}) } } });
|
||||
}
|
||||
|
||||
/** Automatic continuation is requested at most once per chain of runs. */
|
||||
export const RESTART_RETRY_KEY_PREFIX = "restart-interrupted-turn:";
|
||||
|
||||
type Outcome = { requested: true; requestId: string } | { requested: false; reason: string };
|
||||
const MAX_RETRY_CHAIN = 32;
|
||||
|
||||
async function chainUsedAutomaticRetry(db: Db, run: { companyId: string; id: string; retryOfRunId: string | null;
|
||||
contextSnapshot: Record<string, unknown> | null }) {
|
||||
const visited = new Set<string>();
|
||||
let current: typeof run | undefined = run;
|
||||
while (current && !visited.has(current.id) && visited.size < MAX_RETRY_CHAIN) {
|
||||
visited.add(current.id);
|
||||
const retryId = current.contextSnapshot?.taskRetryRequestId;
|
||||
if (typeof retryId === "string") {
|
||||
const [receipt] = await db.select({ key: agentWakeupRequests.idempotencyKey }).from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, run.companyId), sql`${agentWakeupRequests.id}::text = ${retryId}`));
|
||||
if (receipt?.key?.startsWith(`task-retry:${RESTART_RETRY_KEY_PREFIX}`)) return true;
|
||||
}
|
||||
if (!current.retryOfRunId) return false;
|
||||
[current] = await db.select({ companyId: heartbeatRuns.companyId, id: heartbeatRuns.id, retryOfRunId: heartbeatRuns.retryOfRunId,
|
||||
contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.id, current.retryOfRunId)));
|
||||
}
|
||||
return visited.size >= MAX_RETRY_CHAIN;
|
||||
}
|
||||
|
||||
type PrepareChatRetry = NonNullable<Parameters<typeof requestTaskRetry>[0]["prepareChatRetry"]>;
|
||||
|
||||
/** A connected conversation's Retry goes through the chat service, which the
|
||||
* app registers at startup. Without it, a connected task keeps its Retry. */
|
||||
let interruptedTurnChatRetry: PrepareChatRetry | undefined;
|
||||
export function registerInterruptedTurnChatRetry(prepare: PrepareChatRetry | undefined) {
|
||||
interruptedTurnChatRetry = prepare;
|
||||
}
|
||||
|
||||
/** The chat or comment message that woke the run is still on the task and was
|
||||
* not written by a run, so the run still owes it an answer. */
|
||||
async function wakeMessageStillOwed(db: Db, companyId: string, issueId: string, reason: string | null | undefined,
|
||||
context: Record<string, unknown>, wake: { payload: Record<string, unknown> | null }) {
|
||||
if (reason !== EXTERNAL_CHAT_MESSAGE_WAKE_REASON && !isUserCommentContinuationReason(reason)) return false;
|
||||
const commentId = typeof context.wakeCommentId === "string" ? context.wakeCommentId
|
||||
: typeof wake.payload?.commentId === "string" ? wake.payload.commentId : null;
|
||||
if (!commentId) return false;
|
||||
const [comment] = await db.select({ id: issueComments.id }).from(issueComments).where(and(
|
||||
eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId),
|
||||
sql`${issueComments.id}::text = ${commentId}`, isNull(issueComments.deletedAt), isNull(issueComments.createdByRunId)));
|
||||
return comment !== undefined;
|
||||
}
|
||||
|
||||
type Outcome ={ requested: true; requestId: string } | { requested: false; reason: string };
|
||||
|
||||
/**
|
||||
* Reattachment runs after a server restart and for a same-run retry of a remote
|
||||
* native run. When it fails because the original runner or sandbox is gone,
|
||||
* request the same Retry a user would click, once and idempotently per run,
|
||||
* under the requesting user's authority. Only when the run's user input was not
|
||||
* yet acted on, or its last provider turn is settled; an in-flight turn's
|
||||
* outcome is unknown, so it keeps the visible Retry. A system wake continues
|
||||
* this way only when the controller journal proved that no turn was ever
|
||||
* issued, under the run's responsible user. Admission keeps every gate,
|
||||
* including stop proof and saved-work recovery before the next turn.
|
||||
* yet acted on, its last provider turn is settled, or the Runner process is
|
||||
* proven gone; an in-flight turn's outcome is then unknown and recorded, and the
|
||||
* Retry's fresh session never replays it. Without that proof the in-flight turn
|
||||
* keeps the visible Retry. A system wake continues this way only when the
|
||||
* controller journal proved that no turn was ever issued, or when it carried
|
||||
* owed work (an automatic retry, a system assignment, or a chat message still
|
||||
* on the task) whose Runner is proven gone, under the run's responsible user. Admission keeps every gate, including stop proof and
|
||||
* saved-work recovery before the next turn.
|
||||
*/
|
||||
export async function requestRestartInterruptedTurnRetry(db: Db, claim: NativeRestartRecoveryClaim): Promise<Outcome> {
|
||||
if (claim.kind !== "reattach_remote_runner") return { requested: false, reason: "not_reattachment" };
|
||||
@@ -92,7 +164,9 @@ export async function requestInterruptedNativeTurnRetry(db: Db, runId: string):
|
||||
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
|
||||
inArray(heartbeatRunEvents.eventType, [...TURN_STARTED_EVENTS, ...TURN_SETTLED_EVENTS]),
|
||||
)).orderBy(desc(heartbeatRunEvents.seq)).limit(1);
|
||||
if (lastTurn && !isProvenTurnSettlement(lastTurn)) return { requested: false, reason: "provider_turn_unsettled" };
|
||||
const runnerExit = await provenRunnerExit(db, run);
|
||||
const unknownTurn = lastTurn && !isProvenTurnSettlement(lastTurn) ? lastTurn : null;
|
||||
if (unknownTurn && !runnerExit) return { requested: false, reason: "provider_turn_unsettled" };
|
||||
const [wake] = await db.select().from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId),
|
||||
eq(agentWakeupRequests.id, run.wakeupRequestId), eq(agentWakeupRequests.runId, run.id)));
|
||||
@@ -105,8 +179,16 @@ export async function requestInterruptedNativeTurnRetry(db: Db, runId: string):
|
||||
// ever issued: nothing the run did can be repeated, so the Retry runs once
|
||||
// under the run's responsible user. Missing events alone prove nothing,
|
||||
// because a turn can reach the provider before its events are stored.
|
||||
if (!wake || reason === "task_retry" || !run.responsibleUserId || !await hasProvenNoProviderTurn(db, run))
|
||||
// Work the wake still owes the task also continues once the Runner is
|
||||
// proven gone: an automatic retry of earlier owed work, a system
|
||||
// assignment (a routine's dispatch), or a chat message that is still on
|
||||
// the task. Monitors and other system wakes keep their policy.
|
||||
const owedRedelivery = runnerExit !== null && wake !== undefined && (run.retryOfRunId !== null
|
||||
|| reason === "issue_assigned" || await wakeMessageStillOwed(db, run.companyId, issueId, reason, context, wake));
|
||||
if (!wake || reason === "task_retry" || !run.responsibleUserId
|
||||
|| !(owedRedelivery || await hasProvenNoProviderTurn(db, run, runnerExit)))
|
||||
return { requested: false, reason: "not_user_request" };
|
||||
if (owedRedelivery && await chainUsedAutomaticRetry(db, run)) return { requested: false, reason: "automatic_retry_used" };
|
||||
actorId = run.responsibleUserId;
|
||||
} else if (reason === "task_retry") {
|
||||
// A Retry this hook already requested gets no second automatic attempt.
|
||||
@@ -124,16 +206,23 @@ export async function requestInterruptedNativeTurnRetry(db: Db, runId: string):
|
||||
eq(issueComments.authorUserId, userActorId), isNull(issueComments.deletedAt), isNull(issueComments.createdByRunId),
|
||||
)) : [];
|
||||
if (!comment && reason !== "issue_assigned") return { requested: false, reason: "message_unavailable" };
|
||||
} else if (reason === EXTERNAL_CHAT_MESSAGE_WAKE_REASON) {
|
||||
// A linked person's chat message is stored by the chat bridge, not always
|
||||
// as that person's own comment, so the message itself must still be there.
|
||||
if (!await wakeMessageStillOwed(db, run.companyId, issueId, reason, context, wake!))
|
||||
return { requested: false, reason: "message_unavailable" };
|
||||
} else return { requested: false, reason: "not_user_request" };
|
||||
if (!actorId) return { requested: false, reason: "not_user_request" };
|
||||
const [issue] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues)
|
||||
.where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId)));
|
||||
if (!issue || issue.assigneeAgentId !== run.agentId || ["done", "cancelled"].includes(issue.status))
|
||||
return { requested: false, reason: "task_changed" };
|
||||
if (unknownTurn && runnerExit) await recordUnknownTurnOutcome(db, run, unknownTurn, runnerExit);
|
||||
try {
|
||||
const receipt = await requestTaskRetry({ db, companyId: run.companyId, issueId, actorId,
|
||||
actorSource: actorId === "local-board" ? "local_implicit" : "session",
|
||||
idempotencyKey: `${RESTART_RETRY_KEY_PREFIX}${run.id}`, observedRunId: run.id, initiatedBy: "restart_recovery" });
|
||||
idempotencyKey: `${RESTART_RETRY_KEY_PREFIX}${run.id}`, observedRunId: run.id, initiatedBy: "restart_recovery",
|
||||
prepareChatRetry: interruptedTurnChatRetry });
|
||||
return receipt.accepted && receipt.requestId
|
||||
? { requested: true, requestId: receipt.requestId } : { requested: false, reason: "retry_stale" };
|
||||
} catch (error) {
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
serverRestartAttemptCount,
|
||||
serverRestartBudgetSpent,
|
||||
} from "../execution-recovery-attempt.js";
|
||||
import { isServerReplacementInterruption } from "../server-replacement-interruption.js";
|
||||
import { isReplacedPreparation, isServerReplacementInterruption } from "../server-replacement-interruption.js";
|
||||
import { WORKSPACE_GIT_SCAN_ERROR_CODES } from "../workspace-git-operation-scheduler.js";
|
||||
import { REMOTE_WORKSPACE_PREPARATION_TIMEOUT_CODE, REMOTE_WORKSPACE_RESTORE_FAILED_CODE } from "../remote-workspace-transport.js";
|
||||
import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "../reusable-sandbox-resume-error.js";
|
||||
@@ -163,7 +163,8 @@ export function isTransientWorkspacePreparationCode(code: string | null | undefi
|
||||
export const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS =
|
||||
BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length;
|
||||
|
||||
type LaneRun = Parameters<typeof executionFailureRetryCount>[0] & Partial<Parameters<typeof isServerReplacementInterruption>[0]>;
|
||||
type LaneRun = Parameters<typeof executionFailureRetryCount>[0] & Partial<Parameters<typeof isServerReplacementInterruption>[0]>
|
||||
& { controllerProcess?: unknown };
|
||||
|
||||
/**
|
||||
* A server restart or replacement ended this run, so its continuation uses the
|
||||
@@ -172,14 +173,25 @@ type LaneRun = Parameters<typeof executionFailureRetryCount>[0] & Partial<Parame
|
||||
* still has failure budget. Once real failures spent that budget, the
|
||||
* preparation lane refuses, but a restart is still not a failure, so the run
|
||||
* continues in the server-restart lane.
|
||||
*
|
||||
* The exception applies only when the preparation lane really takes the run.
|
||||
* scheduleBoundedRetryForRun passes its own verdict. Without one, only an
|
||||
* interrupted run qualifies. A legacy run that the orphan reaper ended as
|
||||
* `process_lost` while it was preparing carries the same bootstrap marker, but
|
||||
* the preparation lane refuses it: it continues in this lane when its row names
|
||||
* the replaced owner (isReplacedPreparation), and otherwise keeps the charged
|
||||
* transient-failure lane.
|
||||
*/
|
||||
export function usesServerRestartLane(run: LaneRun): boolean {
|
||||
export function usesServerRestartLane(run: LaneRun, preparationLaneTakesRun?: boolean): boolean {
|
||||
if (!run.status || !run.runtimeMode || !isServerReplacementInterruption({ runtimeMode: run.runtimeMode, status: run.status,
|
||||
errorCode: run.errorCode ?? null, resultJson: run.resultJson ?? null, controllerBootId: run.controllerBootId ?? null }))
|
||||
return false;
|
||||
const preparation = parseObject(run.resultJson?.executionRecovery);
|
||||
const interruptedPreparation = preparation.kind === "bootstrap" && preparation.providerWorkStarted === false;
|
||||
return !interruptedPreparation || executionFailureRetryCount(run) >= BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS;
|
||||
const bootstrap = preparation.kind === "bootstrap" && preparation.providerWorkStarted === false;
|
||||
if (!bootstrap || executionFailureRetryCount(run) >= BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS) return true;
|
||||
if (preparationLaneTakesRun ?? run.status === "interrupted") return false;
|
||||
return isReplacedPreparation({ runtimeMode: run.runtimeMode, status: run.status, errorCode: run.errorCode ?? null,
|
||||
resultJson: run.resultJson ?? null, controllerBootId: run.controllerBootId ?? null, controllerProcess: run.controllerProcess });
|
||||
}
|
||||
|
||||
export function failedRunRetryBudgetSpent(run: Parameters<typeof executionFailureRetryCount>[0]
|
||||
@@ -543,7 +555,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen
|
||||
// A run that a server restart or replacement ended did not fail: it
|
||||
// continues in the server-restart lane and never spends the failure budget.
|
||||
const retryReason = opts?.retryReason ??
|
||||
(usesServerRestartLane(run) ? SERVER_RESTART_RETRY_REASON
|
||||
(usesServerRestartLane(run, interruptedPreparation) ? SERVER_RESTART_RETRY_REASON
|
||||
: interruptedPreparation ? INTERRUPTED_PREPARATION_RETRY_REASON : BOUNDED_TRANSIENT_HEARTBEAT_RETRY_REASON);
|
||||
const wakeReason =
|
||||
opts?.wakeReason ?? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_WAKE_REASON;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { and, eq, ne, sql, type SQL } from "drizzle-orm";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, closeLivenessDb, companies, createDb, heartbeatRuns, livenessDb, subscribeDatabaseWork } from "@paperclipai/db";
|
||||
import { agents, closeLivenessDb, companies, controllerLeaseDb, createDb, heartbeatRuns, livenessDb, subscribeDatabaseWork } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
|
||||
import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js";
|
||||
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
|
||||
@@ -122,7 +122,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
DELIVERY_QUEUES.activeExecutionRecovery, DELIVERY_QUEUES.settledNativeProcesses,
|
||||
DELIVERY_QUEUES.strandedAgentStatus, DELIVERY_QUEUES.activeRunSilence];
|
||||
const stops = queues.map(queue => subscribeDatabaseWork(db, queue, event => { if (event === "settled") settled.push(queue); }));
|
||||
const pool = livenessDb(db), prior = pool.$client.options.debug;
|
||||
const pool = controllerLeaseDb(db), prior = pool.$client.options.debug;
|
||||
await pool.execute(sql`select 1`);
|
||||
pool.$client.options.debug = (_connection, query) => { queries.push(query); };
|
||||
const watch = watchLegacyControllerLease(db, run, new AbortController());
|
||||
@@ -224,19 +224,42 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
it("renews on one private pool per client that shutdown can end", async () => {
|
||||
const run = await seed();
|
||||
const owner = createDb(external ?? database.connectionString, { maxConnections: 6 });
|
||||
const pool = livenessDb(owner);
|
||||
const pool = controllerLeaseDb(owner);
|
||||
expect(pool).not.toBe(owner);
|
||||
expect(livenessDb(owner)).toBe(pool);
|
||||
expect(pool).not.toBe(livenessDb(owner));
|
||||
expect(controllerLeaseDb(owner)).toBe(pool);
|
||||
const watch = watchLegacyControllerLease(owner, run, new AbortController());
|
||||
try {
|
||||
await watch.assertOwned();
|
||||
const [{ name }] = await pool.execute<{ name: string }>(sql`select current_setting('application_name') as name`);
|
||||
expect(name).toBe("paperclip-controller-lease");
|
||||
expect(name).toBe("paperclip-legacy-controller-lease");
|
||||
} finally { watch.stop(); }
|
||||
await closeLivenessDb(owner, 1);
|
||||
await expect(controllerLeaseDb(owner).execute(sql`select 1`)).rejects.toThrow();
|
||||
await expect(livenessDb(owner).execute(sql`select 1`)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("renews without queueing behind native lease transactions that hold every liveness connection", async () => {
|
||||
const run = await seed();
|
||||
const owner = createDb(external ?? database.connectionString, { maxConnections: 6 });
|
||||
const nativeRenewals = Array.from({ length: 4 }, () =>
|
||||
livenessDb(owner).transaction(async tx => { await tx.execute(sql`select pg_sleep(5)`); }));
|
||||
const controller = new AbortController();
|
||||
const watch = watchLegacyControllerLease(owner, run, controller);
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
const startedAt = Date.now();
|
||||
await watch.assertOwned("dispatching");
|
||||
expect(Date.now() - startedAt).toBeLessThan(2_000);
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
} finally {
|
||||
watch.stop();
|
||||
await Promise.all(nativeRenewals);
|
||||
await closeLivenessDb(owner, 1);
|
||||
await owner.$client.end({ timeout: 1 });
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it("retries a renewal that times out waiting on the run row instead of losing the lease", async () => {
|
||||
const run = await seed();
|
||||
let lockTaken!: () => void, releaseLock!: () => void;
|
||||
@@ -265,7 +288,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
try {
|
||||
await watch.assertOwned();
|
||||
const terminated = await db.execute<{ pid: number }>(sql`select pg_terminate_backend(pid) as pid from pg_stat_activity
|
||||
where application_name = 'paperclip-controller-lease' and pid <> pg_backend_pid()`);
|
||||
where application_name = 'paperclip-legacy-controller-lease' and pid <> pg_backend_pid()`);
|
||||
expect(terminated.length).toBeGreaterThan(0);
|
||||
await expect(watch.assertOwned("dispatching")).resolves.toBeUndefined();
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
@@ -277,7 +300,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
it("renews fifteen concurrent controllers in one statement", async () => {
|
||||
const runs = await Promise.all(Array.from({ length: 15 }, () => seed()));
|
||||
const queries: string[] = [];
|
||||
const pool = livenessDb(db), prior = pool.$client.options.debug;
|
||||
const pool = controllerLeaseDb(db), prior = pool.$client.options.debug;
|
||||
await pool.execute(sql`select 1`);
|
||||
pool.$client.options.debug = (_connection, query) => { queries.push(query); };
|
||||
const controllers = runs.map(() => new AbortController());
|
||||
@@ -525,6 +548,20 @@ describe("legacy controller lease loss attribution", () => {
|
||||
} finally { watches.forEach(watch => watch.stop()); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("keeps a controller owned when every renewal waits thirty-five seconds for a connection before its statement runs", async () => {
|
||||
vi.useFakeTimers();
|
||||
const run = watchedRun(LEGACY_CONTROLLER_LEASE_MS);
|
||||
const pool = slowPoolDb([run.id], { connections: 1, transactionMs: 35_000 });
|
||||
const controller = new AbortController();
|
||||
const watch = watchLegacyControllerLease(pool.db, run, controller);
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(4 * LEGACY_CONTROLLER_LEASE_MS);
|
||||
expect(controller.signal.reason?.leaseLossTiming).toBeUndefined();
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
expect(pool.transactions()).toBeGreaterThanOrEqual(5);
|
||||
} finally { watch.stop(); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
const watchedRun = (leaseMs: number) => ({ id: randomUUID(), companyId: randomUUID(), runtimeMode: "legacy",
|
||||
controllerBootId: legacyControllerBootId, controllerLeaseExpiresAt: new Date(Date.now() + leaseMs) }) as WatchArgs[1];
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { notifyLiveRunRecovery } from "./live-run-recovery-notifications.js";
|
||||
import { and, eq, gt, lte, sql } from "drizzle-orm";
|
||||
import { heartbeatRuns, livenessDb, type Db } from "@paperclipai/db";
|
||||
import { controllerLeaseDb, heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import type { LegacyControllerLeaseLossCause, LegacyControllerLeaseLossTiming } from "./run-cancellation.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
@@ -110,19 +110,20 @@ function isStatementTimeout(error: unknown): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
type RenewalResult = { outcome: RenewalOutcome; issuedAt: number };
|
||||
type RenewalRequest = {
|
||||
target: RenewalTarget;
|
||||
statementTimeoutMs: number;
|
||||
resolve(outcome: RenewalOutcome): void;
|
||||
resolve(result: RenewalResult): void;
|
||||
reject(error: unknown): void;
|
||||
};
|
||||
type RenewalBatch = { pending: RenewalRequest[]; flushing: boolean };
|
||||
const renewalBatches = new WeakMap<object, RenewalBatch>();
|
||||
|
||||
function renewThroughBatch(db: Db, target: RenewalTarget, statementTimeoutMs: number): Promise<RenewalOutcome> {
|
||||
function renewThroughBatch(db: Db, target: RenewalTarget, statementTimeoutMs: number): Promise<RenewalResult> {
|
||||
let batch = renewalBatches.get(db);
|
||||
if (!batch) renewalBatches.set(db, batch = { pending: [], flushing: false });
|
||||
const outcome = new Promise<RenewalOutcome>((resolve, reject) => {
|
||||
const outcome = new Promise<RenewalResult>((resolve, reject) => {
|
||||
batch.pending.push({ target, statementTimeoutMs, resolve, reject });
|
||||
});
|
||||
if (!batch.flushing) void flushRenewals(db, batch);
|
||||
@@ -142,13 +143,15 @@ async function flushRenewals(db: Db, batch: RenewalBatch) {
|
||||
}
|
||||
try {
|
||||
const statementTimeoutMs = Math.min(...requests.map(request => request.statementTimeoutMs));
|
||||
const outcomes = await livenessDb(db).transaction(async (tx) => {
|
||||
let issuedAt = 0;
|
||||
const outcomes = await controllerLeaseDb(db).transaction(async (tx) => {
|
||||
issuedAt = Date.now();
|
||||
await tx.execute(sql`select set_config('statement_timeout', ${`${statementTimeoutMs}ms`}, true)`);
|
||||
return renewLegacyControllerLeasesInTransaction(tx as unknown as Db, [...targets.values()]);
|
||||
});
|
||||
for (const request of requests) {
|
||||
const sameCompany = targets.get(request.target.id)!.companyId === request.target.companyId;
|
||||
request.resolve(sameCompany ? outcomes.get(request.target.id) ?? "rejected" : "rejected");
|
||||
request.resolve({ outcome: sameCompany ? outcomes.get(request.target.id) ?? "rejected" : "rejected", issuedAt });
|
||||
}
|
||||
} catch (error) {
|
||||
for (const request of requests) request.reject(error);
|
||||
@@ -224,15 +227,48 @@ export function legacyControllerOwnerStamp(
|
||||
processStartedAt: controller.processStartedAt, processGroupId: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* The controller process that ran a run which is already terminal, also when
|
||||
* the orphan reaper revoked its lease: revocation swaps in a random boot id
|
||||
* but keeps the recorded process. Only for judging holds on finished runs,
|
||||
* never a live lease (legacyControllerOwnerStamp owns those).
|
||||
*/
|
||||
export function finishedLegacyControllerOwnerStamp(
|
||||
run: Pick<Run, "status" | "controllerBootId" | "controllerProcess">,
|
||||
): LocalOwnerStamp | null {
|
||||
const current = legacyControllerOwnerStamp(run);
|
||||
if (current || run.status === "running" || run.status === "queued") return current;
|
||||
const controller = readControllerProcess(run.controllerProcess);
|
||||
return controller ? legacyControllerOwnerStamp({ controllerBootId: controller.bootId, controllerProcess: run.controllerProcess })
|
||||
: null;
|
||||
}
|
||||
|
||||
/** The shared prover's verdict on the recorded legacy controller, or null when
|
||||
* the row names none (a native run, a revoked lease, or an older row). */
|
||||
export async function proveLegacyController(
|
||||
run: Pick<Run, "runtimeMode" | "controllerBootId" | "controllerProcess">,
|
||||
): Promise<OwnerProof | null> {
|
||||
if (run.runtimeMode === "native") return null;
|
||||
const stamp = legacyControllerOwnerStamp(run);
|
||||
return stamp === null ? null : proveOwnerGone(stamp);
|
||||
}
|
||||
|
||||
/** True only when the shared prover proves the recorded legacy controller gone. */
|
||||
export async function legacyControllerProvenGone(
|
||||
run: Pick<Run, "runtimeMode" | "controllerBootId" | "controllerProcess">,
|
||||
): Promise<boolean> {
|
||||
if (run.runtimeMode === "native") return false;
|
||||
const stamp = legacyControllerOwnerStamp(run);
|
||||
return stamp !== null && (await proveOwnerGone(stamp)).verdict === "gone";
|
||||
return (await proveLegacyController(run))?.verdict === "gone";
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a run whose lease lapsed stays with its owner while the owner's
|
||||
* server process is proven alive. The owner settles the run itself: its local
|
||||
* deadline stops the adapter and records `controller_lease_lost`. A run still
|
||||
* running after this grace has an owner that no longer drives it, and the
|
||||
* orphan reaper recovers it.
|
||||
*/
|
||||
export const LEGACY_LIVE_OWNER_SETTLE_GRACE_MS = 5 * 60_000;
|
||||
|
||||
/**
|
||||
* The boot id of a run's legacy controller whose lease has not expired yet but
|
||||
* whose recorded process is proven gone, or null. A drained server terminalizes
|
||||
@@ -351,13 +387,13 @@ export function watchLegacyControllerLease(
|
||||
// deadline is measured from that attempt rather than the first one.
|
||||
// Failed attempts are retried until the deadline aborts the controller:
|
||||
// the UPDATE is idempotent and still requires this controller's boot ID.
|
||||
let attemptStartedAt = startedAt;
|
||||
let renewedFrom = startedAt;
|
||||
const renew = async () => {
|
||||
for (;;) {
|
||||
attemptStartedAt = Date.now();
|
||||
try {
|
||||
const outcome = await renewThroughBatch(db, { id: run.id, companyId: run.companyId, stage },
|
||||
const { outcome, issuedAt } = await renewThroughBatch(db, { id: run.id, companyId: run.companyId, stage },
|
||||
renewalStatementTimeoutMs);
|
||||
renewedFrom = issuedAt;
|
||||
if (outcome !== "busy") return outcome === "renewed";
|
||||
await new Promise((resolve) => setTimeout(resolve, LEGACY_CONTROLLER_RENEWAL_BUSY_RETRY_DELAY_MS));
|
||||
if (stopped || controller.signal.aborted) return false;
|
||||
@@ -389,7 +425,7 @@ export function watchLegacyControllerLease(
|
||||
lastRenewedAt = Date.now();
|
||||
renewalCount += 1;
|
||||
renewalFailed = false;
|
||||
armDeadline(Math.max(0, LEGACY_CONTROLLER_LEASE_MS - (Date.now() - attemptStartedAt)));
|
||||
armDeadline(Math.max(0, LEGACY_CONTROLLER_LEASE_MS - (Date.now() - renewedFrom)));
|
||||
}
|
||||
};
|
||||
const timer = setInterval(() => {
|
||||
|
||||
@@ -26,6 +26,7 @@ import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
|
||||
import { issueRecoveryActionService } from "./issue-recovery-actions.js";
|
||||
import { parseIssueExecutionState } from "./issue-execution-policy.js";
|
||||
import { executionFailureRetryCount } from "./execution-recovery-attempt.js";
|
||||
import { isReplacedPreparation } from "./server-replacement-interruption.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { isSupersededConversationRun } from "./agent-conversations.js";
|
||||
import { issueService } from "./issues.js";
|
||||
@@ -56,7 +57,8 @@ export const legacyReconciliationRunFields = {
|
||||
|
||||
/** Error families describe availability, not whether earlier actions happened. */
|
||||
export function legacyExecutionNeedsReconciliation(
|
||||
run: Pick<Run, "runtimeMode" | "status" | "errorCode" | "resultJson"> & Partial<Pick<Run, "scheduledRetryAttempt" | "scheduledRetryReason" | "contextSnapshot">>,
|
||||
run: Pick<Run, "runtimeMode" | "status" | "errorCode" | "resultJson">
|
||||
& Partial<Pick<Run, "scheduledRetryAttempt" | "scheduledRetryReason" | "contextSnapshot" | "controllerBootId" | "controllerProcess">>,
|
||||
): boolean {
|
||||
if (
|
||||
run.runtimeMode === "native" ||
|
||||
@@ -88,6 +90,10 @@ export function legacyExecutionNeedsReconciliation(
|
||||
|| run.errorCode === RUNNER_REVISION_MISMATCH_CODE || run.errorCode === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE
|
||||
|| run.errorCode === REPOSITORY_CATALOG_UNAVAILABLE_CODE) &&
|
||||
evidence?.kind === "bootstrap" && evidence.providerWorkStarted === false) return false;
|
||||
// A server restart or replacement stopped this setup before dispatch: no
|
||||
// provider action happened, so there is nothing to reconcile. Its
|
||||
// continuation is bounded by the server-restart lane, not the failure count.
|
||||
if (isReplacedPreparation({ ...run, controllerBootId: run.controllerBootId ?? null })) return false;
|
||||
if (executionFailureRetryCount(run) >= 2) return true;
|
||||
return !(
|
||||
evidence?.kind === "bootstrap" && evidence.providerWorkStarted === false
|
||||
@@ -346,7 +352,10 @@ export async function settleInterruptedNativeBootstrap(
|
||||
const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, input.run.id), eq(heartbeatRuns.companyId, input.run.companyId))).for("update");
|
||||
if (!task || !run || !isInterruptedNativePreparationCandidate(run) ||
|
||||
run.contextSnapshot?.issueId !== task.id ||
|
||||
executionFailureRetryCount(run) >= 2) return null;
|
||||
// A spent failure budget keeps the hold, except for a preparation that
|
||||
// a server replacement stopped: it never failed, and its continuation
|
||||
// uses the bounded server-restart lane (holds saved by older releases).
|
||||
executionFailureRetryCount(run) >= 2 && !isReplacedPreparation(run)) return null;
|
||||
if (hasWorkspaceRestoreFailure(run.resultJson) && !await hasVerifiedWorkspaceRepair(tx as unknown as Db, run)) return null;
|
||||
const [native] = await tx.select({ id: nativeRunFinalizations.runId }).from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id)).limit(1);
|
||||
const [lease] = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
||||
|
||||
@@ -10637,7 +10637,8 @@ async function executePaperclipNativeSessionAttempt(
|
||||
},
|
||||
});
|
||||
nativeRunRecoveryFlushers.set(traceRunId, flushRecovery);
|
||||
await emitStartupReuse(input.onEvent, "environment", environmentStartupReuse(input.runnerExecutionTarget));
|
||||
await emitStartupReuse(input.onEvent, "environment", environmentStartupReuse(input.runnerExecutionTarget,
|
||||
{ reattachedRetainedLease: input.restartRecovery?.kind === "reattach_remote_runner" }));
|
||||
if (!input.runnerExecutionTarget || input.runnerExecutionTarget.kind === "local") {
|
||||
await emitStartupReuse(input.onEvent, "workspace", { state: "not_applicable", reason: "not_applicable" });
|
||||
}
|
||||
|
||||
@@ -1221,7 +1221,7 @@ export class PaperclipRunnerToolAuthority {
|
||||
}
|
||||
// A new call that would be rejected before dispatch must not reserve a
|
||||
// pending receipt; that would make its callId report an unknown outcome.
|
||||
assertRunnerApiDispatchable(operation, input, Object.keys(record(value)));
|
||||
assertRunnerApiDispatchable(operation, input, record(value));
|
||||
if (Object.keys(receipts).length >= 512) throw badRequest("Run API mutation limit reached");
|
||||
receipts[key] = { digest, operationId: operation.operationId, state: "pending" };
|
||||
await tx.update(heartbeatRuns).set({ resultJson: { ...resultJson, apiToolReceipts: receipts } }).where(eq(heartbeatRuns.id, this.binding.runId));
|
||||
|
||||
@@ -88,7 +88,19 @@ export function validateRunnerApiCall(value: unknown, context: RunnerApiContext)
|
||||
* older accepted call with validateRunnerApiCall, so these rules stay out of it.
|
||||
* Callers that reserve a mutation receipt must run this before the reservation.
|
||||
*/
|
||||
export function assertRunnerApiDispatchable(operation: RunnerApiOperation, input: RunnerApiCall, receivedKeys: readonly string[]): void {
|
||||
export function assertRunnerApiDispatchable(operation: RunnerApiOperation, input: RunnerApiCall, received: Readonly<Record<string, unknown>>): void {
|
||||
assertBodyPresent(operation, input, Object.keys(received));
|
||||
if (operation.method !== "GET" && setsResponseWindow(received.responseText)) {
|
||||
throw badRequest(`This request was not sent: responseText applies only to GET reads and never carries request fields. Resend ${operation.operationId} once without responseText, with its request fields in body${requestFieldHint(operation)}.`);
|
||||
}
|
||||
}
|
||||
|
||||
function setsResponseWindow(value: unknown): boolean {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
return Object.entries(value).some(([key, setting]) => setting !== undefined && !(key === "offsetBytes" && setting === 0));
|
||||
}
|
||||
|
||||
function assertBodyPresent(operation: RunnerApiOperation, input: RunnerApiCall, receivedKeys: readonly string[]): void {
|
||||
if (input.body !== undefined || input.files?.length || !operation.requestBody?.required) return;
|
||||
// A PATCH without a body succeeds as a no-op that reads like a completed
|
||||
// update. A POST or PUT without a body whose schema names required fields
|
||||
@@ -191,7 +203,7 @@ export function runnerApiPagination(headers: Headers) {
|
||||
export async function executeRunnerApi(input: RunnerApiCall, context: RunnerApiContext, io: RunnerApiIo) {
|
||||
const inlineBytes = RUNNER_API_INLINE_BYTES;
|
||||
const { operation, input: validated } = validateRunnerApiCall(input, context);
|
||||
assertRunnerApiDispatchable(operation, validated, Object.keys(input));
|
||||
assertRunnerApiDispatchable(operation, validated, input);
|
||||
input = validated;
|
||||
const sensitiveResponse = runnerApiSensitiveResponse(operation.method, operation.path);
|
||||
const url = runnerApiUrl(operation, input, context, io.apiUrl);
|
||||
|
||||
@@ -811,16 +811,38 @@ describe("runner API request boundary", () => {
|
||||
await expect(executeRunnerApi({ operationId: createProject, body: { name: "Once" }, responseText: { offsetBytes: 4 } }, context, io(request))).rejects.toThrow("This request was not sent");
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{}, { limitBytes: 8192 }, { offsetBytes: 0, limitBytes: 4096 }])("sends a mutation once when responseText asks only for the first window: %j", async responseText => {
|
||||
it.each([{ limitBytes: 8192 }, { offsetBytes: 0, limitBytes: 4096 }])("refuses a new write whose responseText sets a window before sending: %j", async responseText => {
|
||||
const request = vi.fn<typeof fetch>(async () => Response.json({ id: "company-a", name: "Acorn Studio" }));
|
||||
const result = await executeRunnerApi({ operationId: "PATCH /api/companies/{companyId}", pathParams: { companyId: "company-a" }, body: { name: "Acorn Studio" }, responseText }, context, io(request));
|
||||
const call = { operationId: "PATCH /api/companies/{companyId}", pathParams: { companyId: "company-a" }, body: { name: "Acorn Studio" }, responseText };
|
||||
const error = await executeRunnerApi(call, context, io(request)).then(() => null, (caught: Error) => caught);
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(error?.message).toContain("This request was not sent: responseText applies only to GET reads and never carries request fields.");
|
||||
expect(error?.message).toContain("Resend PATCH /api/companies/{companyId} once without responseText, with its request fields in body");
|
||||
expect(validateRunnerApiCall(call, context).input).not.toHaveProperty("responseText");
|
||||
});
|
||||
it.each([
|
||||
{ responseText: {} },
|
||||
{ responseText: { offsetBytes: 0 } },
|
||||
{ saveResponse: false },
|
||||
{ responseText: {}, saveResponse: false },
|
||||
])("sends a write once when its read options are empty or default: %j", async options => {
|
||||
const request = vi.fn<typeof fetch>(async () => Response.json({ ok: true }));
|
||||
const result = await executeRunnerApi({ operationId: "POST /api/issues/{id}/inbox-archive", pathParams: { id: "issue-a" }, body: {}, ...options }, context, io(request));
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
const [, init] = request.mock.calls[0]!;
|
||||
expect(init?.method).toBe("PATCH");
|
||||
expect(JSON.parse(String(init?.body))).toEqual({ name: "Acorn Studio" });
|
||||
expect(result).toMatchObject({ ok: true, status: 200, data: { name: "Acorn Studio" } });
|
||||
const [url, init] = request.mock.calls[0]!;
|
||||
expect(String(url)).toMatch(/\/api\/issues\/issue-a\/inbox-archive$/);
|
||||
expect(init?.method).toBe("POST");
|
||||
expect(JSON.parse(String(init?.body))).toEqual({});
|
||||
expect(result).toMatchObject({ ok: true, status: 200 });
|
||||
expect(result).not.toHaveProperty("responseText");
|
||||
});
|
||||
it("still sends the same write once without responseText", async () => {
|
||||
const request = vi.fn<typeof fetch>(async () => Response.json({ id: "company-a", name: "Acorn Studio" }));
|
||||
const result = await executeRunnerApi({ operationId: "PATCH /api/companies/{companyId}", pathParams: { companyId: "company-a" }, body: { name: "Acorn Studio" } }, context, io(request));
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.parse(String(request.mock.calls[0]![1]?.body))).toEqual({ name: "Acorn Studio" });
|
||||
expect(result).toMatchObject({ ok: true, status: 200, data: { name: "Acorn Studio" } });
|
||||
});
|
||||
it("rejects a PATCH with no body instead of sending a no-op update", async () => {
|
||||
const request = vi.fn<typeof fetch>();
|
||||
const call = { operationId: "PATCH /api/companies/{companyId}", pathParams: { companyId: "company-a" }, query: {}, responseText: { limitBytes: 8192 } };
|
||||
|
||||
@@ -48,7 +48,7 @@ import { legacyShutdownSettlementOwner, settleLegacyShutdownSettlementFence } fr
|
||||
import { nativeControllerOwnerStamp, runProcessOwnerStamp } from "../native-runtime/native-owner-stamps.js";
|
||||
import { settleIssueLock } from "./issue-lock-settlement.js";
|
||||
import { settleAgentLifecycleLease } from "./agent-lifecycle-lease-settlement.js";
|
||||
import { legacyControllerOwnerStamp, settleLegacyControllerLease } from "../legacy-controller-lease.js";
|
||||
import { finishedLegacyControllerOwnerStamp, legacyControllerOwnerStamp, settleLegacyControllerLease } from "../legacy-controller-lease.js";
|
||||
import { heldInterruptedPreparationWhere, settleHeldInterruptedPreparation } from "../interrupted-preparation-hold-settlement.js";
|
||||
import { completedTurnCleanupHoldWhere, settleCompletedTurnCleanupHolds } from "../native-runtime/completed-turn-cleanup-hold-settlement.js";
|
||||
import {
|
||||
@@ -1065,7 +1065,8 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [
|
||||
}, versionLock(heartbeatRuns)),
|
||||
{
|
||||
// A preparation a shutdown interrupted, held before its no-provider-work
|
||||
// proof could exist. Its owner is the recorded controller process: the
|
||||
// proof could exist, or one the orphan reaper ended as process_lost. Its
|
||||
// owner is the recorded controller process: the
|
||||
// shared prover must prove it gone (a missing stamp, or one from another
|
||||
// host or PID space, is unprovable and stays held). The settle re-checks
|
||||
// the durable proof and replays the preparation exactly once.
|
||||
@@ -1073,7 +1074,9 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [
|
||||
// in a pass is released before this kind lists in that same pass.
|
||||
...runKind("legacy_interrupted_preparation_hold", "Interrupted preparation held for replay", "ownership",
|
||||
heldInterruptedPreparationWhere(), row => {
|
||||
const stamp = legacyControllerOwnerStamp(row);
|
||||
// A preparation the orphan reaper ended has a revoked lease: its owner
|
||||
// is still the recorded controller process.
|
||||
const stamp = finishedLegacyControllerOwnerStamp(row);
|
||||
return stamp ? { kind: "process", stamp } : { kind: "none" };
|
||||
}),
|
||||
settle: settleHeldInterruptedPreparation,
|
||||
|
||||
@@ -932,6 +932,7 @@ export function recoveryService(
|
||||
enqueueWakeup: RecoveryWakeup;
|
||||
scheduleRecoveryRetry?: (
|
||||
runId: string,
|
||||
outcome?: { retryExhausted?: boolean },
|
||||
) => Promise<typeof heartbeatRuns.$inferSelect | null>;
|
||||
/** Settle retained explicit retry claims through the queue-first release policy. */
|
||||
settleExplicitContinuationRetry?: (run: typeof heartbeatRuns.$inferSelect) => Promise<void>;
|
||||
@@ -2042,14 +2043,15 @@ export function recoveryService(
|
||||
return null;
|
||||
}
|
||||
if (deps.scheduleRecoveryRetry) {
|
||||
const retry = await deps.scheduleRecoveryRetry(predecessor.id);
|
||||
const scheduling: { retryExhausted?: boolean } = {};
|
||||
const retry = await deps.scheduleRecoveryRetry(predecessor.id, scheduling);
|
||||
if (retry) return retry;
|
||||
// A spent budget is the one "no retry" the sweeper must not wait
|
||||
// out: nothing else will ever queue a successor for this run, so
|
||||
// it reports the exhaustion instead of leaving the issue with no
|
||||
// live path (2026-09-25: three deploy restarts in a row spent the
|
||||
// budget and the issue sat in_progress with no run, unescalated).
|
||||
if (input.outcome && deps.transientRetryBudgetSpent?.(predecessor)) {
|
||||
if (input.outcome && (scheduling.retryExhausted || deps.transientRetryBudgetSpent?.(predecessor))) {
|
||||
input.outcome.retryExhausted = true;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
||||
import { agentWakeupRequests, chatConversations, chatEndpoints, heartbeatRunEvents, heartbeatRuns, issueComments,
|
||||
toolApplications, toolConnections } from "@paperclipai/db";
|
||||
import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
|
||||
import { heartbeatService } from "./heartbeat.js";
|
||||
import { registerInterruptedTurnChatRetry, requestInterruptedNativeTurnRetry, requestRestartInterruptedTurnRetry }
|
||||
from "./heartbeat/restart-interrupted-turn.js";
|
||||
import { readSystemRecovery } from "./system-recovery-state.js";
|
||||
import { reconcileRetainedWorkspaces } from "./workspace-recovery.js";
|
||||
import { useWorkspaceRecoveryFixture, action, db, run, seed } from "./__tests__/workspace-recovery-fixture.js";
|
||||
|
||||
const targets = vi.hoisted(() => new Map<string, AdapterSandboxExecutionTarget>());
|
||||
vi.mock("./environment-execution-target.js", async importOriginal => {
|
||||
const actual = await importOriginal<typeof import("./environment-execution-target.js")>();
|
||||
return { ...actual, resolveEnvironmentExecutionTarget: async (input: Parameters<typeof actual.resolveEnvironmentExecutionTarget>[0]) =>
|
||||
(input.leaseId ? targets.get(input.leaseId) : undefined) ?? actual.resolveEnvironmentExecutionTarget(input) };
|
||||
});
|
||||
|
||||
const TURN_ID = "01a1cdcb-8c83-7221-b602-d80d515d1616";
|
||||
|
||||
/** The refusal the previous release recorded on staging, byte for byte in shape. */
|
||||
const stagingRefusal = (reason: "process_not_running" | "process_identity_changed" = "process_not_running") => ({
|
||||
remoteRunnerRecovery: { stage: "process_verification", reason,
|
||||
...(reason === "process_not_running" ? { runnerSettled: true, runnerLifecycle: "ready",
|
||||
runnerDiagnostics: ["WebSocket peer closed the connection"], runnerExitEvidence: "== runnerd.process-stderr.log" } : {}) },
|
||||
});
|
||||
|
||||
describe("a remote Runner that died in the middle of a provider turn", () => {
|
||||
useWorkspaceRecoveryFixture(targets);
|
||||
|
||||
async function runnerLostMidTurn(input: { wake: "user" | "user_retry" | "system_retry" | "system_monitor"
|
||||
| "system_assignment" | "system_chat" | "user_chat";
|
||||
refusal?: "process_not_running" | "process_identity_changed" | null;
|
||||
chatMessage?: "present" | "deleted" | "written_by_run";
|
||||
events?: string[]; refusalPayload?: Record<string, unknown> }) {
|
||||
const f = await seed("native");
|
||||
const original = await run(f.runId);
|
||||
const system = input.wake !== "user" && input.wake !== "user_retry" && input.wake !== "user_chat";
|
||||
const chat = input.wake === "system_chat" || input.wake === "user_chat";
|
||||
const reason = input.wake === "user" || input.wake === "system_assignment" ? "issue_assigned"
|
||||
: input.wake === "user_retry" ? "task_retry"
|
||||
: chat ? "External chat message received"
|
||||
: input.wake === "system_retry" ? "transient_failure_retry" : "issue_monitor_due";
|
||||
// The chat bridge stores the inbound message as a task comment before it wakes the agent.
|
||||
const [chatComment] = chat ? await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId,
|
||||
body: "Can you also check the release notes?", authorType: "system",
|
||||
...(input.chatMessage === "deleted" ? { deletedAt: new Date() } : {}),
|
||||
...(input.chatMessage === "written_by_run" ? { createdByRunId: f.runId } : {}) }).returning() : [];
|
||||
const [retryIntent] = input.wake === "user_retry" ? await db.insert(agentWakeupRequests).values({ companyId: f.companyId,
|
||||
agentId: original.agentId, source: "on_demand", triggerDetail: "manual", reason: "task_retry", status: "completed",
|
||||
idempotencyKey: `task-retry:${randomUUID()}`, requestedByActorType: "user", requestedByActorId: "local-board",
|
||||
payload: { issueId: f.issueId } }).returning() : [];
|
||||
const [predecessor] = input.wake === "system_retry" ? await db.insert(heartbeatRuns).values({ companyId: f.companyId,
|
||||
agentId: original.agentId, issueId: f.issueId, status: "failed", createdAt: new Date(Date.now() - 60 * 60_000),
|
||||
finishedAt: new Date(Date.now() - 50 * 60_000),
|
||||
errorCode: "environment_provider_unavailable", contextSnapshot: { issueId: f.issueId, wakeReason: "issue_assigned" } }).returning() : [];
|
||||
const [wake] = await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: original.agentId,
|
||||
source: system && input.wake !== "system_assignment" && !chat ? "automation" : "assignment", triggerDetail: "system",
|
||||
reason, status: "failed", runId: f.runId,
|
||||
requestedByActorType: system ? "system" : "user", requestedByActorId: system ? null : "local-board",
|
||||
finishedAt: new Date(), payload: { issueId: f.issueId, ...(chatComment ? { commentId: chatComment.id } : {}) } }).returning();
|
||||
await db.update(heartbeatRuns).set({ errorCode: "native_continuation_requires_reconciliation",
|
||||
error: "runner_remote_process_identity_unavailable", wakeupRequestId: wake.id, responsibleUserId: "local-board",
|
||||
retryOfRunId: predecessor?.id ?? null, startedAt: new Date(Date.now() - 45 * 60_000),
|
||||
contextSnapshot: { issueId: f.issueId, wakeReason: reason,
|
||||
...(chatComment ? { wakeCommentId: chatComment.id, commentId: chatComment.id, wakeSource: "assignment" } : {}),
|
||||
...(retryIntent ? { taskRetryRequestId: retryIntent.id,
|
||||
forceFreshSession: true } : {}), ...(predecessor ? { retryOfRunId: predecessor.id,
|
||||
retryReason: "transient_failure", scheduledRetryAttempt: 1 } : {}) },
|
||||
}).where(eq(heartbeatRuns.id, f.runId));
|
||||
for (const eventType of input.events ?? ["turn.submitted", "turn.started", "tool.execution.started", "turn.accepted", "tool.execution.completed"])
|
||||
await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId: f.runId, agentId: original.agentId,
|
||||
eventType, stream: "system", level: "info", message: eventType,
|
||||
payload: { prpEvent: { eventType, turnId: TURN_ID, payload: {} } } });
|
||||
if (input.refusal !== null) await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId: f.runId,
|
||||
agentId: original.agentId, eventType: "native.remote_runner_recovery_failed", stream: "system", level: "error",
|
||||
message: "Could not verify the existing remote runner.", payload: input.refusalPayload ?? stagingRefusal(input.refusal) });
|
||||
const claim = { kind: "reattach_remote_runner" as const, runId: f.runId, leaseOwner: `boot:2:${randomUUID()}`,
|
||||
controllerGeneration: 2, providerAttempt: 1, restartKind: "hard" as const, recoveryRequestId: null,
|
||||
remote: { providerLeaseId: f.providerLeaseId, remoteCwd: f.remote } };
|
||||
const service = heartbeatService(db, { environmentRuntime: f.environmentRuntime });
|
||||
// Keep the agent's only slot busy so a successor stays observable as queued.
|
||||
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: original.agentId, status: "running" });
|
||||
return { ...f, agentId: original.agentId, claim, service, retryIntent };
|
||||
}
|
||||
const queued = async (companyId: string) => db.select().from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.status, "queued")));
|
||||
const unknownOutcomeEvents = async (runId: string) => db.select().from(heartbeatRunEvents)
|
||||
.where(and(eq(heartbeatRunEvents.runId, runId), eq(heartbeatRunEvents.eventType, "native.interrupted_turn_outcome_unknown")));
|
||||
|
||||
// Staging: a deploy detached the controller, the restart's reattachment then
|
||||
// found the Runner process gone with a turn in flight. The previous release
|
||||
// recorded `process_not_running` and the task waited for a person.
|
||||
it.each([
|
||||
{ title: "a user's assignment", wake: "user" as const, viaClaim: true },
|
||||
{ title: "an automatic retry of the assignment (the staging shape)", wake: "system_retry" as const, viaClaim: true },
|
||||
{ title: "a same-run retry of a user's assignment", wake: "user" as const, viaClaim: false },
|
||||
// Staging after the upgrade fix: a routine's system assignment and an
|
||||
// external chat message, neither a retry, stayed blocked for a person.
|
||||
{ title: "a routine's system assignment", wake: "system_assignment" as const, viaClaim: true },
|
||||
{ title: "an external chat message from an unlinked sender", wake: "system_chat" as const, viaClaim: true },
|
||||
{ title: "an external chat message from a linked person", wake: "user_chat" as const, viaClaim: false },
|
||||
])("continues $title once in a fresh session and records that the turn's outcome is unknown", async ({ wake, viaClaim }) => {
|
||||
const f = await runnerLostMidTurn({ wake });
|
||||
const request = () => viaClaim ? requestRestartInterruptedTurnRetry(db, f.claim) : requestInterruptedNativeTurnRetry(db, f.runId);
|
||||
expect(await request()).toEqual({ requested: true, requestId: expect.any(String) });
|
||||
expect(await request()).toMatchObject({ requested: true });
|
||||
const recorded = await unknownOutcomeEvents(f.runId);
|
||||
expect(recorded).toHaveLength(1);
|
||||
expect(recorded[0]).toMatchObject({ level: "warn", payload: { turnId: TURN_ID, replayed: false,
|
||||
runnerExit: { stage: "process_verification", reason: "process_not_running", runnerLifecycle: "ready" } } });
|
||||
await vi.waitFor(async () => {
|
||||
await Promise.all(await reconcileRetainedWorkspaces(db, f.environmentRuntime, current => f.service.resumeRemoteStopComments(current)) ?? []);
|
||||
expect(readSystemRecovery((await action(f.actionId)).evidence)?.state).toBe("complete");
|
||||
}, { timeout: 10_000, interval: 10 });
|
||||
expect(await readFile(path.join(f.host, "saved.txt"), "utf8")).toBe("finished work\n");
|
||||
await vi.waitFor(async () => expect(await queued(f.companyId)).toHaveLength(1), { timeout: 10_000, interval: 50 });
|
||||
const [successor] = await queued(f.companyId);
|
||||
expect(successor.contextSnapshot).toMatchObject({ previousRunId: f.runId, wakeReason: "task_retry", forceFreshSession: true });
|
||||
const retries = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId),
|
||||
eq(agentWakeupRequests.reason, "task_retry")));
|
||||
expect(retries.filter(retry => retry.idempotencyKey?.startsWith("task-retry:"))).toEqual([expect.objectContaining({
|
||||
idempotencyKey: `task-retry:restart-interrupted-turn:${f.runId}`, requestedByActorType: "user", requestedByActorId: "local-board" })]);
|
||||
}, 30_000);
|
||||
|
||||
it("continues a person's Retry whose turn start timed out and whose Runner was gone at the same-run reattachment", async () => {
|
||||
const f = await runnerLostMidTurn({ wake: "user_retry", events: ["turn.submitted"], refusalPayload: {
|
||||
remoteRunnerRecovery: { stage: "process_verification", reason: "process_not_running", runnerSettled: false,
|
||||
runnerLifecycle: "ready", runnerDiagnostics: ["WebSocket peer closed the connection"], providerTurnIssued: false,
|
||||
runnerExitEvidence: "== runnerd.process-stderr.log" } } });
|
||||
expect(await requestInterruptedNativeTurnRetry(db, f.runId)).toEqual({ requested: true, requestId: expect.any(String) });
|
||||
expect(await requestInterruptedNativeTurnRetry(db, f.runId)).toMatchObject({ requested: true });
|
||||
expect(await unknownOutcomeEvents(f.runId)).toEqual([expect.objectContaining({ payload: expect.objectContaining({
|
||||
lastTurnEvent: "turn.submitted", replayed: false }) })]);
|
||||
await vi.waitFor(async () => {
|
||||
await Promise.all(await reconcileRetainedWorkspaces(db, f.environmentRuntime, current => f.service.resumeRemoteStopComments(current)) ?? []);
|
||||
expect(readSystemRecovery((await action(f.actionId)).evidence)?.state).toBe("complete");
|
||||
}, { timeout: 10_000, interval: 10 });
|
||||
await vi.waitFor(async () => expect(await queued(f.companyId)).toHaveLength(1), { timeout: 10_000, interval: 50 });
|
||||
const [successor] = await queued(f.companyId);
|
||||
expect(successor.contextSnapshot).toMatchObject({ previousRunId: f.runId, wakeReason: "task_retry", forceFreshSession: true });
|
||||
const retries = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId),
|
||||
eq(agentWakeupRequests.reason, "task_retry")));
|
||||
expect(retries.filter(retry => retry.id !== f.retryIntent!.id && retry.idempotencyKey?.startsWith("task-retry:"))).toEqual([
|
||||
expect.objectContaining({ idempotencyKey: `task-retry:restart-interrupted-turn:${f.runId}`, requestedByActorId: "local-board" })]);
|
||||
}, 30_000);
|
||||
|
||||
it.each([
|
||||
{ title: "inherits the hook's Retry intent", inherit: true },
|
||||
{ title: "reaches the hook's Retry run through its retry chain", inherit: false },
|
||||
])("gives no second automatic Retry to a system retry that $title and then lost its Runner mid-turn", async ({ inherit }) => {
|
||||
const f = await runnerLostMidTurn({ wake: "system_retry" });
|
||||
const current = await run(f.runId);
|
||||
const [hookIntent] = await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId,
|
||||
source: "on_demand", triggerDetail: "manual", reason: "task_retry", status: "completed",
|
||||
idempotencyKey: `task-retry:restart-interrupted-turn:${randomUUID()}`, requestedByActorType: "user",
|
||||
requestedByActorId: "local-board", payload: { issueId: f.issueId } }).returning();
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { ...current.contextSnapshot, wakeReason: "task_retry",
|
||||
taskRetryRequestId: hookIntent.id } }).where(eq(heartbeatRuns.id, current.retryOfRunId!));
|
||||
if (inherit) await db.update(heartbeatRuns).set({ contextSnapshot: { ...current.contextSnapshot,
|
||||
taskRetryRequestId: hookIntent.id } }).where(eq(heartbeatRuns.id, f.runId));
|
||||
expect(await requestRestartInterruptedTurnRetry(db, f.claim)).toEqual({ requested: false, reason: "automatic_retry_used" });
|
||||
expect(await unknownOutcomeEvents(f.runId)).toHaveLength(0);
|
||||
expect((await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId),
|
||||
eq(agentWakeupRequests.reason, "task_retry")))).filter(retry => retry.id !== hookIntent.id)).toHaveLength(0);
|
||||
}, 30_000);
|
||||
|
||||
// The staging chat task runs through a connected Slack conversation, whose
|
||||
// endpoint restricts external execution: its Retry goes through the chat service.
|
||||
describe("an external chat message in a connected conversation", () => {
|
||||
async function connectConversation(f: { companyId: string; issueId: string; agentId: string }) {
|
||||
const [application] = await db.insert(toolApplications).values({ companyId: f.companyId, name: "Slack", type: "chat" }).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({ companyId: f.companyId, applicationId: application.id,
|
||||
name: "Slack", uid: randomUUID(), transport: "chat_sdk", connectionPurpose: "channel" }).returning();
|
||||
const [endpoint] = await db.insert(chatEndpoints).values({ companyId: f.companyId, connectionId: connection.id,
|
||||
provider: "slack", publicId: randomUUID(), assignedAgentId: f.agentId, status: "active" }).returning();
|
||||
expect(endpoint.externalExecutionPolicy).toBe("restricted");
|
||||
await db.insert(chatConversations).values({ companyId: f.companyId, endpointId: endpoint.id, issueId: f.issueId,
|
||||
externalConversationId: "channel", externalThreadId: randomUUID(), externalLabel: "#work", state: "waiting" });
|
||||
}
|
||||
|
||||
it("continues through the chat service's Retry", async () => {
|
||||
const f = await runnerLostMidTurn({ wake: "system_chat" });
|
||||
await connectConversation(f);
|
||||
const actionId = randomUUID();
|
||||
const prepared: Array<{ failedRunId: string; initiatedByUserId: string }> = [];
|
||||
registerInterruptedTurnChatRetry(async (_tx, scope) => { prepared.push(scope); return { actionId }; });
|
||||
try {
|
||||
const outcome = await requestRestartInterruptedTurnRetry(db, f.claim);
|
||||
expect(outcome).toEqual({ requested: true, requestId: expect.any(String) });
|
||||
expect(prepared).toEqual([expect.objectContaining({ failedRunId: f.runId, initiatedByUserId: "local-board" })]);
|
||||
const [retry] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id,
|
||||
(outcome as { requestId: string }).requestId));
|
||||
expect(retry.payload).toMatchObject({ taskRetry: { chatActionId: actionId } });
|
||||
expect(await unknownOutcomeEvents(f.runId)).toHaveLength(1);
|
||||
} finally { registerInterruptedTurnChatRetry(undefined); }
|
||||
}, 30_000);
|
||||
|
||||
it("keeps the visible Retry when the chat service is not available", async () => {
|
||||
const f = await runnerLostMidTurn({ wake: "system_chat" });
|
||||
await connectConversation(f);
|
||||
expect(await requestRestartInterruptedTurnRetry(db, f.claim)).toEqual({ requested: false, reason: "retry_refused" });
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ title: "the refusal did not prove the Runner process gone", wake: "user" as const, refusal: "process_identity_changed" as const,
|
||||
reason: "provider_turn_unsettled" },
|
||||
{ title: "no reattachment refusal was recorded", wake: "user" as const, refusal: null, reason: "provider_turn_unsettled" },
|
||||
{ title: "the source was a monitor wake, not a retry of owed work", wake: "system_monitor" as const, refusal: "process_not_running" as const,
|
||||
reason: "not_user_request" },
|
||||
{ title: "a system chat wake's message was deleted", wake: "system_chat" as const, refusal: "process_not_running" as const,
|
||||
chatMessage: "deleted" as const, reason: "not_user_request" },
|
||||
{ title: "a system chat wake's message was written by a run", wake: "system_chat" as const,
|
||||
refusal: "process_not_running" as const, chatMessage: "written_by_run" as const, reason: "not_user_request" },
|
||||
{ title: "a linked person's chat message was deleted", wake: "user_chat" as const, refusal: "process_not_running" as const,
|
||||
chatMessage: "deleted" as const, reason: "message_unavailable" },
|
||||
{ title: "a system assignment's Runner was not proven gone", wake: "system_assignment" as const,
|
||||
refusal: "process_identity_changed" as const, reason: "provider_turn_unsettled" },
|
||||
])("keeps the visible Retry and records nothing when $title", async ({ wake, refusal, reason, ...rest }) => {
|
||||
const f = await runnerLostMidTurn({ wake, refusal, chatMessage: "chatMessage" in rest ? rest.chatMessage : undefined });
|
||||
expect(await requestRestartInterruptedTurnRetry(db, f.claim)).toEqual({ requested: false, reason });
|
||||
expect(await unknownOutcomeEvents(f.runId)).toHaveLength(0);
|
||||
expect(await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId),
|
||||
eq(agentWakeupRequests.reason, "task_retry")))).toHaveLength(0);
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { heartbeatRuns } from "@paperclipai/db";
|
||||
import { legacyControllerBootId } from "./legacy-controller-lease.js";
|
||||
import { SERVER_SHUTDOWN_INTERRUPTED_CODE } from "./legacy-shutdown-before-dispatch.js";
|
||||
import { readControllerProcess } from "./controller-process-identity.js";
|
||||
|
||||
type Run = Pick<typeof heartbeatRuns.$inferSelect,
|
||||
"runtimeMode" | "status" | "errorCode" | "resultJson" | "controllerBootId">;
|
||||
@@ -29,3 +30,19 @@ export function isServerReplacementInterruption(run: Run, currentBootId: string
|
||||
return diagnostic !== null && typeof diagnostic === "object"
|
||||
&& (diagnostic as Record<string, unknown>).runPredatesObserver === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacement stopped this legacy run's setup before adapter dispatch
|
||||
* (bootstrap evidence `providerWorkStarted: false`), and the row names the
|
||||
* server process that owned it. No provider action happened, so it continues
|
||||
* in the server-restart lane even when its failure budget is spent. A row
|
||||
* saved by an older release without a controller process stamp cannot show
|
||||
* its owner and stays in the charged lane.
|
||||
*/
|
||||
export function isReplacedPreparation(run: Run & { controllerProcess?: unknown }, currentBootId: string = legacyControllerBootId): boolean {
|
||||
const evidence = run.resultJson?.executionRecovery;
|
||||
const record = evidence && typeof evidence === "object" && !Array.isArray(evidence)
|
||||
? evidence as Record<string, unknown> : null;
|
||||
return record?.kind === "bootstrap" && record.providerWorkStarted === false
|
||||
&& readControllerProcess(run.controllerProcess) !== null && isServerReplacementInterruption(run, currentBootId);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { agents, agentWakeupRequests, chatConversations, chatEndpoints, companies, budgetPolicies, costEvents, createDb, type Db, environmentLeases, environments, executionWorkspaces, executionWorkspaceSnapshots, workspaceOperations, heartbeatRunEvents, heartbeatRuns, issueComments, issues, approvals, issueApprovals, issueRecoveryActions, nativeRunFinalizations, toolApplications, toolConnections, toolInvocations, applyPendingMigrations } from "@paperclipai/db";
|
||||
import { agents, agentWakeupRequests, chatActions, chatConversations, chatEndpoints, companies, budgetPolicies, costEvents, createDb, type Db, environmentLeases, environments, executionWorkspaces, executionWorkspaceSnapshots, workspaceOperations, heartbeatRunEvents, heartbeatRuns, issueComments, issues, approvals, issueApprovals, issueRecoveryActions, nativeRunFinalizations, toolApplications, toolConnections, toolInvocations, applyPendingMigrations } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
|
||||
import { priorRecoveryApiReceipt, unresolvedRecoveryToolInvocation } from "./recovery-effect-receipts.js";
|
||||
import { requestTaskRetry } from "./task-retry.js";
|
||||
@@ -937,6 +937,95 @@ describe("durable task Retry admission", () => {
|
||||
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
const refusedExactChatReplay = (reason?: string) => async (tx: Db, scope: { companyId: string; issueId: string; failedRunId: string }) => {
|
||||
const [endpoint] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.companyId, scope.companyId));
|
||||
await tx.insert(chatActions).values({ companyId: scope.companyId, endpointId: endpoint.id, kind: "failed_run_retry",
|
||||
status: "issued", providerActionId: randomUUID(), payload: { issueId: scope.issueId, failedRunId: scope.failedRunId } });
|
||||
throw new HttpError(409, "refused", { code: "chat_failed_run_retry_not_authorized", ...(reason ? { reason } : {}) });
|
||||
};
|
||||
|
||||
it.each([undefined, "accepted_result_without_new_input", "prior_result_publication", "source_authorization"])(
|
||||
"continues a connected task from saved work when its exact chat request cannot be repeated: %s", async reason => {
|
||||
const input = await seedChatTask();
|
||||
const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.observedRunId));
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: input.issueId, source: "issue.monitor",
|
||||
wakeReason: "issue_monitor_due" } }).where(eq(heartbeatRuns.id, source.id));
|
||||
const receipt = await requestTaskRetry({ ...input, actorSource: "local_implicit", prepareChatRetry: refusedExactChatReplay(reason) });
|
||||
expect(receipt).toMatchObject({ accepted: true, stale: false, observedRunId: source.id });
|
||||
expect(receipt.chatActionId).toBeUndefined();
|
||||
expect(await db.select().from(chatActions).where(eq(chatActions.companyId, input.companyId))).toHaveLength(0);
|
||||
const [intent] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!));
|
||||
expect(intent).toMatchObject({ status: "deferred_issue_execution", reason: "task_retry", requestedByActorId: input.actorId,
|
||||
payload: { issueId: input.issueId, taskRetry: { sourceRunId: source.id, actorId: input.actorId } } });
|
||||
expect((intent.payload!.taskRetry as Record<string, unknown>).chatActionId).toBeUndefined();
|
||||
await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }).where(eq(agents.id, source.agentId));
|
||||
await db.insert(heartbeatRuns).values({ companyId: input.companyId, agentId: source.agentId, status: "running" });
|
||||
await heartbeatService(db).resumeTaskRetry(input.companyId, receipt.requestId!);
|
||||
const queued = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId),
|
||||
eq(heartbeatRuns.status, "queued")));
|
||||
expect(queued).toHaveLength(1);
|
||||
expect(queued[0].contextSnapshot).toMatchObject({ issueId: input.issueId, previousRunId: source.id,
|
||||
taskRetryRequestId: receipt.requestId, forceFreshSession: true, responsibleUserId: input.actorId });
|
||||
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!)))[0])
|
||||
.toMatchObject({ status: "coalesced", runId: queued[0].id });
|
||||
});
|
||||
|
||||
it.each(["person", "automatic"] as const)(
|
||||
"continues a person's saved board turn on a connected task from saved work without replaying it: %s", async initiator => {
|
||||
const input = await seedChatTask();
|
||||
const [source] = await db.update(heartbeatRuns).set({ runtimeMode: "legacy", errorCode: "adapter_failed",
|
||||
error: "Provider stopped", responsibleUserId: input.actorId, sessionIdAfter: "provider-session",
|
||||
contextSnapshot: { issueId: input.issueId, source: "issue.comment.reopen", wakeCommentId: randomUUID() } })
|
||||
.where(eq(heartbeatRuns.id, input.observedRunId)).returning();
|
||||
let calls = 0;
|
||||
const request = { ...input, actorSource: "local_implicit" as const,
|
||||
...(initiator === "automatic" ? { initiatedBy: "restart_recovery" as const } : {}),
|
||||
prepareChatRetry: async () => { calls += 1; return { actionId: randomUUID() }; } };
|
||||
if (initiator === "automatic") {
|
||||
await expect(requestTaskRetry(request)).rejects.toMatchObject({ status: 409,
|
||||
details: { code: "chat_failed_run_retry_not_authorized", reason: "saved_board_message_not_replayable" } });
|
||||
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId))).toHaveLength(0);
|
||||
expect(calls).toBe(0);
|
||||
return;
|
||||
}
|
||||
const receipt = await requestTaskRetry(request);
|
||||
expect(receipt).toMatchObject({ accepted: true, stale: false, observedRunId: source.id });
|
||||
expect(receipt.chatActionId).toBeUndefined();
|
||||
expect(calls).toBe(0);
|
||||
const [intent] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!));
|
||||
const taskRetry = intent.payload!.taskRetry as Record<string, unknown>;
|
||||
expect(taskRetry).toMatchObject({ sourceRunId: source.id, actorId: input.actorId });
|
||||
expect(taskRetry.chatActionId).toBeUndefined();
|
||||
expect(taskRetry.boardMessageOrigin).toBeUndefined();
|
||||
await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }).where(eq(agents.id, source.agentId));
|
||||
await db.insert(heartbeatRuns).values({ companyId: input.companyId, agentId: source.agentId, status: "running" });
|
||||
await heartbeatService(db).resumeTaskRetry(input.companyId, receipt.requestId!);
|
||||
const queued = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId),
|
||||
eq(heartbeatRuns.status, "queued")));
|
||||
expect(queued).toHaveLength(1);
|
||||
expect(queued[0].contextSnapshot).toMatchObject({ previousRunId: source.id, taskRetryRequestId: receipt.requestId,
|
||||
forceFreshSession: true, responsibleUserId: input.actorId });
|
||||
expect(queued[0].contextSnapshot?.boardMessageRetry).toBeUndefined();
|
||||
expect(queued[0].contextSnapshot?.wakeCommentId).toBeUndefined();
|
||||
});
|
||||
|
||||
it("continues a person's Retry on a connected task when no chat retry owner is available", async () => {
|
||||
const input = await seedChatTask();
|
||||
const receipt = await requestTaskRetry({ ...input, actorSource: "local_implicit" });
|
||||
expect(receipt).toMatchObject({ accepted: true, chatActionId: undefined });
|
||||
const automatic = await seedChatTask();
|
||||
await expect(requestTaskRetry({ ...automatic, initiatedBy: "provider_limit_reset" })).rejects.toMatchObject({ status: 409 });
|
||||
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, automatic.companyId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("keeps an automatic Retry from continuing a connected task without the exact chat request", async () => {
|
||||
const input = await seedChatTask();
|
||||
await expect(requestTaskRetry({ ...input, initiatedBy: "restart_recovery", prepareChatRetry: refusedExactChatReplay() }))
|
||||
.rejects.toMatchObject({ status: 409, details: { code: "chat_failed_run_retry_not_authorized" } });
|
||||
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId))).toHaveLength(0);
|
||||
expect(await db.select().from(chatActions).where(eq(chatActions.companyId, input.companyId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("does not retry an authorization denial", async () => {
|
||||
const input = await seedChatTask();
|
||||
let calls = 0;
|
||||
|
||||
@@ -18,13 +18,14 @@ import { preserveNativeFailedWorkspace, preserveTaskRemoteWorkspaceWriter } from
|
||||
import { NativeWorkspaceFinalizationBusyError } from "./native-runtime/native-workspace-finalization-ownership.js";
|
||||
import { adapterExecutionControls } from "./adapter-execution-control.js";
|
||||
import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js";
|
||||
import { deferredChatInputPredicate, resumeDeferredChatWake } from "./durable-chat-wakeup.js";
|
||||
import { deferredChatInputPredicate, resumeDeferredChatWake, unadmittedChatWakeupCondition } from "./durable-chat-wakeup.js";
|
||||
import { notifyDeferredExecutionWork } from "./deferred-execution-notifications.js";
|
||||
import { hasPendingRunCleanup } from "./execution-blocker.js";
|
||||
import { PersistedExecutionWaitRefusal } from "./deferred-execution-wait.js";
|
||||
import { rearmExhaustedNativeFinalization } from "./native-runtime/exhausted-finalization-retry.js";
|
||||
import { NativeChatReviewPresentationContentionError } from "./native-runtime/native-chat-review-presentation.js";
|
||||
import { isExternalChatWaitAuthorizationContention } from "./native-runtime/chat-attachment-reuse.js";
|
||||
import { selectTaskRetryInput } from "./chat-channels/task-retry-input.js";
|
||||
|
||||
export async function taskRetryMutationAllowed(db: Db, input: {
|
||||
companyId: string; issueId: string; actorId: string; actorSource: TaskRetryIntent["actorSource"];
|
||||
@@ -241,6 +242,11 @@ function automaticRetryActor(input: Pick<TaskRetryRequest, "initiatedBy" | "acto
|
||||
const TASK_RETRY_CONTENTION_ATTEMPTS = 10;
|
||||
const TASK_RETRY_CONTENTION_DELAY_MS = 100;
|
||||
|
||||
function isExactChatReplayRefusal(error: unknown) {
|
||||
return error instanceof HttpError && error.status === 409 &&
|
||||
(error.details as Record<string, unknown> | undefined)?.code === "chat_failed_run_retry_not_authorized";
|
||||
}
|
||||
|
||||
function isTaskRetryContention(error: unknown) {
|
||||
return error instanceof NativeChatReviewPresentationContentionError || isExternalChatWaitAuthorizationContention(error);
|
||||
}
|
||||
@@ -418,9 +424,15 @@ function admitTaskRetry(input: TaskRetryRequest) {
|
||||
await notifyDeferredExecutionWork(tx, { companyId: issue.companyId, requestId: id });
|
||||
}
|
||||
}
|
||||
if (chat && !active && !busy && !boardMessageOrigin && !intent.queuedChatRequestId && (latest.contextSnapshot?.source === "issue.comment.reopen" || latest.contextSnapshot?.boardMessageRetry === true) &&
|
||||
latest.responsibleUserId === input.actorId) {
|
||||
throw conflict("This saved message cannot be retried safely. Send a new message on the task to continue from saved work.",
|
||||
const savedBoardTurn = Boolean(chat && !active && !busy && !boardMessageOrigin && !intent.queuedChatRequestId &&
|
||||
(latest.contextSnapshot?.source === "issue.comment.reopen" || latest.contextSnapshot?.boardMessageRetry === true) &&
|
||||
latest.responsibleUserId === input.actorId);
|
||||
const hasUnadmittedChatInput = async () => (await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.id, issue.id),
|
||||
eq(issues.companyId, issue.companyId), unadmittedChatWakeupCondition(issues.id, issues.companyId))).limit(1)).length > 0 ||
|
||||
Boolean((await selectTaskRetryInput(tx, { companyId: issue.companyId, issueId: issue.id,
|
||||
agentId: issue.assigneeAgentId!, failedRunId: latest.id }))?.sourceActionIds.length);
|
||||
if (savedBoardTurn && (input.initiatedBy || await hasUnadmittedChatInput())) {
|
||||
throw conflict("This saved message can't be repeated exactly as it was sent. Retry continues the task from its saved work instead.",
|
||||
{ code: "chat_failed_run_retry_not_authorized", reason: "saved_board_message_not_replayable" });
|
||||
}
|
||||
await tx.insert(agentWakeupRequests).values({ id, companyId: issue.companyId, agentId: issue.assigneeAgentId,
|
||||
@@ -429,12 +441,23 @@ function admitTaskRetry(input: TaskRetryRequest) {
|
||||
status: active || busy ? "coalesced" : "deferred_issue_execution",
|
||||
runId: active?.runId ?? (busy ? latest.id : null),
|
||||
payload: { issueId: issue.id, taskRetry: intent }, finishedAt: active || busy ? new Date() : null });
|
||||
if (chat && !boardMessageOrigin && !intent.queuedChatRequestId && !active && !busy) {
|
||||
if (!input.prepareChatRetry) throw conflict("Retry is unavailable for this connected conversation.");
|
||||
intent.chatActionId = (await input.prepareChatRetry(db, { companyId: issue.companyId, issueId: issue.id,
|
||||
agentId: issue.assigneeAgentId, failedRunId: latest.id, initiatedByUserId: input.actorId, retryIntentId: id })).actionId;
|
||||
await tx.update(agentWakeupRequests).set({ payload: { issueId: issue.id, taskRetry: intent } })
|
||||
.where(eq(agentWakeupRequests.id, id));
|
||||
if (chat && !boardMessageOrigin && !intent.queuedChatRequestId && !active && !busy && !savedBoardTurn) {
|
||||
if (!input.prepareChatRetry && input.initiatedBy) throw conflict("Retry is unavailable for this connected conversation.");
|
||||
const prepareChatRetry = input.prepareChatRetry ?? (() => { throw conflict("Retry is unavailable for this connected conversation.",
|
||||
{ code: "chat_failed_run_retry_not_authorized" }); });
|
||||
const scope = { companyId: issue.companyId, issueId: issue.id, agentId: issue.assigneeAgentId,
|
||||
failedRunId: latest.id, initiatedByUserId: input.actorId, retryIntentId: id };
|
||||
const prepared = await tx.transaction(savepoint => prepareChatRetry(savepoint as unknown as Db, scope))
|
||||
.catch(async error => {
|
||||
if (input.initiatedBy || !isExactChatReplayRefusal(error)) throw error;
|
||||
if (await hasUnadmittedChatInput()) throw error;
|
||||
return null;
|
||||
});
|
||||
if (prepared) {
|
||||
intent.chatActionId = prepared.actionId;
|
||||
await tx.update(agentWakeupRequests).set({ payload: { issueId: issue.id, taskRetry: intent } })
|
||||
.where(eq(agentWakeupRequests.id, id));
|
||||
}
|
||||
}
|
||||
if (!busy) {
|
||||
for (const action of records) {
|
||||
|
||||
@@ -241,7 +241,7 @@ export function toolActionDeliveryService(
|
||||
request.status === "executed"
|
||||
? "The approved action already ran. Do not call it again; continue with the recorded result. Process the result and answer the user in your own words. Do not paste the raw tool or transport JSON unless the user asks for it."
|
||||
: request.status === "rejected"
|
||||
? "The human declined this action. Do not retry the same call. Adjust your approach or explain what is blocked."
|
||||
? "The human declined this action. Do not retry the same call on your own. Adjust your approach or explain what is blocked. If the person asks for the same action again in a later message, that is an explicit retry: make the call again so a fresh approval card is posted."
|
||||
: request.status === "expired" ||
|
||||
request.status === "cancelled"
|
||||
? "The review is no longer available. Do not execute the stored request. Explain the recorded outcome before requesting another review."
|
||||
|
||||
@@ -8970,7 +8970,7 @@ export function createToolGatewayService(
|
||||
invocationId: invocation.id,
|
||||
actionRequestId: actionRequest.id,
|
||||
instructions:
|
||||
"The action was declined. Do not retry the same call; adjust your approach or report the decline on the task.",
|
||||
"The action was declined. Do not retry the same call on your own; adjust your approach or report the decline on the task. If the person asks for the same action again in a new message, the call made for that message posts a fresh approval card.",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1595,7 +1595,7 @@ describe("automatic retained workspace recovery", () => {
|
||||
await expect(db.transaction(async tx => {
|
||||
await tx.update(agentWakeupRequests).set({ status: "skipped" }).where(eq(agentWakeupRequests.id, wake.id));
|
||||
await recover(tx as unknown as typeof db);
|
||||
expect(scheduleRecoveryRetry).toHaveBeenCalledWith(queued.id);
|
||||
expect(scheduleRecoveryRetry).toHaveBeenCalledWith(queued.id, expect.any(Object));
|
||||
throw rollback;
|
||||
})).rejects.toBe(rollback);
|
||||
scheduleRecoveryRetry.mockClear();
|
||||
|
||||
Reference in new issue
Block a user