diff --git a/server/src/services/native-runtime/native-controller-archive-source.ts b/server/src/services/native-runtime/native-controller-archive-source.ts index 43f3b604002..c9fc32f244f 100644 --- a/server/src/services/native-runtime/native-controller-archive-source.ts +++ b/server/src/services/native-runtime/native-controller-archive-source.ts @@ -17,6 +17,9 @@ export type SettledControllerArchiveOwner = { filesystemIndependence?: { source: OriginalHarnessVolumeCapability; scopeDigest: string; factsDigest: string }; }; const fileDigest = (value: string) => createHash("sha256").update(value).digest("hex"); +export class NativeControllerArchiveSourceUnsettled extends Error { + constructor(readonly state: string) { super("native_controller_archive_source_unsettled"); } +} export function nativeControllerArchiveProfileDigest(value: unknown) { const profile = value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; @@ -32,22 +35,24 @@ export function nativeControllerArchiveCoordinatorDigest(value: { } export async function assertSettledControllerArchiveSource(db: Db, owner: SettledControllerArchiveOwner) { - function fail(): never { throw new Error("native_controller_archive_source_unsettled"); } - if (owner.controllerDigest === null && !owner.filesystemIndependence) fail(); + function fail(state: string): never { throw new NativeControllerArchiveSourceUnsettled(state); } + if (owner.controllerDigest === null && !owner.filesystemIndependence) fail("controller_fingerprint_missing"); if (owner.filesystemIndependence) { await assertOriginalHarnessVolumeSource(owner.filesystemIndependence.source); await (await import("./native-harness-filesystem-independence.js")).assertNativeHarnessFilesystemArchiveSource(db, owner); } await db.execute(sql`set local lock_timeout = '1s'`); - if (!await tryLockNativeWorkspaceFinalization(db, owner)) fail(); + if (!await tryLockNativeWorkspaceFinalization(db, owner)) fail("finalization_busy"); const [task] = await db.select().from(issues).where(and(eq(issues.companyId, owner.companyId), eq(issues.id, owner.issueId))).for("update"); - if (!task || task.executionRunId || task.checkoutRunId) fail(); + if (!task || task.executionRunId || task.checkoutRunId) fail("task_active"); const [coordinator] = await db.select().from(nativeRunFinalizations).where(and( eq(nativeRunFinalizations.companyId, owner.companyId), eq(nativeRunFinalizations.issueId, owner.issueId), eq(nativeRunFinalizations.runId, owner.runId))).for("update"); - if (!coordinator || coordinator.leaseOwner || coordinator.nextAttemptAt - || !(coordinator.phase === "terminal_failure" || coordinator.phase === "committed" && coordinator.resultId) - || nativeControllerArchiveCoordinatorDigest(coordinator) !== owner.coordinatorDigest) fail(); + if (!coordinator) fail("coordinator_missing"); + if (coordinator.leaseOwner) fail("coordinator_leased"); + if (coordinator.nextAttemptAt) fail("coordinator_retry_scheduled"); + if (!(coordinator.phase === "terminal_failure" || coordinator.phase === "committed" && coordinator.resultId)) fail("coordinator_unsettled"); + if (nativeControllerArchiveCoordinatorDigest(coordinator) !== owner.coordinatorDigest) fail("coordinator_changed"); const [selection] = await db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.id, owner.selectedSessionId), eq(agentTaskSessions.companyId, owner.companyId), eq(agentTaskSessions.agentId, owner.agentId), eq(agentTaskSessions.lastRunId, owner.selectedLastRunId))).for("share"); @@ -57,20 +62,21 @@ export async function assertSettledControllerArchiveSource(db: Db, owner: Settle const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, owner.runId), eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId), eq(heartbeatRuns.runtimeMode, "native"))).for("share"); - if (!selection || !selectedRun || !run?.finishedAt + if (!selection || !selectedRun) fail("session_selection_changed"); + if (!run?.finishedAt || (owner.filesystemIndependence ? !["failed", "succeeded"].includes(run.status) || run.status === "succeeded" && (coordinator.phase !== "committed" || !coordinator.resultId) : run.status !== "failed") - || nativeControllerArchiveProfileDigest(run.runnerProfileJson) !== owner.profileDigest) fail(); + || nativeControllerArchiveProfileDigest(run.runnerProfileJson) !== owner.profileDigest) fail("run_changed"); const [active] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId), inArray(heartbeatRuns.status, ["queued", "running"]), or(eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.issueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId)))).limit(1); - if (active) fail(); + if (active) fail("turn_active"); const selected = await findNativeSessionResumeRun(db, { companyId: owner.companyId, agentId: owner.agentId, issueId: owner.issueId, normalizedSessionId: owner.sessionId, beforeCreatedAt: selectedRun.createdAt, includeProgressBarrier: true }); - if (!selected || selected.id !== owner.runId || nativeControllerArchiveProfileDigest(selected.runnerProfileJson) !== owner.profileDigest) fail(); + if (!selected || selected.id !== owner.runId || nativeControllerArchiveProfileDigest(selected.runnerProfileJson) !== owner.profileDigest) fail("resume_source_changed"); const material = await readLegacyNativeControllerArchiveDigests(selected); if ((material.controllerDigest ?? null) !== owner.controllerDigest - || (material.supervisorDigest ?? null) !== owner.supervisorDigest) fail(); + || (material.supervisorDigest ?? null) !== owner.supervisorDigest) fail("controller_files_changed"); } export async function archiveSettledFailedNativeController(db: Db, input: { @@ -84,7 +90,7 @@ export async function archiveSettledFailedNativeController(db: Db, input: { if (material.controller === undefined) return "source_already_absent" as const; const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, selected.companyId), eq(nativeRunFinalizations.issueId, selected.issueId), eq(nativeRunFinalizations.runId, source.id))); - if (!coordinator) throw new Error("native_controller_archive_source_unsettled"); + if (!coordinator) throw new NativeControllerArchiveSourceUnsettled("coordinator_missing"); const owner: SettledControllerArchiveOwner = { kind: "settled_controller_archive", companyId: selected.companyId, issueId: selected.issueId, agentId: selected.agentId, runId: source.id, sessionId: selected.sessionId, selectedSessionId: selected.id, selectedLastRunId: selected.lastRunId, diff --git a/server/src/services/native-runtime/native-controller-migration.integration.test.ts b/server/src/services/native-runtime/native-controller-migration.integration.test.ts index 84984a33168..f8731237992 100644 --- a/server/src/services/native-runtime/native-controller-migration.integration.test.ts +++ b/server/src/services/native-runtime/native-controller-migration.integration.test.ts @@ -385,10 +385,14 @@ describeEmbeddedPostgres.each(["volume_free_owner", "eligibility_unreadable", "a status: "queued", runtimeMode: "native" }); return result; }); - const counts = await prestageNativeControllers(f.db, { storage, signal: AbortSignal.timeout(30_000) }); + const outcomes: string[] = []; + const counts = await prestageNativeControllers(f.db, { storage, signal: AbortSignal.timeout(30_000), onOutcome: outcome => outcomes.push(outcome) }); if (["archive_online_owned", "archive_online_changed", "archive_online_active", "archive_online_foreign"].includes(scenario)) { expect(counts.archivedFailed).toBe(0); expect(counts.deferred[scenario === "archive_online_foreign" ? "artifact_binding" : "archive_source_unsettled"]).toBe(1); + const state = { archive_online_owned: "coordinator_leased", archive_online_changed: "controller_files_changed", + archive_online_active: "turn_active" }[scenario as "archive_online_owned"]; + if (state) expect(outcomes).toEqual(["archive_source_unsettled", `archive_source_unsettled:${state}`]); if (["archive_online_owned", "archive_online_changed"].includes(scenario)) expect(await hasLocalNativeControllerObligations(f.db, storage)).toBe(true); const backups = await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.runId, f.runId)); expect(backups.some(backup => backup.status === "current")).toBe(false); @@ -448,8 +452,11 @@ describeEmbeddedPostgres.each(["volume_free_owner", "eligibility_unreadable", "a await f.db.update(agentTaskSessions).set({ id: "00000000-0000-4000-8000-000000000001" }).where(eq(agentTaskSessions.id, f.session.id)); const next = await fixture(); await settle(next); - const actual = await prestageNativeControllers(f.db, { signal: AbortSignal.timeout(30_000) }); + const outcomes: string[] = []; + const actual = await prestageNativeControllers(f.db, { signal: AbortSignal.timeout(30_000), onOutcome: outcome => outcomes.push(outcome) }); expect(actual).toMatchObject({ inspected: 2, imported: 1, deferred: { artifact_unproven: 1 } }); + const [source] = await f.db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(outcomes).toContain(`artifact_unproven:${source.status}_run`); expect(await loadNativeRunnerCheckpoint(f.db, { companyId: f.companyId, issueId: f.issueId, runId: f.runId })).toBeNull(); expect(await loadNativeRunnerCheckpoint(f.db, { companyId: next.companyId, issueId: next.issueId, runId: next.runId })).not.toBeNull(); expect(await f.db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId))).toEqual(before); diff --git a/server/src/services/native-runtime/native-controller-migration.ts b/server/src/services/native-runtime/native-controller-migration.ts index 64b38b18f08..f424a59c2da 100644 --- a/server/src/services/native-runtime/native-controller-migration.ts +++ b/server/src/services/native-runtime/native-controller-migration.ts @@ -18,7 +18,7 @@ import type { StorageService } from "../../storage/types.js"; import { durableNativeHarnessStorage } from "./native-harness-backup-storage.js"; import { archiveFailedLegacyNativeController, hasArchivedLegacyNativeController } from "./native-controller-archive.js"; import { redactRunnerApiPayloads } from "./runner-api-log-redaction.js"; -import { archiveSettledFailedNativeController } from "./native-controller-archive-source.js"; +import { archiveSettledFailedNativeController, NativeControllerArchiveSourceUnsettled } from "./native-controller-archive-source.js"; import { nativeControllerSourceDigest } from "./native-controller-source-digest.js"; import { isVolumeFreeControllerStateOwnerEntry, volumeFreeControllerStateOwned } from "./volume-free-controller-state.js"; @@ -402,6 +402,7 @@ function onlineControllerSourceDeferral(error: unknown): string | null { native_controller_migration_artifact_unavailable: "artifact_unavailable", native_controller_archive_source_unsettled: "archive_source_unsettled", }; + if (error instanceof NativeControllerArchiveSourceUnsettled && /^[a-z_]{1,40}$/.test(error.state)) return `archive_source_unsettled:${error.state}`; if (reasons[error.message]) return reasons[error.message]; if (error.message.startsWith("runner_remote_provider_artifact_incompatible:")) return "artifact_incompatible"; if (error instanceof SyntaxError) return "invalid_source_json"; @@ -468,7 +469,7 @@ export async function prestageNativeControllers(db: Db, input: { signal: AbortSi if (error?.code === "55P03" || error?.cause?.code === "55P03") return "source_busy"; throw error; }); - if (source.status === "failed" && ["owner_not_released", "artifact_unproven", "checkpoint_binding", "source_unproven", "artifact_binding"].includes(outcome)) { + if (source.status === "failed" && ["owner_not_released", "artifact_unproven", "checkpoint_binding", "source_unproven", "artifact_binding"].includes(outcome.split(":")[0]!)) { const storage = input.storage ?? durableNativeHarnessStorage(); if (storage) outcome = await archiveSettledFailedNativeController(db, { selected, source, storage, signal: input.signal }).catch(error => { input.signal.throwIfAborted(); @@ -478,7 +479,11 @@ export async function prestageNativeControllers(db: Db, input: { signal: AbortSi throw error; }); } + const [named, detail] = outcome.split(":"); + outcome = named!; + const state = detail ?? (outcome === "artifact_unproven" ? `${source.status}_run` : undefined); input.onOutcome?.(outcome); + if (state) input.onOutcome?.(`${outcome}:${state}`); if (outcome === "archived_failed") counts.archivedFailed++; else if (outcome === "imported" || outcome === "unchanged") counts[outcome]++; else if (outcome === "source_already_absent") counts.sourceAlreadyAbsent++; diff --git a/server/src/services/native-runtime/native-workspace-migration.test.ts b/server/src/services/native-runtime/native-workspace-migration.test.ts new file mode 100644 index 00000000000..edec8908ee7 --- /dev/null +++ b/server/src/services/native-runtime/native-workspace-migration.test.ts @@ -0,0 +1,38 @@ +import { randomUUID } from "node:crypto"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const resume = vi.hoisted(() => ({ run: null as null | { id: string; runnerProfileJson: { nativeExecutionInput: unknown } } })); +vi.mock("./native-session-resume.js", () => ({ findNativeSessionResumeRun: async () => resume.run })); +vi.mock("../../vendor/paperclip-runner/index.js", () => ({ parseNativeExecutionInput: (value: unknown) => value })); + +const { inspectNativeWorkspaceMigration } = await import("./native-workspace-migration.js"); + +describe("native workspace migration identity", () => { + const companyId = randomUUID(), workspaceId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), sessionId = randomUUID(); + let sync: unknown; + const db = { + execute: async () => [{ agentId, issueId, sessionId, createdAt: new Date() }], + select: () => ({ from: () => ({ where: async () => [{ sync }] }) }), + } as never; + const execution = (patch: Record = {}, cwd = "/workspace") => ({ binding: { executionWorkspaceId: workspaceId, + companyId, agentId, issueId, ...patch }, session: { normalizedSessionId: sessionId }, workspace: { cwd } }); + const syncReference = (patch: Record = {}) => ({ schema: "paperclip.native-workspace-sync/v3", state: "finalized", + descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), workspaceId, leaseId: randomUUID(), + providerLeaseId: randomUUID(), remoteCwd: "/home/daytona/workspace", ...patch }); + beforeEach(() => { sync = syncReference(); resume.run = { id: randomUUID(), runnerProfileJson: { nativeExecutionInput: execution() } }; }); + + it("records the continuity of a proven session", async () => { + expect(await inspectNativeWorkspaceMigration(db, { companyId, id: workspaceId })) + .toMatchObject({ remoteCwd: "/home/daytona/workspace", sessions: [{ agentId, issueId, sessionId, logicalCwd: "/workspace" }] }); + }); + it.each([ + ["unsynced", () => { sync = null; }], + ["other_workspace", () => { sync = syncReference({ workspaceId: randomUUID() }); }], + ["rebound", () => { resume.run!.runnerProfileJson.nativeExecutionInput = execution({ executionWorkspaceId: randomUUID() }); }], + ["path_invalid", () => { resume.run!.runnerProfileJson.nativeExecutionInput = execution({}, "workspace"); }], + ])("names a session whose saved identity is %s", async (state, arrange) => { + arrange(); + await expect(inspectNativeWorkspaceMigration(db, { companyId, id: workspaceId })) + .rejects.toThrow(`native_workspace_migration_identity_${state}`); + }); +}); diff --git a/server/src/services/native-runtime/native-workspace-migration.ts b/server/src/services/native-runtime/native-workspace-migration.ts index f60ece66d75..a36e18953a3 100644 --- a/server/src/services/native-runtime/native-workspace-migration.ts +++ b/server/src/services/native-runtime/native-workspace-migration.ts @@ -36,8 +36,10 @@ export async function inspectNativeWorkspaceMigration(db: Db, workspace: Workspa const sync = readNativeWorkspaceSyncReference(saved?.sync); if (execution.binding.executionWorkspaceId !== workspace.id || execution.binding.companyId !== workspace.companyId || execution.binding.agentId !== row.agentId || execution.binding.issueId !== row.issueId - || execution.session.normalizedSessionId !== row.sessionId || !absolute(execution.workspace.cwd) - || !sync || sync.workspaceId !== workspace.id || !absolute(sync.remoteCwd)) throw new Error("native_workspace_migration_identity_unproven"); + || execution.session.normalizedSessionId !== row.sessionId) throw new Error("native_workspace_migration_identity_rebound"); + if (!sync) throw new Error("native_workspace_migration_identity_unsynced"); + if (sync.workspaceId !== workspace.id) throw new Error("native_workspace_migration_identity_other_workspace"); + if (!absolute(execution.workspace.cwd) || !absolute(sync.remoteCwd)) throw new Error("native_workspace_migration_identity_path_invalid"); if (remoteCwd && remoteCwd !== sync.remoteCwd) throw new Error("native_workspace_migration_remote_path_conflict"); remoteCwd = sync.remoteCwd; sessions.push({ sourceRunId: source.id, agentId: row.agentId, issueId: row.issueId, sessionId: row.sessionId, logicalCwd: execution.workspace.cwd });