diff --git a/server/src/__tests__/skill-version-cache.test.ts b/server/src/__tests__/skill-version-cache.test.ts index 5c31f420f8f..2947983c93c 100644 --- a/server/src/__tests__/skill-version-cache.test.ts +++ b/server/src/__tests__/skill-version-cache.test.ts @@ -6,7 +6,7 @@ import os from "node:os"; import path from "node:path"; import { eq } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; -import { agents, heartbeatRuns, heartbeatRunEvents, issues, nativeRunFinalizations, environmentLeases, companies, companySkills, companySkillVersions, companySkillRepositorySnapshots, createDb } from "@paperclipai/db"; +import { agents, heartbeatRuns, heartbeatRunEvents, issues, issueRecoveryActions, nativeRunFinalizations, environmentLeases, companies, companySkills, companySkillVersions, companySkillRepositorySnapshots, createDb } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { companySkillService } from "../services/company-skills.js"; import { skillVersionCachePaths, touchSkillVersionCache, withSkillVersionCacheLock } from "../services/skill-version-cache.js"; @@ -286,9 +286,45 @@ describePostgres("immutable skill version cache", () => { runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, run.id)); await db.insert(nativeRunFinalizations).values({ companyId, issueId: issue!.id, runId: run.id, phase: "terminal_failure", recoveryState: "blocked" }); + // Unresolved recovery: the same run is scheduled to resume from its saved input. + await resumeAction(companyId, issue!.id, run.id); return { run, execution }; } + async function resumeAction(companyId: string, issueId: string, runId: string) { + const [action] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", + cause: "native_session_interrupted", fingerprint: `resume:${runId}`, nextAction: "Resume the saved run.", + evidence: { runId }, wakePolicy: { kind: "resume_native_run", runId } }).returning(); + return action!; + } + + it("evicts and deletes a skill whose only pin is a blocked failed run that nothing will resume", async () => { + const f = await fixture(); + await f.resolve(f.versions[0]!.id); + await touchSkillVersionCache(f.companyId, f.skillId, f.versions[0]!.id, Date.now() - 7_200_000); + const run = await activeRun(f.companyId, { skillVersions: { [f.key]: f.versions[0]!.id } }); + const [issue] = await db.insert(issues).values({ companyId: f.companyId, title: "Failed journey" }).returning(); + await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issue!.id, nativePhase: "terminal_failure", + status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.id)); + await db.insert(nativeRunFinalizations).values({ companyId: f.companyId, issueId: issue!.id, runId: run.id, + phase: "terminal_failure", recoveryState: "blocked", failureCode: "native_continuation_requires_reconciliation" }); + const action = await resumeAction(f.companyId, issue!.id, run.id); + await expect(companySkillService(db).deleteSkill(f.companyId, f.skillId)).rejects.toThrow("active or recovering run"); + await db.update(issueRecoveryActions).set({ status: "resolved", wakePolicy: null }).where(eq(issueRecoveryActions.id, action.id)); + await db.update(nativeRunFinalizations).set({ nextAttemptAt: new Date(Date.now() + 60_000) }) + .where(eq(nativeRunFinalizations.runId, run.id)); + await expect(companySkillService(db).deleteSkill(f.companyId, f.skillId)).rejects.toThrow("active or recovering run"); + await db.update(nativeRunFinalizations).set({ nextAttemptAt: null, leaseOwner: "native-finalizer:other" }) + .where(eq(nativeRunFinalizations.runId, run.id)); + await expect(companySkillService(db).deleteSkill(f.companyId, f.skillId)).rejects.toThrow("active or recovering run"); + expect((await sweepSkillVersionCache(db, { companyId: f.companyId })).skipped.protected_version).toBe(1); + await db.update(nativeRunFinalizations).set({ leaseOwner: null }).where(eq(nativeRunFinalizations.runId, run.id)); + expect((await sweepSkillVersionCache(db, { companyId: f.companyId })).evicted).toBe(1); + await expect(companySkillService(db).deleteSkill(f.companyId, f.skillId)).resolves.toMatchObject({ id: f.skillId }); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id)))[0]) + .toMatchObject({ phase: "terminal_failure", recoveryState: "blocked" }); + }); + it.each([false, true])("protects unknown legacy versions without changing unresolved recovery (bundled skill: %s)", async bundled => { const f = await fixture(); const old = await f.resolve(f.versions[0]!.id); diff --git a/server/src/services/skill-version-cache.ts b/server/src/services/skill-version-cache.ts index 9494ff29f62..a7c54694417 100644 --- a/server/src/services/skill-version-cache.ts +++ b/server/src/services/skill-version-cache.ts @@ -4,7 +4,7 @@ import { randomUUID } from "node:crypto"; import { constants, promises as fs } from "node:fs"; import path from "node:path"; import { and, eq, inArray, isNull, sql } from "drizzle-orm"; -import { companySkillVersions, heartbeatRuns, +import { companySkillVersions, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, environmentLeases, withDedicatedDbConnection, type Db } from "@paperclipai/db"; import { resolvePaperclipInstanceRoot } from "../home-paths.js"; import { assertSkillSnapshotPath } from "./skill-snapshot.js"; @@ -101,20 +101,30 @@ export async function lastUsedAt(filename: string): Promise { } } -export function skillRunNeedsFilesSql() { +export function skillRunNeedsFilesSql(options: { releaseBlockedFailures?: boolean } = {}) { const unstartedAdmission = and( inArray(heartbeatRuns.status, ["queued", "scheduled_retry"]), noRetainedExecutionPredicate(), isNull(heartbeatRuns.finishedAt), isNull(heartbeatRuns.runnerInstanceId), isNull(heartbeatRuns.nativePhase), isNull(heartbeatRuns.nativePhaseUpdatedAt), sql`not (coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) ?| array['skillVersions', 'skillSelectionSnapshot'])`, ); + // For version pins, a blocked terminal failure is a recorded dead end: Retry + // and fresh continuation start new runs that select skills again. Only a + // same-run resume, a scheduled attempt, or a lease holder reads its pins again. + // Runtime asset preservation keeps its broader retention. + const blockedFailureSettled = options.releaseBlockedFailures ? sql`and not (f.phase = 'terminal_failure' + and f.recovery_state is not distinct from 'blocked' and f.lease_owner is null and f.next_attempt_at is null + and not exists (select 1 from ${issueRecoveryActions} a + where a.company_id = f.company_id and a.source_issue_id = f.issue_id and a.status in ('active', 'escalated') + and a.wake_policy->>'kind' = 'resume_native_run' and a.wake_policy->>'runId' = f.run_id::text))` : sql``; return sql`not (${unstartedAdmission}) and ( ${heartbeatRuns.status} not in ('succeeded', 'failed', 'timed_out', 'cancelled', 'interrupted') or ${heartbeatRuns.finishedAt} is null or ${heartbeatRuns.controllerLeaseExpiresAt} > now() or exists (select 1 from ${nativeRunFinalizations} f where f.company_id = ${heartbeatRuns.companyId} and f.run_id = ${heartbeatRuns.id} - and (f.phase <> 'committed' or f.lease_owner is not null or f.recovery_state is not null)) + and (f.phase <> 'committed' or f.lease_owner is not null or f.recovery_state is not null) + ${blockedFailureSettled}) or exists (select 1 from ${environmentLeases} l where l.company_id = ${heartbeatRuns.companyId} and l.heartbeat_run_id = ${heartbeatRuns.id} and (l.status = 'pending_cleanup' or l.cleanup_status = 'failed' @@ -139,7 +149,7 @@ export async function protectedVersions(db: Db, companyId: string, targetSkill?: and not coalesce(${heartbeatRuns.contextSnapshot} ? 'skillVersions', false) then ${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput' end`, }) - .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), skillRunNeedsFilesSql())); + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), skillRunNeedsFilesSql({ releaseBlockedFailures: true }))); const versions = new Set(); const leaseDeadlines = new Map(); const unknown = () => ({ versions: null, leaseDeadlines });