fix(ephemeral): save retained runtime skill bundles at startup and never strand a volume-free server on lost ones (#22190)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A volume-free server keeps no local volume. It must find every file
it needs in durable storage.
> - Before a volume-free server starts, a data gate refuses to start if
records still point at files on a local disk.
> - Old native runs can keep runtime skill bundles that a release before
#19729 wrote only to its own disk. The gate reports these as
`runtime_skill_assets_require_migration`.
> - On a volume-free server those files are not on the disk, and no
volume can be attached again. So the refusal repeats on every restart,
and nothing can clear it. A staging stack crash-looped like this and
stayed down.
> - This pull request makes the server copy every retained bundle that
is still on its disk into durable storage, and start over the bundles
that are gone, the same way #20990 handles harness backups.
> - The benefit is that a volume-free stack can always start again. No
one has to repair it by hand.

## Linked Issues or Issue Description

Refs #19675, #19729, #20990

**What happened?**

A volume-free staging stack ran for twelve days on a release that kept
runtime skill bundles only on its container disk. When that container
stopped, every newer release crash-looped at boot with `Volume-free
server data is not eligible: runtime_skill_assets_require_migration`.
The old container was gone, so the bundles were gone. The deploy could
not roll back, and a retry could not help.

**Expected behavior**

A volume-free server starts. It saves each retained bundle that is still
on its disk to durable storage. It starts over a bundle that is not on
its disk when the volume-free owner marker proves that no volume is
mounted, and restart recovery owns those runs.

**Steps to reproduce**

1. Retain a native run with an admitted runtime skill bundle that has no
version ID and no durable preservation receipt.
2. Remove the bundle from the instance root.
3. Start the server with `PAPERCLIP_EPHEMERAL_SERVER=true` and the
volume-free owner marker present.
4. Startup fails with `runtime_skill_assets_require_migration`, on every
restart.

## What Changed

- `runtime-skill-preservation.ts`:
- The obligation scan is one generator.
`hasLocalRuntimeSkillObligations` uses it.
- New `preserveLocalRuntimeSkillObligations` copies each obligated run's
bundles with `preserveRuntimeSkillAssets` and returns `{ bundles,
unsaved }`.
- A missing source is decided at its reader:
`readLocalManifest`/`readSource` throw `RuntimeSkillSourceAbsent` (other
instance root, or a missing directory, manifest or listed file). Only
that error marks a run unsaved. Any other failure, including an `ENOENT`
from storage or cache work, propagates.
- `preserveRuntimeSkillAssets` no longer aborts on an invalid or
non-durable existing receipt. It copies the local bytes again and
replaces the receipt.
- One durability helper (`preservedAssetRowDurable` for metadata,
`preservedAssetDurable` with a metadata or object read) replaces the
copies in the scan, staging, locking, preservation and rehydration.
- `runtime-skill-preservation-reference.ts`: the scan matches only null
pins, which is exactly what preservation copies. A non-null pin is a
version pin and cannot become an obligation that nothing can settle.
- `file-manifest-cache.ts`: new `inspectFileManifest` returns
`verified`, `missing` or `changed` from the same walk.
`verifyFileManifest` wraps it.
- `ephemeral-server-contract.ts`: the gate saves the bundles still on
the disk. If none stay unsaved, the blocker clears. Unsaved runs are
waived only when the volume-free owner marker is present, with a
warning. A save failure still refuses. The decision uses the copy pass
result, not another scan. One exported blocker constant.
- `ephemeral-migration-data.ts`: offline enrollment accepts the blocker
and copies the bundles from the attached volume, in a phase after the
package phases. Any unsaved run still fails the enrollment.
- `index.ts`: comment update only.
- Tests: `ephemeral-server-runtime-skill-startup.test.ts` (real scan,
real copy, embedded Postgres) and an S3-gated case in
`ephemeral-migration.test.ts`.

## Verification

- `cd server && npx vitest run
src/__tests__/ephemeral-server-runtime-skill-startup.test.ts`
- Red on `origin/master`: 2 of 3 fail with the production error
`Volume-free server data is not eligible:
runtime_skill_assets_require_migration`.
- Green with this change: all cases pass (lost bundle, saved bundle, no
marker, mixed present and lost, one missing listed file, non-version
pin, mixed pins, non-durable receipt recapture, storage failure, storage
ENOENT, unsaved set).
- `cd server && npx vitest run
src/__tests__/ephemeral-server-startup-run-state.test.ts
src/__tests__/runtime-skill-preservation.test.ts` pass (existing gate
and preservation behavior unchanged).
- `cd server && npx tsc --noEmit -p .` passes.
- `ephemeral-migration.test.ts` needs `PAPERCLIP_TEST_S3_ENDPOINT`. It
typechecks, but it was not run here.

## Risks

- A run whose bundle is lost now starts under restart recovery instead
of blocking the whole server. Recovery of that one run can fail. Before,
the whole server stayed down, and the bundle was lost anyway.
- Startup does more work only when unsaved legacy bundles exist. A
current release saves bundles before admission (#19729), so new runs
never add this work.
- No schema change. No API change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, test runs).

## 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>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-18 11:00:20 -06:00
1 parent 3c460f20cc
commit a7ea2a799a
8 files changed
+409 -57

No files matched your search

@@ -27,7 +27,12 @@ import { companySkillService } from "../services/company-skills.js";
import { skillPackageStore } from "../services/skill-package-store.js";
import { skillInstallationMaintenance } from "../services/skill-installation-maintenance.js";
import { migrateLocalSkillPackageObjects } from "../services/skill-package-storage-migration.js";
import { companySkills, companySkillRepositorySnapshots } from "@paperclipai/db";
import { companySkills, companySkillRepositorySnapshots, nativeRunFinalizations } from "@paperclipai/db";
import { materializeAsset } from "../services/native-runtime/runtime-context.js";
import { nativeRuntimeContextFixture } from "../services/native-runtime/runtime-context.test-fixture.js";
import { canonicalNativeRuntimeContextDigest, parseNativeExecutionInput } from "../vendor/paperclip-runner/index.js";
import { snapshotFile } from "../services/skill-snapshot.js";
import { hasLocalRuntimeSkillObligations } from "../services/native-runtime/runtime-skill-preservation.js";
// Explicit real-dependency qualification. Never contacts off-host storage in
// the default test path; use a disposable S3-compatible service and PostgreSQL.
@@ -300,4 +305,42 @@ describe.skipIf(!process.env.PAPERCLIP_TEST_S3_ENDPOINT)("existing-volume enroll
.where(eq(agentInstructionWorkingCopies.runId, run!.id));
expect((await migrate()).eligibility.eligible).toBe(true);
});
// The original trigger: a retained runtime skill bundle whose bytes match a
// package snapshot still on the volume's local disk. Package phases must move
// that snapshot first, or the bundle's save reuses a local-disk receipt.
it("saves a retained runtime skill bundle that matches a local-disk package snapshot", async () => {
const owner = await agent(), issueId = randomUUID(), runId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Old native run" });
const content = Buffer.from("# legacy admitted skill\n");
vi.stubEnv("PAPERCLIP_STORAGE_PROVIDER", "local_disk");
await skillPackageStore(db, getStorageService()).prepare(companyId, [snapshotFile("SKILL.md", "skill", content)], true);
vi.stubEnv("PAPERCLIP_STORAGE_PROVIDER", "s3");
const bundle = await materializeAsset([{ path: "SKILL.md", content, mode: 0o400 }]);
const context = nativeRuntimeContextFixture();
context.skills = [{ key: "legacy", runtimeName: "legacy", versionId: null, bundle }];
context.aggregateDigest = canonicalNativeRuntimeContextDigest(context);
const execution = parseNativeExecutionInput({ schema: "paperclip.native-execution-input.v3",
binding: { companyId, runId, agentId: owner.id, issueId, executionWorkspaceId: runId },
task: { identifier: "MIG-1", title: "Old admission", description: null, prompt: "Use the skill", workMode: "standard" },
workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null },
session: { normalizedSessionId: null, driverKind: "codex_app_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
provider: { kind: "codex", model: null },
completionContract: { id: "contract", sha256: "saved", schemaVersion: "paperclip.completion-contract.v1",
contract: { revision: "1", objective: "Use the skill", criteria: [{ id: "use", requirement: "Use skill" }] } },
interactionResponses: [], credentialBindings: [], executionMode: "default", planningContext: null, runtimeContext: context });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: owner.id, nativeIssueId: issueId, runtimeMode: "native",
status: "failed", finishedAt: new Date(), runnerProfileJson: { nativeExecutionInput: execution } });
await db.insert(nativeRunFinalizations).values({ companyId, runId, issueId, phase: "terminal_failure", recoveryState: "blocked" });
try {
expect(await hasLocalRuntimeSkillObligations(db)).toBe(true);
expect(await migrate()).toMatchObject({ eligibility: { eligible: true }, counts: { runtimeSkillAssets: 1 } });
expect(await hasLocalRuntimeSkillObligations(db)).toBe(false);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
const receipt = run!.runnerProfileJson!.nativeRuntimeSkillPreservation as { assets: Array<{ packageSnapshotId: string }> };
expect((await skillPackageStore(db).descriptor(companyId, receipt.assets[0]!.packageSnapshotId)).storage)
.toMatchObject({ provider: "s3", durable: true });
} finally {
await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
}
}, 120_000);
});
@@ -0,0 +1,198 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest";
import { activityLog, agentFileRoots, agents, companies, heartbeatRuns, issues, companySkillRepositorySnapshots as snapshots,
nativeRunFinalizations, createDb } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import * as storageModule from "../storage/index.js";
import { createStorageService } from "../storage/service.js";
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
import { materializeAsset } from "../services/native-runtime/runtime-context.js";
import { nativeRuntimeContextFixture } from "../services/native-runtime/runtime-context.test-fixture.js";
import { canonicalNativeRuntimeContextDigest, parseNativeExecutionInput } from "../vendor/paperclip-runner/index.js";
import { hasLocalRuntimeSkillObligations, preserveLocalRuntimeSkillObligations } from "../services/native-runtime/runtime-skill-preservation.js";
import { removeRuntimeAssetTree } from "../services/native-runtime/runtime-asset-retention.js";
import { assertEphemeralServerData } from "../services/ephemeral-server-contract.js";
import { volumeFreeControllerStateOwned } from "../services/native-runtime/volume-free-controller-state.js";
vi.mock("../services/native-runtime/native-harness-backup-migration.js", () => ({
hasLocalNativeHarnessObligations: vi.fn(async () => false) }));
vi.mock("../services/native-runtime/volume-free-controller-state.js", async importOriginal => ({
...await importOriginal<typeof import("../services/native-runtime/volume-free-controller-state.js")>(),
volumeFreeControllerStateOwned: vi.fn(),
}));
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let home: string;
const previousHome = process.env.PAPERCLIP_HOME;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("ephemeral-runtime-skill-startup-");
db = createDb(database.connectionString, { maxConnections: 6 });
home = await fs.mkdtemp(path.join(os.tmpdir(), "ephemeral-runtime-skill-startup-"));
process.env.PAPERCLIP_HOME = home;
const storage = createStorageService({ ...createLocalDiskStorageProvider(path.join(home, "objects")), id: "s3" });
vi.spyOn(storageModule, "getStorageService").mockReturnValue(storage);
}, 90_000);
afterEach(async () => {
vi.unstubAllEnvs();
vi.mocked(volumeFreeControllerStateOwned).mockReset();
for (const table of [activityLog, nativeRunFinalizations, heartbeatRuns, issues, agentFileRoots, agents, snapshots, companies]) await db.delete(table);
});
afterAll(async () => {
vi.restoreAllMocks();
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
await db?.$client.end({ timeout: 1 });
await database?.cleanup();
if (home) await removeRuntimeAssetTree(home);
});
/** A native run admitted by a release that did not yet save runtime skill
* bundles at admission: the bundle exists only on the admitting server's disk. */
async function retainedUnsavedRuntimeSkill(options: { pins?: Array<string | null> } = {}) {
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), issueId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Runtime skill startup", issuePrefix: `S${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Legacy admission" });
await db.insert(agentFileRoots).values({ companyId, agentId, generation: randomUUID(), entries: [] });
await db.insert(issues).values({ id: issueId, companyId, title: "Old native run" });
const bundle = await materializeAsset([{ path: "SKILL.md", content: Buffer.from(`# legacy ${runId}\n`), mode: 0o400 },
{ path: "notes.md", content: Buffer.from("notes\n"), mode: 0o400 }]);
const context = nativeRuntimeContextFixture();
context.skills = (options.pins ?? [null]).map((versionId, index) => ({ key: `legacy-${index}`, runtimeName: `legacy-${index}`, versionId, bundle }));
context.aggregateDigest = canonicalNativeRuntimeContextDigest(context);
const execution = parseNativeExecutionInput({ schema: "paperclip.native-execution-input.v3",
binding: { companyId, runId, agentId, issueId, executionWorkspaceId: runId },
task: { identifier: "LEGACY-1", title: "Old admission", description: null, prompt: "Use the skill", workMode: "standard" },
workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null },
session: { normalizedSessionId: null, driverKind: "codex_app_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
provider: { kind: "codex", model: null },
completionContract: { id: "contract", sha256: "saved", schemaVersion: "paperclip.completion-contract.v1",
contract: { revision: "1", objective: "Use the skill", criteria: [{ id: "use", requirement: "Use skill" }] } },
interactionResponses: [], credentialBindings: [], executionMode: "default", planningContext: null, runtimeContext: context });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId, runtimeMode: "native",
status: "failed", finishedAt: new Date(), runnerProfileJson: { nativeExecutionInput: execution } });
await db.insert(nativeRunFinalizations).values({ companyId, runId, issueId, phase: "terminal_failure", recoveryState: "blocked" });
return { runId, bundle };
}
const lose = (bundle: { rootPath: string }) => removeRuntimeAssetTree(bundle.rootPath);
const saved = async (runId: string) => {
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
return Object.hasOwn(run!.runnerProfileJson ?? {}, "nativeRuntimeSkillPreservation");
};
const volumeFreeServer = () => {
vi.stubEnv("PAPERCLIP_EPHEMERAL_SERVER", "true");
vi.stubEnv("PAPERCLIP_DURABLE_AGENT_FILES", "true");
};
// Staging, 2026-11-18: a stack ran volume-free for twelve days on
// a release that kept runtime skill bundles only on its container disk. When
// that container stopped, every newer release refused to start with
// runtime_skill_assets_require_migration, and nothing could clear it.
it("starts a volume-free server over runtime skill bundles a lost disk held", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(true);
const { bundle } = await retainedUnsavedRuntimeSkill();
await removeRuntimeAssetTree(path.dirname(path.dirname(bundle.rootPath)));
await expect(assertEphemeralServerData(db)).resolves.toBeUndefined();
});
it("saves bundles still on this disk to durable storage before starting", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(false);
const { runId } = await retainedUnsavedRuntimeSkill();
expect(await hasLocalRuntimeSkillObligations(db)).toBe(true);
await expect(assertEphemeralServerData(db)).resolves.toBeUndefined();
expect(await hasLocalRuntimeSkillObligations(db)).toBe(false);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(run!.runnerProfileJson).toHaveProperty("nativeRuntimeSkillPreservation");
expect(volumeFreeControllerStateOwned).not.toHaveBeenCalled();
});
it("still refuses a missing bundle on a filesystem with no volume-free owner marker", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(false);
const { bundle } = await retainedUnsavedRuntimeSkill();
await removeRuntimeAssetTree(path.dirname(path.dirname(bundle.rootPath)));
await expect(assertEphemeralServerData(db)).rejects.toThrow("runtime_skill_assets_require_migration");
});
it("saves the bundles still here and starts over the lost ones on a volume-free filesystem", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(true);
const present = await retainedUnsavedRuntimeSkill(), lost = await retainedUnsavedRuntimeSkill();
await lose(lost.bundle);
await expect(assertEphemeralServerData(db)).resolves.toBeUndefined();
expect(await saved(present.runId)).toBe(true);
expect(await saved(lost.runId)).toBe(false);
});
it("treats a bundle missing one listed file as lost, not changed", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(true);
const { bundle } = await retainedUnsavedRuntimeSkill();
await fs.chmod(bundle.rootPath, 0o700);
await fs.rm(path.join(bundle.rootPath, "notes.md"));
await expect(assertEphemeralServerData(db)).resolves.toBeUndefined();
});
it("does not hold startup on a non-null pin that is not a version ID, which preservation never copies", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(false);
await retainedUnsavedRuntimeSkill({ pins: ["legacy-pin"] });
expect(await hasLocalRuntimeSkillObligations(db)).toBe(false);
await expect(assertEphemeralServerData(db)).resolves.toBeUndefined();
});
it("saves the null pin of a run that mixes it with a non-version pin, and settles the run", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(false);
const { runId } = await retainedUnsavedRuntimeSkill({ pins: ["legacy-pin", null] });
expect(await preserveLocalRuntimeSkillObligations(db)).toEqual({ bundles: 1, unsaved: [] });
expect(await saved(runId)).toBe(true);
expect(await hasLocalRuntimeSkillObligations(db)).toBe(false);
});
it("recaptures a bundle still here when its receipt's package is no longer durable", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(false);
const { runId } = await retainedUnsavedRuntimeSkill();
await preserveLocalRuntimeSkillObligations(db);
await db.update(snapshots).set({ storage: null });
expect(await hasLocalRuntimeSkillObligations(db)).toBe(true);
await expect(assertEphemeralServerData(db)).resolves.toBeUndefined();
expect(await hasLocalRuntimeSkillObligations(db)).toBe(false);
expect(await saved(runId)).toBe(true);
});
it("refuses a storage error that looks like a missing file, even on a volume-free filesystem", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(true);
await retainedUnsavedRuntimeSkill();
const missing = Object.assign(new Error("temp file vanished"), { code: "ENOENT" });
const put = vi.spyOn(storageModule.getStorageService(), "putFile").mockRejectedValue(missing);
try { await expect(assertEphemeralServerData(db)).rejects.toThrow("runtime_skill_assets_require_migration"); }
finally { put.mockRestore(); }
});
it("refuses when saving a bundle that is here fails, even on a volume-free filesystem", async () => {
volumeFreeServer();
vi.mocked(volumeFreeControllerStateOwned).mockResolvedValue(true);
const { runId } = await retainedUnsavedRuntimeSkill();
const put = vi.spyOn(storageModule.getStorageService(), "putFile").mockRejectedValue(new Error("storage offline"));
try { await expect(assertEphemeralServerData(db)).rejects.toThrow("runtime_skill_assets_require_migration"); }
finally { put.mockRestore(); }
expect(await saved(runId)).toBe(false);
});
// The offline enrollment phase is this pass with a hard refusal on any unsaved
// run; the full enrollment suite needs a real S3 endpoint (ephemeral-migration.test.ts).
it("reports exactly the runs it could not save, for enrollment to refuse", async () => {
const present = await retainedUnsavedRuntimeSkill(), lost = await retainedUnsavedRuntimeSkill();
await lose(lost.bundle);
expect(await preserveLocalRuntimeSkillObligations(db)).toEqual({ bundles: 1, unsaved: [lost.runId] });
expect(await saved(present.runId)).toBe(true);
expect(await preserveLocalRuntimeSkillObligations(db)).toEqual({ bundles: 0, unsaved: [lost.runId] });
});