mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
## 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 <noreply@anthropic.com>
111 lines
9.5 KiB
TypeScript
111 lines
9.5 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { resolve } from "node:path";
|
|
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";
|
|
import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js";
|
|
import { nativeHarnessStateBase, readNativeHarnessBackupStamp, verifyNativeHarnessBackupStampAsync } from "./native-harness-backup-stamp.js";
|
|
import { readNativeHarnessBackupSource } from "./native-harness-backup-source.js";
|
|
import { withWorkspaceLockKeepalive } from "./native-workspace-lock-keepalive.js";
|
|
|
|
type Run = typeof heartbeatRuns.$inferSelect;
|
|
type Coordinator = typeof nativeRunFinalizations.$inferSelect;
|
|
type Lease = typeof environmentLeases.$inferSelect;
|
|
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;
|
|
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(),
|
|
controllerBootId: run.controllerBootId, controllerLeaseExpiresAt: run.controllerLeaseExpiresAt?.toISOString(),
|
|
processPid: run.processPid, processGroupId: run.processGroupId, processStartedAt: run.processStartedAt?.toISOString(),
|
|
runnerInstanceId: run.runnerInstanceId, runnerProfileJson: run.runnerProfileJson });
|
|
const coordinatorDigest = (row: Coordinator) => nativeSha256({ phase: row.phase, resultId: row.resultId,
|
|
controllerBootId: row.controllerBootId, controllerGeneration: row.controllerGeneration, recoveryState: row.recoveryState });
|
|
const leaseDigest = (row: Lease) => nativeSha256({ heartbeatRunId: row.heartbeatRunId, status: row.status,
|
|
releasedAt: row.releasedAt?.toISOString(), cleanupStatus: row.cleanupStatus, providerLeaseId: row.providerLeaseId,
|
|
nativeHarnessBackup: row.metadata?.nativeHarnessBackup });
|
|
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. */
|
|
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" | "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 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}`));
|
|
const lease = leases.find(row => readNativeHarnessBackupStamp(row.metadata?.nativeHarnessBackup, input.providerLeaseId)?.sessionScopeSha256 === input.scopeDigest);
|
|
if (!lease) return { owner: null, reason: "lease_missing" };
|
|
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,
|
|
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));
|
|
return { owner };
|
|
}
|
|
|
|
export async function assertSettledNativeHarnessBackupSource(db: Db, owner: SettledNativeHarnessBackupOwner,
|
|
signal = AbortSignal.timeout(300_000)) {
|
|
signal.throwIfAborted();
|
|
await db.execute(sql`set local lock_timeout = '1s'`);
|
|
if (!await tryLockNativeWorkspaceFinalization(db, owner)) fail();
|
|
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();
|
|
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 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 (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();
|
|
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();
|
|
const [lease] = await db.select().from(environmentLeases).where(and(eq(environmentLeases.id, owner.sourceLeaseId),
|
|
eq(environmentLeases.companyId, owner.companyId), eq(environmentLeases.issueId, owner.issueId),
|
|
eq(environmentLeases.providerLeaseId, owner.providerLeaseId))).for("share");
|
|
const stamp = readNativeHarnessBackupStamp(lease?.metadata?.nativeHarnessBackup, owner.providerLeaseId);
|
|
if (!lease || !stamp || leaseDigest(lease) !== owner.leaseDigest || stamp.sessionScopeSha256 !== owner.scopeDigest
|
|
|| stamp.manifestSha256 !== owner.manifestSha256 || stamp.normalizedSessionId !== owner.sessionId
|
|
|| stamp.runnerInstanceId !== owner.runnerInstanceId) fail();
|
|
if (!/^[a-f0-9]{64}$/.test(owner.scopeDigest)
|
|
|| resolve(owner.root) !== resolve(nativeHarnessStateBase(), owner.scopeDigest, "failover-backups", "current")) fail();
|
|
const [settings] = await db.execute<{ idle_timeout_ms: string }>(sql`select
|
|
extract(epoch from current_setting('idle_in_transaction_session_timeout')::interval) * 1000 as idle_timeout_ms`);
|
|
await withWorkspaceLockKeepalive(db, Number(settings.idle_timeout_ms), async () => {
|
|
const source = await readNativeHarnessBackupSource(owner.root);
|
|
if (!source || source.state.runId !== owner.runId || source.state.lifecycle !== "suspended"
|
|
|| `sha256:${createHash("sha256").update(source.manifestBytes).digest("hex")}` !== owner.manifestSha256
|
|
|| !await verifyNativeHarnessBackupStampAsync(stamp, owner.providerLeaseId, signal, owner.root)) fail();
|
|
});
|
|
}
|