The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
perf(recovery): decline native legacy checks before bulk reads (#17540)
Devin Foley80c1261417a5
diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.mdindex 51d174bb3e..0875b17744 100644--- a/doc/native-workspace-finalization-recovery.md+++ b/doc/native-workspace-finalization-recovery.md@@ -492,3 +492,10 @@ binding, and chat source fields under the existing nonblocking share lock.It excludes saved execution input, runner profiles, and log excerpts. Actualretry admission still reads the complete run and its recovery evidence. Thesereads preserve stored run data, source revocation checks, and JSON value types.++Legacy continuation recovery rejects native runs before it loads their saved+execution input. The persisted disposition check reads only the task binding+for a native run. It keeps the same task-binding and native-finalization skip+reasons, including the original nonblank binding values. Native input and history+stay stored. Real legacy recovery still reads+its complete context, profile, excerpts, and required failure evidence.diff --git a/server/src/services/recovery/legacy-disposition-read.test.ts b/server/src/services/recovery/legacy-disposition-read.test.tsnew file mode 100644index 0000000000..749a799187--- /dev/null+++ b/server/src/services/recovery/legacy-disposition-read.test.ts@@ -0,0 +1,88 @@+import { randomBytes, randomUUID } from "node:crypto";+import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";+import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture";+import { eq } from "drizzle-orm";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";+import { readLegacyDispositionSource } from "./legacy-disposition-read.js";+import { recoveryService } from "./service.js";++const support = await getEmbeddedPostgresTestSupport();++describe.skipIf(!support.supported)("legacy disposition source reads", () => {+ let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;+ let db: ReturnType<typeof createDb>;+ let companyId: string;+ let agentId: string;++ beforeAll(async () => {+ database = await startEmbeddedPostgresTestDatabase("legacy-disposition-read-");+ db = createDb(database.connectionString);+ const [company] = await db.insert(companies).values({ name: "Legacy disposition fixture", issuePrefix: "LDF" }).returning();+ const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Disposition agent", adapterType: "process" }).returning();+ companyId = company.id;+ agentId = agent.id;+ }, 60_000);++ afterAll(async () => {+ await db?.$client.end();+ await database?.cleanup();+ });++ it("declines native input below the byte budget and keeps complete legacy evidence", async () => {+ const issueId = randomUUID(), bulk = randomBytes(128 * 1024).toString("base64");+ const context = { issueId, savedInput: bulk, executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 1 } };+ const [before] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", status: "succeeded",+ contextSnapshot: context, runnerProfileJson: { savedInput: bulk }, stdoutExcerpt: bulk, stderrExcerpt: bulk,+ errorCode: "adapter_failed", resultJson: { executionRecovery: { providerWorkStarted: true }, stdout: bulk } }).returning();+ const events: Array<Record<string, unknown>> = [];+ const now = Date.now();+ const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));+ installDatabaseResponseCapture(db, { heartbeatRuns }, capture);+ try {+ expect(await readLegacyDispositionSource(db, { companyId, issueId, runId: before.id }))+ .toEqual({ kind: "skip", decision: { kind: "skip", reason: "native_finalization" } });+ } finally { capture.flush(); }+ expect(events.at(-1)).toMatchObject({ completedQueries: 1, groups: 1 });+ expect(Number(events.at(-1)?.responseValueBytes)).toBeLessThan(1024);+ expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, before.id)))[0]).toEqual(before);+ expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64));+ await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, before.id));+ const legacy = await readLegacyDispositionSource(db, { companyId, issueId, runId: before.id });+ expect(legacy.kind).toBe("full");+ if (legacy.kind !== "full") throw new Error("expected complete legacy input");+ expect(legacy.run).toEqual({ ...before, runtimeMode: "legacy" });+ expect((await readLegacyDispositionSource(db, { companyId: randomUUID(), issueId, runId: before.id })))+ .toMatchObject({ kind: "full", run: undefined });+ });++ it.each([+ { context: { issueId: " target " }, issueId: "target", reason: "invalid_issue_binding" },+ { context: { issueId: " ", taskId: "target" }, issueId: "target", reason: "native_finalization" },+ { context: { taskId: " target " }, issueId: "target", reason: "invalid_issue_binding" },+ { context: { issueId: 42, taskId: "target" }, issueId: "target", reason: "native_finalization" },+ { context: { issueId: "other", taskId: "target" }, issueId: "target", reason: "invalid_issue_binding" },+ { context: { issueId: null, taskId: false }, issueId: "target", reason: "invalid_issue_binding" },+ { context: null, issueId: "target", reason: "invalid_issue_binding" },+ ])("keeps native binding decisions for $context", async ({ context, issueId, reason }) => {+ const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", contextSnapshot: context }).returning();+ expect(await readLegacyDispositionSource(db, { companyId, issueId, runId: run.id }))+ .toEqual({ kind: "skip", decision: { kind: "skip", reason } });+ });++ it("skips native continuation in SQL without loading or rewriting its saved input", async () => {+ const bulk = randomBytes(128 * 1024).toString("base64");+ const [before] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", status: "succeeded",+ contextSnapshot: { issueId: randomUUID(), savedInput: bulk }, runnerProfileJson: { savedInput: bulk } }).returning();+ const enqueueWakeup = vi.fn(async () => { throw new Error("native work must not enter legacy recovery"); });+ const service = recoveryService(db, { enqueueWakeup });+ const events: Array<Record<string, unknown>> = [], now = Date.now();+ const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));+ installDatabaseResponseCapture(db, { heartbeatRuns }, capture);+ try { expect(await service.reconcileLegacyContinuation(before.id)).toBe("skipped"); }+ finally { capture.flush(); }+ expect(events.at(-1)).toMatchObject({ completedQueries: 1, responseValueBytes: 0 });+ expect(enqueueWakeup).not.toHaveBeenCalled();+ expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, before.id)))[0]).toEqual(before);+ });+});diff --git a/server/src/services/recovery/legacy-disposition-read.ts b/server/src/services/recovery/legacy-disposition-read.tsnew file mode 100644index 0000000000..08f9204f49--- /dev/null+++ b/server/src/services/recovery/legacy-disposition-read.ts@@ -0,0 +1,24 @@+import { heartbeatRuns, type Db } from "@paperclipai/db";+import { and, eq, getTableColumns, sql } from "drizzle-orm";+import { recoveryRunResultColumn } from "./run-result-read.js";++export async function readLegacyDispositionSource(+ db: Db,+ scope: { companyId: string; issueId: string; runId: string },+) {+ const where = and(eq(heartbeatRuns.id, scope.runId), eq(heartbeatRuns.companyId, scope.companyId));+ const [native] = await db.select({+ issueId: sql<unknown>`${heartbeatRuns.contextSnapshot}->'issueId'`,+ taskId: sql<unknown>`${heartbeatRuns.contextSnapshot}->'taskId'`,+ }).from(heartbeatRuns).where(and(where, eq(heartbeatRuns.runtimeMode, "native"))).limit(1);+ if (native) {+ const bound = [native.issueId, native.taskId]+ .map(value => typeof value === "string" && value.trim().length > 0 ? value : null).find(Boolean) ?? null;+ return { kind: "skip" as const, decision: {+ kind: "skip" as const, reason: bound === scope.issueId ? "native_finalization" : "invalid_issue_binding",+ } };+ }+ const [run] = await db.select({ ...getTableColumns(heartbeatRuns), resultJson: recoveryRunResultColumn })+ .from(heartbeatRuns).where(where).limit(1);+ return { kind: "full" as const, run };+}diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.tsindex 331122e10d..5701571e86 100644--- a/server/src/services/recovery/service.ts+++ b/server/src/services/recovery/service.ts@@ -1,5 +1,6 @@import { recoveryRunContextColumn, recoveryRunVersionColumn } from "./run-context-read.js";import { recoveryRunResultColumn } from "./run-result-read.js";+import { readLegacyDispositionSource } from "./legacy-disposition-read.js";import { isAgentAwaitingSetup } from "../../modules/agent-lifecycle/index.js";import { onboardingFirstTaskAwaitingUserSql } from "./onboarding-first-task-wait.js";import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";@@ -3793,9 +3794,9 @@ export function recoveryService(episode: LegacyDispositionEpisode,dispatchRunId?: string,) {- const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(and(- eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, issue.companyId),- )).limit(1);+ const source = await readLegacyDispositionSource(db, { companyId: issue.companyId, issueId: issue.id, runId });+ if (source.kind === "skip") return source.decision;+ const run = source.run;if (!run) return { kind: "skip" as const, reason: "missing_run" };const context = parseObject(run.contextSnapshot);if ((readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId)) !== issue.id) {@@ -3854,7 +3855,9 @@ export function recoveryService(}async function reconcileLegacyContinuation(runId: string) {- const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1);+ const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.id, runId), not(eq(heartbeatRuns.runtimeMode, "native")), eq(heartbeatRuns.status, "succeeded"),+ )).limit(1);if (!run || run.runtimeMode === "native" || run.status !== "succeeded") return "skipped" as const;const context = parseObject(run.contextSnapshot);const issueId = readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId);