From 949bc3765c28df63aadfd0a22807bad75ae5b5ca Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:51:32 -0600 Subject: [PATCH] fix(cloud): preserve a settled harness backup whose session is not selected, as offline does (#22647) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A hosted server copies its Runner harness backups to shared storage before it moves to a volume-free shape > - The online pass copies a settled backup only when exactly one task session selects the backup's native session > - Some stacks stay blocked with `native_harness:source_session_not_selected`, but the offline migration publishes the same backup > - A selected session whose backup source is not on the disk is reported with no code at all > - This pull request applies the offline outcome online with a selection fence, and names the missing-source case > - The benefit is that these stacks can move, and the native harness blocker always says why it remains ## Linked Issues or Issue Description Refs #19715, #22294 **What happened?** On staging, two stacks stay ineligible with `native_harness_backups_require_migration`. Each online pass defers one backup as `native_harness:source_session_not_selected`. That code means that no task session, or more than one, points at the backup's native session. **Expected behavior** The online pass gives a settled backup the same outcome as the offline migration. The offline migration publishes the backup whether or not a session selects it. **Steps to reproduce** 1. Keep a sealed backup of a failed native run with a settled coordinator and a verified lease stamp. 2. Delete the task session that selects it (or add a second one for the same native session). 3. Run the online pre-copy. It defers the backup as `source_session_not_selected`. The offline migration publishes it. **Additional context** The selection check exists so that publication does not race a change of the selected session. It does not need exactly one selection for that. ## What Changed - The settled-source owner records the exact set of task sessions that select the native session: none, one or several. Publication rechecks the same set under a share lock. A changed selection keeps the source local (`source_changed`), as before. The `session_not_selected` reason is removed. - The run, coordinator, task, lease, finalization lock and payload checks do not change. - After the source walk, the pre-copy lists the selected sessions that still need a backup. A selected scope with no source on this disk is reported as `selected_source_absent`. Before, it produced no outcome. ## Verification - Red (embedded PostgreSQL, real files): `cd server && npx vitest run src/services/native-runtime/native-harness-online-preservation.integration.test.ts` failed 4 new tests: unselected and ambiguous sources were deferred, and a missing selected source produced no outcome. - Green: the same file passes (20 tests). New tests show that an unselected or ambiguous source publishes, the run and task sessions do not change, the backup restores the exact bytes, and a selection that appears before publication keeps the receipt pending. - `native-harness-backup-storage.integration.test.ts`: the former `source_session_not_selected` expectation now expects publication by the settled-source owner (activity `native_harness_backup_preserved`), not by the offline owner. - `npx vitest run` of all 8 files that use these owners (startup gate, prestage command, filesystem independence, obligations, storage, online preservation): 240 tests pass. - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify` result is in a comment below. ## Risks - A settled backup of an unselected session now moves to shared storage online. The offline migration already does this, and the source files stay on the disk. - The pre-copy now runs the obligation scan once after the source walk. This is the same scan that the eligibility read runs. - Pass deferral codes change: `native_harness:source_session_not_selected` is gone, and `native_harness:selected_source_absent` is new. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../native-harness-backup-migration.ts | 35 +++++++-- ...harness-backup-storage.integration.test.ts | 11 ++- ...ss-online-preservation.integration.test.ts | 73 ++++++++++++++++++- .../native-harness-preservation-source.ts | 33 ++++----- 4 files changed, 120 insertions(+), 32 deletions(-) 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 1afac2805a8..685245aafd9 100644 --- a/server/src/services/native-runtime/native-harness-backup-migration.ts +++ b/server/src/services/native-runtime/native-harness-backup-migration.ts @@ -15,8 +15,15 @@ import { hasValidNativeHarnessFilesystemIndependence } from "./native-harness-fi const MAX_PARALLEL_INDEPENDENCE_CHECKS = 4; export async function hasLocalNativeHarnessObligations(db: Db): Promise { + for await (const _ of localNativeHarnessObligationScopes(db)) return true; + return false; +} + +async function* localNativeHarnessObligationScopes(db: Db, all = false, signal?: AbortSignal, + skip: ReadonlySet = new Set()): AsyncGenerator { let afterSession = "", afterScope = ""; for (;;) { + signal?.throwIfAborted(); const rows = await db.execute<{ company_id: string; selected_session_id: string; scope_digest: string; has_receipt: boolean }>(sql`with selected_sessions as materialized ( select s.company_id, s.id, s.last_run_id, r.native_issue_id, r.native_session_id from agent_task_sessions s @@ -33,20 +40,24 @@ export async function hasLocalNativeHarnessObligations(db: Db): Promise and b.scope_digest = e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' and b.status = 'current') and (s.id::text, coalesce(e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256', '')) > (${afterSession}, ${afterScope}) order by selected_session_id, scope_digest limit 100`); - let next = 0, invalid = false; + let next = 0, failed = false; + const invalid: string[] = []; const checked = await Promise.allSettled(Array.from({ length: Math.min(MAX_PARALLEL_INDEPENDENCE_CHECKS, rows.length) }, async () => { - while (!invalid && next < rows.length) { + while (!failed && (all || !invalid.length) && next < rows.length) { + signal?.throwIfAborted(); const row = rows[next++]!; + if (skip.has(row.scope_digest)) continue; try { if (!row.has_receipt || !await hasValidNativeHarnessFilesystemIndependence(db, { companyId: row.company_id, selectedSessionId: row.selected_session_id, scopeDigest: row.scope_digest, - })) invalid = true; - } catch (error) { invalid = true; throw error; } + })) invalid.push(row.scope_digest); + } catch (error) { failed = true; throw error; } } })); for (const result of checked) if (result.status === "rejected") throw result.reason; - if (invalid) return true; - if (rows.length < 100) return false; + signal?.throwIfAborted(); + yield* invalid; + if (rows.length < 100) return; afterSession = rows.at(-1)!.selected_session_id; afterScope = rows.at(-1)!.scope_digest; } } @@ -183,11 +194,13 @@ export async function migrateNativeHarnessBackups(db: Db, input: { } export async function prestageNativeHarnessBackups(db: Db, input: { storage: StorageService; signal: AbortSignal; onOutcome?: (outcome: string) => void }) { + const visited = new Set(); const deferSource = (scopeDigest: string, reason: string, outcome: string) => { console.warn(JSON.stringify({ schema: "paperclip.native-harness-prestage-source.v1", scopeDigest, reason })); return outcome; }; const outcomes = await mapSources({ ...input, concurrency: 1, onResult: (outcome: string) => input.onOutcome?.(outcome), unavailableSource: (error, scopeDigest) => { + visited.add(scopeDigest); if (error instanceof NativeHarnessBackupSourceError || error instanceof Error && error.message === "native_harness_migration_source_unsettled") { return deferSource(scopeDigest, error.message, "source_unavailable"); } @@ -197,6 +210,7 @@ export async function prestageNativeHarnessBackups(db: Db, input: { storage: Sto return undefined; } }, async (source, signal) => { signal.throwIfAborted(); + visited.add(source.scopeDigest); const run = await sourceRun(db, source).catch(error => { if (error instanceof Error && error.message === "native_harness_migration_binding_mismatch") return null; throw error; @@ -264,7 +278,16 @@ 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)) { + input.signal.throwIfAborted(); + if (visited.has(scopeDigest)) continue; + visited.add(scopeDigest); + absent++; + input.onOutcome?.("selected_source_absent"); + } const counts = { inspected: outcomes.length, published: 0, current: 0, deferred: {} as Record }; + if (absent) counts.deferred.selected_source_absent = 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-storage.integration.test.ts b/server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts index 65b648d3b84..468250efab4 100644 --- a/server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts +++ b/server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts @@ -3,7 +3,7 @@ import { createHash, randomUUID } from "node:crypto"; import { chmod, mkdir, readFile, rename, stat, symlink, readlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { and, eq, inArray } from "drizzle-orm"; -import { agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, nativeRunResults, +import { activityLog, agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, nativeRunResults, nativeProviderArtifacts, nativeProviderArtifactReferences, nativeRunnerCheckpoints } from "@paperclipai/db"; import { afterEach, expect, it, vi } from "vitest"; import { describeEmbeddedPostgres, nativeRestartFixture } from "../../__tests__/helpers/native-restart.js"; @@ -609,11 +609,14 @@ describeEmbeddedPostgres("durable native provider backups", () => { expect(put).not.toHaveBeenCalled(); expect(await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest))).toEqual([]); }); - it("defers failed history without treating pre-copy as offline authority", async () => { + it("preserves settled failed history of an unselected session through the settled-source owner, never offline authority", async () => { const [f] = await offlineFixtures(1); expect(await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) })) - .toEqual({ inspected: 1, published: 0, current: 0, deferred: { source_session_not_selected: 1 } }); - expect(await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest))).toEqual([]); + .toEqual({ inspected: 1, published: 1, current: 0, deferred: {} }); + expect((await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest)))[0].status).toBe("current"); + const [preserved] = await f.db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), + eq(activityLog.action, "native_harness_backup_preserved"), eq(activityLog.runId, f.runId))); + expect(preserved).toMatchObject({ actorId: "native-harness-preservation", details: { scopeDigest: f.scopeDigest, originalFilesRetained: true } }); }); it("defers a source being replaced online while offline migration still refuses it", async () => { const f = await inactiveFixture(); 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 2a22ca49cbf..af570f736ee 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,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { cp, mkdir, readFile, symlink, writeFile } from "node:fs/promises"; +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"; @@ -15,6 +15,7 @@ import { persistNativeHarnessBackup, restoreDurableNativeHarnessBackup } from ". import { settledNativeHarnessBackupOwner } from "./native-harness-preservation-source.js"; import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js"; import * as backupStamp from "./native-harness-backup-stamp.js"; +import * as independence from "./native-harness-filesystem-independence.js"; import { nativeHarnessPrestageDatabaseUrl } from "../../maintenance/native-harness-prestage-runtime.js"; describeEmbeddedPostgres("online preservation of settled legacy harness backups", () => { @@ -104,17 +105,81 @@ describeEmbeddedPostgres("online preservation of settled legacy harness backups" ["scheduled_retry", "source_run_active"], ["failed_unfinished", "source_run_unfinished"], ["coordinator_missing", "source_coordinator_missing"], - ["session_not_selected", "source_session_not_selected"], ])("names why a %s source stays local", async (kind, outcome) => { const f = await fixture(), put = vi.spyOn(f.storage, "putFile"); if (kind === "running" || kind === "scheduled_retry") await f.db.update(heartbeatRuns).set({ status: kind, finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); if (kind === "failed_unfinished") await f.db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); if (kind === "coordinator_missing") await f.db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); - if (kind === "session_not_selected") await f.db.delete(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); expect(await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) })) .toMatchObject({ published: 0, deferred: { [outcome]: 1 } }); expect(put).not.toHaveBeenCalled(); }); + it.each(["unselected", "ambiguous"])("preserves a settled source whose session is %s, as the offline migration does", async selection => { + const f = await fixture(); + if (selection === "unselected") await f.db.delete(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); + else await f.db.insert(agentTaskSessions).values({ companyId: f.companyId, agentId: environment.current.agentId, + adapterType: "paperclip_runner", taskKey: `${f.issueId}:second`, lastRunId: f.runId }); + const sessions = await f.db.select().from(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); + const [before] = await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + const result = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) }); + expect(result.published).toBe(1); + vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", join(environment.current.runtimeRoot, randomUUID())); + const leftover = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) }); + vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", f.base); + expect(leftover).toMatchObject({ inspected: 0, published: 0 }); + expect(result.deferred).toEqual(leftover.deferred); + expect((await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest)))[0].status).toBe("current"); + expect((await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(before); + expect(await f.db.select().from(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId))).toEqual(sessions); + expect(await readFile(join(f.root, "codex-home", "sessions", "history.json"), "utf8")).toBe(JSON.stringify(f.saved)); + const restored = join(environment.current.runtimeRoot, randomUUID()); homes.push(restored); + expect(await restoreDurableNativeHarnessBackup({ ...f, backupRoot: restored })).toBe(true); + expect(JSON.parse(await readFile(join(restored, "current", "codex-home", "sessions", "history.json"), "utf8"))).toEqual(f.saved); + }); + it("keeps the source local when its session selection changes before publication", async () => { + const f = await fixture(), put = f.storage.putFile.bind(f.storage); + await f.db.delete(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); + vi.spyOn(f.storage, "putFile").mockImplementation(async input => { + const result = await put(input); + await f.db.insert(agentTaskSessions).values({ companyId: f.companyId, agentId: environment.current.agentId, + adapterType: "paperclip_runner", taskKey: f.issueId, lastRunId: f.runId }); + return result; + }); + expect(await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) })) + .toMatchObject({ published: 0, deferred: { source_changed: 1 } }); + expect(await f.db.select({ status: nativeHarnessBackups.status }).from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest))) + .toEqual([{ status: "pending" }]); + }); + it("names a selected session whose backup source is not on this disk", async () => { + const f = await fixture(), signal = AbortSignal.timeout(15_000); + await f.db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); + const present = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + expect(present.deferred.source_run_active).toBe(1); + await rm(join(f.base, f.scopeDigest), { recursive: true }); + const absent = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + expect(absent.deferred.source_run_active).toBeUndefined(); + expect(absent.deferred.selected_source_absent).toBe((present.deferred.selected_source_absent ?? 0) + 1); + expect(absent).toMatchObject({ inspected: 0, published: 0 }); + }); + 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 }); + const [run] = await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + await f.db.update(heartbeatRuns).set({ runnerProfileJson: { ...run.runnerProfileJson, nativeHarnessFilesystemIndependence: {} } }) + .where(eq(heartbeatRuns.id, f.runId)); + const check = vi.spyOn(independence, "hasValidNativeHarnessFilesystemIndependence"); + const execute = f.db.execute.bind(f.db); + const scan = vi.spyOn(f.db, "execute").mockImplementation(((query: Parameters[0]) => { + controller.abort(new Error("budget spent")); + return execute(query); + }) as typeof f.db.execute); + const outcomes: string[] = []; + await expect(prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: controller.signal, + onOutcome: outcome => outcomes.push(outcome) })).rejects.toThrow("budget spent"); + expect(scan).toHaveBeenCalledTimes(1); + expect(check).not.toHaveBeenCalled(); + expect(outcomes).toEqual([]); + }); it("respects the physical advisory lock while unrelated work stays active", async () => { const f = await fixture(), put = vi.spyOn(f.storage, "putFile"); let release!: () => void, entered!: () => void; @@ -185,7 +250,7 @@ describeEmbeddedPostgres("online preservation of settled legacy harness backups" const good = await fixture({ base: bad.base, scopeId: "a" }); expect(bad.scopeDigest < good.scopeDigest).toBe(true); expect(await prestageNativeHarnessBackups(bad.db, { storage: bad.storage, signal: AbortSignal.timeout(15_000) })) - .toMatchObject({ inspected: 2, published: 1, deferred: { source_changed: 1 } }); + .toMatchObject({ published: 1, deferred: { source_changed: 1 } }); expect(await bad.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, bad.scopeDigest))).toEqual([]); expect((await good.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, good.scopeDigest)))[0].status).toBe("current"); }); diff --git a/server/src/services/native-runtime/native-harness-preservation-source.ts b/server/src/services/native-runtime/native-harness-preservation-source.ts index 8564ba6e101..2495d547d4c 100644 --- a/server/src/services/native-runtime/native-harness-preservation-source.ts +++ b/server/src/services/native-runtime/native-harness-preservation-source.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; import { resolve } from "node:path"; -import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { and, asc, eq, inArray, or, sql } from "drizzle-orm"; import { agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db"; import { adapterExecutionControls } from "../adapter-execution-control.js"; import { nativeSha256 } from "./canonical.js"; @@ -16,7 +16,7 @@ export type SettledNativeHarnessBackupOwner = { kind: "settled_native_harness_backup"; companyId: string; issueId: string; agentId: string; runId: string; sessionId: string; runnerInstanceId: string; scopeDigest: string; root: string; manifestSha256: string; - selectedSessionId: string; selectedLastRunId: string; sourceLeaseId: string; providerLeaseId: string; + selections: Array<{ id: string; lastRunId: string | null }>; sourceLeaseId: string; providerLeaseId: string; runDigest: string; coordinatorDigest: string; leaseDigest: string; }; const runDigest = (run: Run) => nativeSha256({ status: run.status, finishedAt: run.finishedAt?.toISOString(), @@ -31,6 +31,14 @@ const leaseDigest = (row: Lease) => nativeSha256({ heartbeatRunId: row.heartbeat const settled = (row: Coordinator) => row.leaseOwner === null && row.nextAttemptAt === null && (row.phase === "terminal_failure" || row.phase === "committed" && row.resultId !== null); const fail = (): never => { throw new Error("native_harness_preservation_source_unsettled"); }; +const sessionSelections = (db: Db, input: { companyId: string; agentId: string; issueId: string; sessionId: string }) => + db.select({ id: agentTaskSessions.id, lastRunId: agentTaskSessions.lastRunId }).from(agentTaskSessions).where(and( + eq(agentTaskSessions.companyId, input.companyId), eq(agentTaskSessions.agentId, input.agentId), + eq(agentTaskSessions.adapterType, "paperclip_runner"), + sql`exists (select 1 from ${heartbeatRuns} where ${heartbeatRuns.id} = ${agentTaskSessions.lastRunId} + and ${heartbeatRuns.companyId} = ${agentTaskSessions.companyId} and ${heartbeatRuns.agentId} = ${agentTaskSessions.agentId} + and ${heartbeatRuns.nativeIssueId} = ${input.issueId} and ${heartbeatRuns.nativeSessionId} = ${input.sessionId})`, + )).orderBy(asc(agentTaskSessions.id)); /** Copy sealed historical files without certifying provider termination, changing * a failed run, or taking an expired coordinator. Every publication rechecks it. */ @@ -38,17 +46,12 @@ export async function settledNativeHarnessBackupOwner(db: Db, input: { companyId: string; issueId: string; runId: string; sessionId: string; runnerInstanceId: string; scopeDigest: string; root: string; manifestSha256: string; providerLeaseId: string; signal: AbortSignal; }): Promise<{ owner: SettledNativeHarnessBackupOwner; reason?: never } - | { owner: null; reason: "coordinator_missing" | "coordinator_unsettled" | "session_not_selected" | "lease_missing" }> { + | { owner: null; reason: "coordinator_missing" | "coordinator_unsettled" | "lease_missing" }> { const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId))); const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.issueId, input.issueId), eq(nativeRunFinalizations.runId, input.runId))); if (!run || !coordinator || !settled(coordinator)) return { owner: null, reason: run && coordinator ? "coordinator_unsettled" : "coordinator_missing" }; - const selected = await db.select({ id: agentTaskSessions.id, lastRunId: agentTaskSessions.lastRunId }).from(agentTaskSessions) - .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, agentTaskSessions.companyId), eq(heartbeatRuns.agentId, agentTaskSessions.agentId), - eq(heartbeatRuns.id, agentTaskSessions.lastRunId))).where(and(eq(agentTaskSessions.companyId, input.companyId), - eq(agentTaskSessions.agentId, run.agentId), eq(agentTaskSessions.adapterType, "paperclip_runner"), - eq(heartbeatRuns.nativeIssueId, input.issueId), eq(heartbeatRuns.nativeSessionId, input.sessionId))).limit(2); - if (selected.length !== 1 || !selected[0]!.lastRunId) return { owner: null, reason: "session_not_selected" }; + const selections = await sessionSelections(db, { ...input, agentId: run.agentId }); const leases = await db.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.issueId, input.issueId), eq(environmentLeases.providerLeaseId, input.providerLeaseId), sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'manifestSha256' = ${input.manifestSha256}`)); @@ -57,7 +60,7 @@ export async function settledNativeHarnessBackupOwner(db: Db, input: { const owner: SettledNativeHarnessBackupOwner = { kind: "settled_native_harness_backup", companyId: input.companyId, issueId: input.issueId, agentId: run.agentId, runId: input.runId, sessionId: input.sessionId, runnerInstanceId: input.runnerInstanceId, scopeDigest: input.scopeDigest, root: input.root, manifestSha256: input.manifestSha256, - selectedSessionId: selected[0]!.id, selectedLastRunId: selected[0]!.lastRunId, + selections, sourceLeaseId: lease.id, providerLeaseId: input.providerLeaseId, runDigest: runDigest(run), coordinatorDigest: coordinatorDigest(coordinator), leaseDigest: leaseDigest(lease) }; await db.transaction(tx => assertSettledNativeHarnessBackupSource(tx as unknown as Db, owner, input.signal)); @@ -74,18 +77,12 @@ export async function assertSettledNativeHarnessBackupSource(db: Db, owner: Sett 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 || !settled(coordinator) || coordinatorDigest(coordinator) !== owner.coordinatorDigest) fail(); - const [selection] = await db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, owner.companyId), - eq(agentTaskSessions.agentId, owner.agentId), eq(agentTaskSessions.id, owner.selectedSessionId), - eq(agentTaskSessions.adapterType, "paperclip_runner"), - eq(agentTaskSessions.lastRunId, owner.selectedLastRunId))).for("share"); - const [selectedRun] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId), - eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.id, owner.selectedLastRunId), - eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId))); + const selections = await sessionSelections(db, owner).for("share"); const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.id, owner.runId), eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId), eq(heartbeatRuns.runnerInstanceId, owner.runnerInstanceId), eq(heartbeatRuns.runtimeMode, "native"))).for("share"); const [clock] = await db.execute<{ now: Date }>(sql`select clock_timestamp() as now`); - if (!selection || !selectedRun || !run?.finishedAt || !["failed", "cancelled", "interrupted", "timed_out"].includes(run.status) + if (JSON.stringify(selections) !== JSON.stringify(owner.selections) || !run?.finishedAt || !["failed", "cancelled", "interrupted", "timed_out"].includes(run.status) || run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date(clock.now) || adapterExecutionControls.has(run.id) || run.runnerProfileJson?.nativeWorkspaceFinalizationOwner != null || runDigest(run) !== owner.runDigest) fail();