Files
PaperClipAI/server/src/services/native-runtime/native-controller-archive-source.ts
T
DottaandPaperclip 72f7b42fe3 Preserve settled failed controller state during online migration (#19678)
## Thinking Path

> - Paperclip controls agent work across web-server releases.
> - Volume-free servers need retained controller state in shared
storage.
> - Successful settled sources already support online migration.
> - Some retained failed sources have no accepted result and must stay
available for recovery inspection.
> - This change copies those sources under task, coordinator and
publication fences while unrelated work continues.
> - The original files, failed status and recovery warnings remain
unchanged.

## Linked Issues or Issue Description

Refs #19038. Refs #19631.

**What are you trying to improve?**
Preserve retained failed controller files without waiting for global
idle.

**What problem does this solve?**
The online producer skips terminal failed controllers. Their files can
still be needed for recovery inspection even when no accepted provider
artifact proves executable continuation.

**What would the improvement look like?**
A settled exact source can enter the existing encrypted archive store.
An accepted committed failed source can use the existing checkpoint
import. Busy, changed, unowned or foreign sources remain blocked.

## What Changed

- Add a source owner bound to the selected task session, run,
coordinator generation, admitted input and file digests.
- Check the task, physical finalizer lock, released coordinator,
canonical resume source and active related turns before upload and
before publication.
- Preserve failed sources through the existing encrypted archive format.
Do not treat archived bytes as execution authority or old-writer stop
proof.
- Allow the existing accepted committed checkpoint import for a finished
failed run without changing its status.
- Validate admitted input bindings before looking up local controller
files.
- Document the online preservation path and the final static writer
fence.

## Verification

- Real PostgreSQL: 125 cases passed across migration, controller
recovery and durable backup storage. One added assertion inspected an
unadmitted queued fixture; it was corrected while retaining the
queued-turn preservation and stale-publication assertions. The final
migration rerun passes 51/51; the other three affected suites pass
75/75.
- Genuine prepatch RED: online failed-source preservation and accepted
committed failed-source import both fail on the previous producer and
recovery owners.
- New cases cover independent restore after deleting the original
source, an expired but non-null coordinator owner, source mutation after
upload, a new related queued turn during upload, foreign input binding
and an accepted committed failed result.
- The full rebased server source and test-tree typecheck passes after
restoring its missing ignored workspace SDK link and building that
existing dependency.
- Module boundaries and whitespace checks pass.
- Rebased onto current master; both provider-artifact imports and the
new archive owner are preserved. Rebased type and module-boundary checks
pass. All six archive cases pass on the exact rebased head (39.68
seconds). All CI gates pass on exact head
81fc974cd9. Fresh Greptile review is 5/5
with no unresolved comments. No serving migration, deletion or
deployment is performed by this PR.

- Review memory fix: 64 KiB streamed hashes avoid retaining another
controller string at each publication fence. A 256 MiB source is hashed
three times while the original string remains live under a 512 MiB heap.
The old full-string comparison reproduces an OOM; the fixed two-case
suite passes. Full source/test-tree typecheck and module boundaries pass
on the new code. All six real-PostgreSQL archive cases pass again with
streaming enabled (17.31 seconds); ownership, queued-turn and
post-upload mutation guards remain covered.

## Risks

- This is a copy-only preservation operation. It does not prove the
original process has stopped. Final enrollment must arm static ephemeral
mode on the original volume, observe the old deployment stopped and
repeat data eligibility.
- A source change during upload leaves an unpublished pending object.
The normal retention owner handles obsolete attempts; the source remains
required until a verified current archive exists.
- An archive is forensic evidence. It does not make an unaccepted failed
provider result resumable.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning and code execution. The host
does not expose the exact serving model ID or context-window size.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-06 18:38:50 -06:00

90 lines
7.0 KiB
TypeScript

import { and, eq, inArray, or, sql } from "drizzle-orm";
import { createHash } from "node:crypto";
import { agentTaskSessions, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { nativeSha256 } from "./canonical.js";
import { findNativeSessionResumeRun } from "./native-session-resume.js";
import { readLegacyNativeControllerArchiveDigests, readLegacyNativeControllerArchiveSource } from "./native-controller-migration.js";
import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js";
import { archiveFailedLegacyNativeController } from "./native-controller-archive.js";
import type { StorageService } from "../../storage/types.js";
export type SettledControllerArchiveOwner = {
kind: "settled_controller_archive";
companyId: string; issueId: string; agentId: string; runId: string; sessionId: string;
selectedSessionId: string; selectedLastRunId: string;
profileDigest: string; coordinatorDigest: string; controllerDigest: string; supervisorDigest: string | null;
};
const fileDigest = (value: string) => createHash("sha256").update(value).digest("hex");
export function nativeControllerArchiveProfileDigest(value: unknown) {
const profile = value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
return nativeSha256({ nativeExecutionInput: profile.nativeExecutionInput ?? null, nativeToolContractFingerprint: profile.nativeToolContractFingerprint ?? null,
sessionCheckpoint: profile.sessionCheckpoint ?? null, nativeControllerRecovery: profile.nativeControllerRecovery ?? null });
}
export function nativeControllerArchiveCoordinatorDigest(value: {
phase: string; resultId: string | null; controllerBootId: string | null; controllerGeneration: number; recoveryState: unknown;
}) {
return nativeSha256({ phase: value.phase, resultId: value.resultId, controllerBootId: value.controllerBootId,
controllerGeneration: value.controllerGeneration, recoveryState: value.recoveryState });
}
export async function assertSettledControllerArchiveSource(db: Db, owner: SettledControllerArchiveOwner) {
function fail(): never { throw new Error("native_controller_archive_source_unsettled"); }
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 || coordinator.leaseOwner || coordinator.nextAttemptAt
|| !(coordinator.phase === "terminal_failure" || coordinator.phase === "committed" && coordinator.resultId)
|| nativeControllerArchiveCoordinatorDigest(coordinator) !== owner.coordinatorDigest) fail();
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");
const [selectedRun] = await db.select({ createdAt: heartbeatRuns.createdAt }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, owner.selectedLastRunId), eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.agentId, owner.agentId),
eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId)));
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 || run.status !== "failed"
|| nativeControllerArchiveProfileDigest(run.runnerProfileJson) !== owner.profileDigest) 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 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();
const material = await readLegacyNativeControllerArchiveDigests(selected);
if (material.controllerDigest !== owner.controllerDigest
|| (material.supervisorDigest ?? null) !== owner.supervisorDigest) fail();
}
export async function archiveSettledFailedNativeController(db: Db, input: {
selected: { id: string; lastRunId: string; companyId: string; agentId: string; issueId: string; sessionId: string };
source: NonNullable<Awaited<ReturnType<typeof findNativeSessionResumeRun>>>;
storage: StorageService; signal: AbortSignal;
}) {
input.signal.throwIfAborted();
const { selected, source } = input;
const material = await readLegacyNativeControllerArchiveSource(source);
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");
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,
profileDigest: nativeControllerArchiveProfileDigest(source.runnerProfileJson), coordinatorDigest: nativeControllerArchiveCoordinatorDigest(coordinator),
controllerDigest: fileDigest(material.controller), supervisorDigest: material.supervisor === undefined ? null : fileDigest(material.supervisor) };
await db.transaction(tx => assertSettledControllerArchiveSource(tx as unknown as Db, owner));
input.signal.throwIfAborted();
await archiveFailedLegacyNativeController(db, { companyId: selected.companyId, issueId: selected.issueId, runId: source.id,
controller: material.controller, supervisor: material.supervisor, storage: input.storage, onlineOwner: owner, signal: input.signal });
return "archived_failed" as const;
}