diff --git a/server/src/services/native-runtime/native-harness-backup-migration.ts b/server/src/services/native-runtime/native-harness-backup-migration.ts index 685245aafd9..62d3ae7a48b 100644 --- a/server/src/services/native-runtime/native-harness-backup-migration.ts +++ b/server/src/services/native-runtime/native-harness-backup-migration.ts @@ -11,6 +11,7 @@ import { offlineMigrationExecutionWhere } from "../offline-migration-execution.j import { NativeHarnessBackupSourceError, readNativeHarnessBackupSource } from "./native-harness-backup-source.js"; import { settledNativeHarnessBackupOwner } from "./native-harness-preservation-source.js"; import { hasValidNativeHarnessFilesystemIndependence } from "./native-harness-filesystem-independence.js"; +import { NATIVE_HARNESS_BACKUP_SOURCE_ABSENT_KEY, recordNativeHarnessBackupSourceAbsence } from "./native-harness-backup-source-absence.js"; const MAX_PARALLEL_INDEPENDENCE_CHECKS = 4; @@ -19,8 +20,10 @@ export async function hasLocalNativeHarnessObligations(db: Db): Promise return false; } +type ObligationScope = { companyId: string; selectedSessionId: string; scopeDigest: string }; + async function* localNativeHarnessObligationScopes(db: Db, all = false, signal?: AbortSignal, - skip: ReadonlySet = new Set()): AsyncGenerator { + skip: ReadonlySet = new Set()): AsyncGenerator { let afterSession = "", afterScope = ""; for (;;) { signal?.throwIfAborted(); @@ -38,10 +41,13 @@ async function* localNativeHarnessObligationScopes(db: Db, all = false, signal?: where e.metadata->'nativeHarnessBackup'->>'schema' = 'paperclip.native-harness-backup-stamp.v2' and not exists (select 1 from native_harness_backups b where b.company_id = s.company_id and b.scope_digest = e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' and b.status = 'current') + and not coalesce(r.runner_profile_json #> array['${sql.raw(NATIVE_HARNESS_BACKUP_SOURCE_ABSENT_KEY)}', 'scopes', + e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256', 'manifestSha256s'] + ? (e.metadata->'nativeHarnessBackup'->>'manifestSha256'), false) and (s.id::text, coalesce(e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256', '')) > (${afterSession}, ${afterScope}) order by selected_session_id, scope_digest limit 100`); let next = 0, failed = false; - const invalid: string[] = []; + const invalid: ObligationScope[] = []; const checked = await Promise.allSettled(Array.from({ length: Math.min(MAX_PARALLEL_INDEPENDENCE_CHECKS, rows.length) }, async () => { while (!failed && (all || !invalid.length) && next < rows.length) { signal?.throwIfAborted(); @@ -50,7 +56,7 @@ async function* localNativeHarnessObligationScopes(db: Db, all = false, signal?: try { if (!row.has_receipt || !await hasValidNativeHarnessFilesystemIndependence(db, { companyId: row.company_id, selectedSessionId: row.selected_session_id, scopeDigest: row.scope_digest, - })) invalid.push(row.scope_digest); + })) invalid.push({ companyId: row.company_id, selectedSessionId: row.selected_session_id, scopeDigest: row.scope_digest }); } catch (error) { failed = true; throw error; } } })); @@ -190,6 +196,10 @@ export async function migrateNativeHarnessBackups(db: Db, input: { const [active] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(offlineMigrationExecutionWhere()).limit(1); if (active) throw new Error("native_harness_migration_requires_offline_writers"); const counts = await mapSources(input, (source, signal) => migrateSource(db, { storage: input.storage, signal }, source)); + for await (const scope of localNativeHarnessObligationScopes(db, true, input.signal)) { + input.signal.throwIfAborted(); + await recordNativeHarnessBackupSourceAbsence(db, { ...scope, signal: input.signal }); + } return counts.reduce((total, count) => total + count, 0); } @@ -278,16 +288,18 @@ export async function prestageNativeHarnessBackups(db: Db, input: { storage: Sto throw error; } }); - let absent = 0; - for await (const scopeDigest of localNativeHarnessObligationScopes(db, true, input.signal, visited)) { + const absent: Record = {}; + let gone = 0; + for await (const scope of localNativeHarnessObligationScopes(db, true, input.signal, visited)) { input.signal.throwIfAborted(); - if (visited.has(scopeDigest)) continue; - visited.add(scopeDigest); - absent++; - input.onOutcome?.("selected_source_absent"); + if (visited.has(scope.scopeDigest)) continue; + visited.add(scope.scopeDigest); + const outcome = await recordNativeHarnessBackupSourceAbsence(db, { ...scope, signal: input.signal }); + input.onOutcome?.(outcome); + if (outcome === "source_gone_recorded") gone++; + else absent[outcome] = (absent[outcome] ?? 0) + 1; } - const counts = { inspected: outcomes.length, published: 0, current: 0, deferred: {} as Record }; - if (absent) counts.deferred.selected_source_absent = absent; + const counts = { inspected: outcomes.length, published: 0, current: 0, ...(gone ? { sourceGone: gone } : {}), deferred: absent }; for (const outcome of outcomes) { if (outcome === "published" || outcome === "current") counts[outcome]++; else counts.deferred[outcome] = (counts.deferred[outcome] ?? 0) + 1; diff --git a/server/src/services/native-runtime/native-harness-backup-source-absence.ts b/server/src/services/native-runtime/native-harness-backup-source-absence.ts new file mode 100644 index 00000000000..77cf008c943 --- /dev/null +++ b/server/src/services/native-runtime/native-harness-backup-source-absence.ts @@ -0,0 +1,93 @@ +import { lstat, readdir } from "node:fs/promises"; +import { join } from "node:path"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { agentTaskSessions, heartbeatRuns, nativeHarnessBackups, nativeRunFinalizations, type Db } from "@paperclipai/db"; +import { adapterExecutionControls } from "../adapter-execution-control.js"; +import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js"; +import { nativeHarnessStateBase } from "./native-harness-backup-stamp.js"; +import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js"; + +export const NATIVE_HARNESS_BACKUP_SOURCE_ABSENT_KEY = "nativeHarnessBackupSourceAbsent"; +const SCHEMA = "paperclip.native-harness-backup-source-absent.v1"; +const terminal = ["succeeded", "failed", "cancelled", "interrupted", "timed_out"]; +type Scopes = Record; +export type NativeHarnessBackupSourceAbsence = "source_gone_recorded" | "selected_source_absent" | "selected_source_retiring" | "selected_source_unsettled" | "selected_source_busy"; + +const object = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +async function localSourceState(scopeDigest: string): Promise<"gone" | "present" | "retiring" | "unsettled"> { + const backups = join(nativeHarnessStateBase(), scopeDigest, "failover-backups"); + const missing = (error: NodeJS.ErrnoException) => { if (error.code === "ENOENT" || error.code === "ENOTDIR") return null; throw error; }; + if (await lstat(join(backups, "current")).catch(missing)) return "present"; + const names = (await readdir(backups).catch(missing) ?? []).filter(name => !name.startsWith(".expired-")); + if (names.some(name => name.startsWith(".retiring-"))) return "retiring"; + return names.length ? "unsettled" : "gone"; +} + +export async function recordNativeHarnessBackupSourceAbsence(db: Db, input: { + companyId: string; selectedSessionId: string; scopeDigest: string; signal: AbortSignal; +}): Promise { + if (!/^[a-f0-9]{64}$/.test(input.scopeDigest)) return "selected_source_absent"; + const publications: ActivityPublication[] = []; + const outcome = await db.transaction(async transaction => { + const tx = transaction as unknown as Db; + input.signal.throwIfAborted(); + await tx.execute(sql`set local lock_timeout = '1s'`); + const [selection] = await tx.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, input.companyId), + eq(agentTaskSessions.id, input.selectedSessionId), eq(agentTaskSessions.adapterType, "paperclip_runner"))).for("update"); + if (!selection?.lastRunId) return "selected_source_absent" as const; + if (!await tryLockNativeWorkspaceFinalization(tx, { companyId: input.companyId, runId: selection.lastRunId })) return "selected_source_absent" as const; + const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), + eq(heartbeatRuns.id, selection.lastRunId), eq(heartbeatRuns.agentId, selection.agentId))).for("update"); + const [clock] = await tx.execute<{ now: Date }>(sql`select clock_timestamp() as now`); + if (!run?.nativeIssueId || !run.nativeSessionId || !run.finishedAt || !terminal.includes(run.status) + || run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date(clock.now) + || adapterExecutionControls.has(run.id) || run.runnerProfileJson?.nativeWorkspaceFinalizationOwner != null) { + return "selected_source_absent" as const; + } + const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, input.companyId), + eq(nativeRunFinalizations.runId, run.id))).for("update"); + if (coordinator && (coordinator.leaseOwner || coordinator.nextAttemptAt)) return "selected_source_absent" as const; + const [active] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), + inArray(heartbeatRuns.status, ["queued", "running"]), or(eq(heartbeatRuns.nativeIssueId, run.nativeIssueId), + eq(heartbeatRuns.issueId, run.nativeIssueId), eq(heartbeatRuns.nativeSessionId, run.nativeSessionId)))).limit(1); + if (active) return "selected_source_absent" as const; + const [current] = await tx.select({ id: nativeHarnessBackups.id }).from(nativeHarnessBackups).where(and( + eq(nativeHarnessBackups.companyId, input.companyId), eq(nativeHarnessBackups.scopeDigest, input.scopeDigest), + eq(nativeHarnessBackups.status, "current"))).limit(1); + if (current) return "selected_source_absent" as const; + const leases = await tx.execute<{ manifest: string }>(sql`select e.metadata->'nativeHarnessBackup'->>'manifestSha256' as manifest + from environment_leases e where e.company_id = ${input.companyId}::uuid and e.issue_id = ${run.nativeIssueId}::uuid + and e.metadata->'nativeHarnessBackup'->>'schema' = 'paperclip.native-harness-backup-stamp.v2' + and e.metadata->'nativeHarnessBackup'->>'normalizedSessionId' = ${run.nativeSessionId} + and e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' = ${input.scopeDigest} + order by e.id for share of e`); + const manifests = [...new Set(leases.map(row => row.manifest).filter(value => /^sha256:[a-f0-9]{64}$/.test(value ?? "")))].sort(); + if (!manifests.length) return "selected_source_absent" as const; + input.signal.throwIfAborted(); + const local = await localSourceState(input.scopeDigest); + if (local === "retiring") return "selected_source_retiring" as const; + if (local === "unsettled") return "selected_source_unsettled" as const; + if (local === "present") return "selected_source_absent" as const; + const profile = object(run.runnerProfileJson), recorded = object(profile[NATIVE_HARNESS_BACKUP_SOURCE_ABSENT_KEY]); + const scopes: Scopes = recorded.schema === SCHEMA ? { ...object(recorded.scopes) } as Scopes : {}; + const previous = scopes[input.scopeDigest]?.manifestSha256s ?? []; + if (manifests.every(manifest => previous.includes(manifest))) return "source_gone_recorded" as const; + const recordedAt = new Date(clock.now).toISOString(); + scopes[input.scopeDigest] = { manifestSha256s: [...new Set([...previous, ...manifests])].sort(), recordedAt }; + await tx.update(heartbeatRuns).set({ runnerProfileJson: { ...profile, [NATIVE_HARNESS_BACKUP_SOURCE_ABSENT_KEY]: { schema: SCHEMA, scopes } } }) + .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, input.companyId))); + await logActivity(tx, { companyId: input.companyId, actorType: "system", actorId: "native-harness-preservation", + action: "native_harness_backup_source_gone_recorded", entityType: "heartbeat_run", entityId: run.id, + agentId: run.agentId, runId: run.id, details: { scopeDigest: input.scopeDigest, manifestSha256s: manifests, + selectedSessionId: input.selectedSessionId } }, publications); + return "source_gone_recorded" as const; + }).catch((error: { code?: string; cause?: { code?: string } }) => { + input.signal.throwIfAborted(); + if ((error?.code ?? error?.cause?.code) === "55P03") return "selected_source_busy" as const; + throw error; + }); + for (const publication of publications) publishActivity(publication); + return outcome; +} diff --git a/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts b/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts index af570f736ee..8d28f769c8f 100644 --- a/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts +++ b/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts @@ -1,8 +1,8 @@ import { createHash, randomUUID } from "node:crypto"; import { cp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { eq } from "drizzle-orm"; -import { agentTaskSessions, createDb, environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db"; +import { and, eq, inArray } from "drizzle-orm"; +import { activityLog, agentTaskSessions, createDb, environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db"; import { afterEach, expect, it, vi } from "vitest"; import { describeEmbeddedPostgres, nativeRestartFixture } from "../../__tests__/helpers/native-restart.js"; import { createLocalDiskStorageProvider } from "../../storage/local-disk-provider.js"; @@ -10,7 +10,7 @@ import { createStorageService } from "../../storage/service.js"; import { buildNativeHarnessBackupManifest } from "./native-session-executor.js"; import { createNativeHarnessBackupStamp, verifyNativeHarnessBackupStampAsync } from "./native-harness-backup-stamp.js"; import { removeNativeHarnessBackup } from "./native-harness-backup-cleanup.js"; -import { prestageNativeHarnessBackups } from "./native-harness-backup-migration.js"; +import { migrateNativeHarnessBackups, prestageNativeHarnessBackups } from "./native-harness-backup-migration.js"; import { persistNativeHarnessBackup, restoreDurableNativeHarnessBackup } from "./native-harness-backup-storage.js"; import { settledNativeHarnessBackupOwner } from "./native-harness-preservation-source.js"; import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js"; @@ -161,6 +161,71 @@ describeEmbeddedPostgres("online preservation of settled legacy harness backups" expect(absent.deferred.selected_source_absent).toBe((present.deferred.selected_source_absent ?? 0) + 1); expect(absent).toMatchObject({ inspected: 0, published: 0 }); }); + it.each(["online", "offline"])("records a settled selected session whose backup source is gone and moves %s", async path => { + const f = await fixture(), signal = AbortSignal.timeout(15_000); + await f.db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }) + .where(inArray(heartbeatRuns.status, ["queued", "running"])); + await f.db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); + const baseline = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + await f.db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.runId)); + await rm(join(f.base, f.scopeDigest), { recursive: true }); + if (path === "online") { + const outcomes: string[] = []; + const result = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal, onOutcome: outcome => outcomes.push(outcome) }); + expect(result.sourceGone).toBe(1); + expect(result.deferred.selected_source_absent).toBe(baseline.deferred.selected_source_absent); + expect(outcomes.filter(outcome => outcome === "source_gone_recorded")).toHaveLength(1); + } else await migrateNativeHarnessBackups(f.db, { storage: f.storage, writersStopped: true, signal }); + const [run] = await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.status).toBe("failed"); + expect(run.runnerProfileJson?.nativeHarnessBackupSourceAbsent).toMatchObject({ + scopes: { [f.scopeDigest]: { manifestSha256s: [f.stamp.manifestSha256] } } }); + expect(await f.db.select().from(activityLog).where(and(eq(activityLog.runId, f.runId), + eq(activityLog.action, "native_harness_backup_source_gone_recorded")))).toHaveLength(1); + expect(await f.db.select().from(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId))).toHaveLength(1); + expect((await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal })).sourceGone).toBeUndefined(); + const newer = `sha256:${"e".repeat(64)}`; + await f.db.insert(environmentLeases).values({ companyId: f.companyId, issueId: f.issueId, heartbeatRunId: f.runId, + providerLeaseId: randomUUID(), status: "expired", metadata: { nativeHarnessBackup: { ...f.stamp, manifestSha256: newer } } }); + expect((await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal })).sourceGone).toBe(1); + const [again] = await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(again.runnerProfileJson?.nativeHarnessBackupSourceAbsent).toMatchObject({ + scopes: { [f.scopeDigest]: { manifestSha256s: [f.stamp.manifestSha256, newer].sort() } } }); + }); + it.each([ + ["active", "selected_source_absent"], + ["retiring", "selected_source_retiring"], + ["previous", "selected_source_unsettled"], + ])("keeps a gone backup source blocked while the session is %s", async (kind, outcome) => { + const f = await fixture(), signal = AbortSignal.timeout(15_000); + const baseline = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + await f.db.delete(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest)); + await rm(join(f.base, f.scopeDigest), { recursive: true }); + if (kind === "active") await f.db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); + else await mkdir(join(f.base, f.scopeDigest, "failover-backups", kind === "previous" ? "previous" : `.retiring-${randomUUID()}`), { recursive: true }); + const result = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + expect(result.deferred[outcome]).toBe((baseline.deferred[outcome] ?? 0) + 1); + expect(result.sourceGone).toBeUndefined(); + const [run] = await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.runnerProfileJson?.nativeHarnessBackupSourceAbsent).toBeUndefined(); + }); + it("names a gone backup source whose run row is busy and records it on the next pass", async () => { + const f = await fixture(), signal = AbortSignal.timeout(15_000); + const baseline = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + await f.db.delete(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest)); + await rm(join(f.base, f.scopeDigest), { recursive: true }); + let release!: () => void, entered!: () => void; + const gate = new Promise(resolve => { release = resolve; }), ready = new Promise(resolve => { entered = resolve; }); + const holder = f.db.transaction(async tx => { + await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)).for("update"); entered(); await gate; + }); + try { + await ready; + const busy = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + expect(busy.deferred.selected_source_busy).toBe((baseline.deferred.selected_source_busy ?? 0) + 1); + } finally { release(); await holder; } + expect((await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal })).sourceGone).toBe(1); + }); it("stops the selected-source scan once the pass is cancelled", async () => { const f = await fixture(), controller = new AbortController(); await rm(join(f.base, f.scopeDigest), { recursive: true }); diff --git a/server/src/services/online-durable-data-migration.ts b/server/src/services/online-durable-data-migration.ts index e22fc7ae0ff..269c14eb58f 100644 --- a/server/src/services/online-durable-data-migration.ts +++ b/server/src/services/online-durable-data-migration.ts @@ -282,6 +282,7 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, case "native_harness_backups": { await owners.nativeHarnessBackups(db, { storage, signal, onOutcome: outcome => { if (outcome === "published") add(counts, "nativeHarnessBackups"); + else if (outcome === "source_gone_recorded") add(counts, "nativeHarnessBackupSourcesGone"); else if (outcome !== "current") defer(`native_harness:${outcome}`); } }); return null;