From cbf67dba0a7bbbb601db16c4e6ce75bc346c6a2e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:38:30 -0600 Subject: [PATCH] fix(cloud): record a selected harness backup whose source is gone instead of blocking the move (#22716) 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 > - Hosted stacks move from a volume to volume-free storage, offline in maintenance or online with no outage > - A stack moves only when no local native harness backup obligation remains > - A selected session can carry a backup stamp whose files are no longer on the volume > - Offline and online both refuse that stack forever, because nothing can copy files that are gone > - This pull request records "backup source was gone" for that session, the same way offline and online, after a locked recheck > - The benefit is that the stack moves, and the gone backup is recorded instead of silently forgotten ## Linked Issues or Issue Description **What happened?** An online durable-data pass reports `native_harness:selected_source_absent` on every pass for a stack. The selected session has a v2 backup stamp, but `failover-backups/current` for that scope is not on disk. The offline maintenance path also fails: `native_harness_backups_require_migration` stays true because `migrateNativeHarnessBackups` only visits sources on disk. The stack can never move. **Expected behavior** When the backup files are already gone and the session is settled, both paths record that the backup source was gone and stop counting it as an obligation. A session that is still active, or a backup that the expiration service is rotating, stays blocked with a name. **Steps to reproduce** 1. Create a selected `paperclip_runner` session whose last run is settled and whose environment lease has a v2 backup stamp. 2. Remove `/`. 3. Run `prestageNativeHarnessBackups` or `migrateNativeHarnessBackups`. 4. Before this change, `selected_source_absent` repeats and `hasLocalNativeHarnessObligations` stays true. **Paperclip version or commit** master at b2a12fab49. ## What Changed - Add `recordNativeHarnessBackupSourceAbsence`. In one transaction it locks the selected session row, the run's finalization advisory lock, the last run row and the finalization row. It requires a settled run (terminal, no controller lease, no live execution control, no finalization owner, no lease owner or scheduled retry on the coordinator), no queued or running turn on the task or session, no current durable backup for the scope, and stamped leases for the scope. Then it rechecks the disk. If `current` is back, it records nothing. If a `.retiring-*` backup exists, it returns `selected_source_retiring`. If any other entry remains (for example `previous` from an interrupted publish), it returns `selected_source_unsettled`. Only a scope with no entries besides `.expired-*` trash counts as gone. Otherwise it writes `nativeHarnessBackupSourceAbsent` on the last run (scope digest to stamped manifest digests) and logs `native_harness_backup_source_gone_recorded`. - A lock timeout during the recheck returns `selected_source_busy` for this pass instead of failing the harness phase. - The obligation query excludes a scope only when the selected session's last run records that exact scope and that exact stamped manifest digest. A new turn changes the last run, and a new stamp changes the manifest, so the obligation comes back. - The online pass (`prestageNativeHarnessBackups`) and the offline pass (`migrateNativeHarnessBackups`) both call the same recorder for the obligations they could not copy. The online pass counts `nativeHarnessBackupSourcesGone` and does not defer it. - Previous-release story: the new key is additive run state. No resume path reads it. A session behaves after the move exactly as it does on the volume today without its backup. A previous release ignores the key and still reports the obligation. ## Verification - Red: the new tests fail on master. Online still reports `selected_source_absent`, offline still has an obligation (`expected true to be false`), and the retiring case is not named. - Green: `npx vitest run src/services/native-runtime/native-harness-online-preservation.integration.test.ts src/services/native-runtime/native-harness-backup-obligations.integration.test.ts src/services/online-durable-data-migration.test.ts` (62 passed, including busy-row and previous-backup cases). - Neighbors: `ephemeral-server-startup-run-state`, `ephemeral-server-runtime-skill-startup`, `native-harness-prestage(-runtime)`, `native-harness-filesystem-independence`, `native-harness-backup-storage` (218 passed). - `pnpm typecheck` in `server` passes. ## Risks - Medium. A gone backup stops blocking the move. The recorder writes only after a locked recheck that the run is settled, no turn is active, and the files are still absent. A backup that is rotating stays blocked. - The record changes the last run's `runnerProfileJson`. Filesystem-independence facts include that profile. The recorder writes only when no valid independence receipt exists, so no existing receipt changes. - No schema migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use and code execution. ## 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 | 34 ++++--- .../native-harness-backup-source-absence.ts | 93 +++++++++++++++++++ ...ss-online-preservation.integration.test.ts | 71 +++++++++++++- .../services/online-durable-data-migration.ts | 1 + 4 files changed, 185 insertions(+), 14 deletions(-) create mode 100644 server/src/services/native-runtime/native-harness-backup-source-absence.ts 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;