mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - During a release swap, the outgoing server stops and the incoming server takes over the live runs on remote Runners > - The incoming server reached those runs late: it waited up to 60 s for the outgoing server's controller lease to lapse, re-verified each run's whole log from object storage, and deferred a reattach when the agent directory was busy. Queued starts competed with the reattaches for the same resources. > - On hosted staging, the later a live run was reached, the more likely it was to fail. Runs reached in under 150 s never failed; runs reached after 420 s almost always failed. > - This pull request hands live runs over at the start of shutdown, makes a reattach skip work that the same run already did, and holds queued starts while handed-over runs are being reached, with a 180 s cap. > - The benefit is that live runs are reached within seconds of a swap instead of minutes, so they continue instead of failing. ## Linked Issues or Issue Description **What happened?** Hosted staging, release swaps on 2026-11-13 (06:05Z to 09:45Z). For each run that crossed a swap we measured the gap from the last Runner output to the moment the new server recorded the Runner's process identity: - gap under 150 s: 0 of 9 runs failed - gap over 420 s: 14 of 15 runs failed - median gap: 180 s for runs that resumed, 470 s for runs that failed In one traced run the incoming server waited on `remote_controller_lease_live` three times (09:14:21, 09:15:18, 09:16:17), claimed at 09:16:59, and spent 85 s in `task.prepare`. Of that, `heartbeat.prepare.run_output` took 58.7 s, because it re-read the run's whole log from object storage. A control run spent 23 s in `task.prepare`. Queued starts used the same preparation path, the same 8 object-I/O slots and the same database pool, and nothing gave a reattach priority. The first-attempt failures were `PRP command session.snapshot timed out` and `codex_history_read_failed`. The retry then failed with `runner_harness_state_mismatch: resumed_not_suspended`, `runner_remote_process_identity_unavailable` or `provider_turn_lost_on_restore`. **Expected behavior** Every live run is reached within about 30 s of the swap. Queued work starts after that, or after a bounded wait. **Steps to reproduce** 1. Run a two-server release swap with live remote runs and queued runs. 2. Observe `native.recovery.transition` "waiting" events with `remote_controller_lease_live`, then the claim, then a long `heartbeat.prepare.run_output` span. 3. The new tests in `reattach-phase.test.ts` and `heartbeat-native-early-hand-off.test.ts` model this. **Paperclip version or commit** `master` at426e8a35dc. ## What Changed - Early hand-off at shutdown (`heartbeat/recovery.ts`, `server/src/index.ts`): in deploy-overlap mode, the outgoing server releases the remote controller lease of its live runs at SIGTERM (`recoveryState` `awaiting_runner_reattach`). A run another server already took over is left alone. The incoming server no longer waits for the lease to lapse. - Reattach fast path: - `heartbeat/run-output.ts`, `native-runtime/native-run-log-export.ts`: a reattach starts without waiting for the existing log to be re-verified. - `heartbeat/agent-directory-busy.ts`, `heartbeat.ts`: a reattach that meets a busy agent directory waits in process (at most 30 s) instead of being deferred to a full re-preparation. An ordinary start is still deferred at once, with no added wait. - Reattach phase lifecycle (`heartbeat/reattach-phase.ts`): the watch is a worker on the shared delivery coordinator, queue `reattach-phase`. - Trigger: one startup listing of a previous server's live runs; then the hand-over notification (`notifyReattachHandOver`, sent in the hand-over transaction); the earliest lease deadline it watches (a killed owner); and a 2 s re-check only while handed-over runs are still pending, which ends with the phase (cap 180 s). The bounded re-check exists because a run can also end on another path that sends no notification to this queue. - Source of truth: `native_run_finalizations` and `heartbeat_runs` rows. - Quiet condition: nothing pending and no watched lease, so no deadline and no SQL. It stops with the coordinator at shutdown. - Reached hook for every driver (`native-session-executor.ts`): a reattached run counts as reached when the native session runtime hands the executor its recovered or opened session (`onSession`). Every driver reaches that point only after the Runner answered this server's attach and recovery commands, including an adopted `RunnerdExternalDriver` Runner, which records no new process identity. The identity hook stays as an earlier signal. - Claim wake: when the reattach-phase worker finds runs that just became claimable (hand-over notification or a killed owner's lease deadline), it starts this server's restart-recovery claim for them at once. A validation cell showed the claim otherwise waited about 21.5 s after the hand-over. - `recovery/assigned-work-sweep.ts`: the `deferred_reattach_phase` return now sits before every action path of `act()`, except starting an overdue saved-work recovery (it resumes an existing run). - The in-transaction admission re-check of a queued claim (`confirmRunAdmissionStillOpen`) also honours the reattach phase. A phase that begins during a claim returns the run to the queue through the existing rollback. - A reattach whose log re-verification runs in the background awaits it before the log is finalized (`settleDeferredLogRecovery`, both finalization sites in `run-completion.ts`). - Reattach phase (`heartbeat/reattach-phase.ts`, `heartbeat/run-admission.ts`): `isReattachPhaseActive()` is true while runs that a previous controller handed over (lease released or observed expired, or claimed by this server's restart recovery) are claimable but not yet reached. A run is reached when its process identity is recorded. Authentication is logged as a mark. The cap (180 s, `PAPERCLIP_REATTACH_PHASE_CAP_MS`) counts from the moment the runs became claimable. Later batches join or re-arm the phase. Runs reached after 150 s are counted and logged. - Gates on the phase: - `claimQueuedRun`, start-next, resume-queued and dispatch in `heartbeat/queue.ts`, `run-lifecycle.ts` and `native-runner-execution-driver.ts` leave queued runs queued. - `execution-recovery-resolution.ts`: one line, the first line of `deliverReconciledExecutions`. - `recovery/assigned-work-sweep.ts`: one line, outcome `deferred_reattach_phase`. - `heartbeat/recovery.ts`: a one-line claim hook (`noteReattachRunsClaimed`) after restart recovery claims runs. - The owner of those three files agreed to these one-line gates. - `tests/restart-chaos/daytona-image.ts`: `PAPERCLIP_CHAOS_TEST_ACCEPT_IMAGE_CONTENT_ID` lets a local wave run a controller-only branch against an existing Daytona image. It accepts a content-ID mismatch only for the exact content ID of the named image, and it prints a TEST OVERRIDE warning. This is harness-only. ## Verification Red on master, green on this branch: - `heartbeat/reattach-phase.test.ts` (27 tests). Five of the six two-server scenarios were red on the earlier phase timing: - `does not hold queued starts while the previous owner is alive and not handing over` - `closes the gate when the previous owner hands its runs over, and counts reach latency from the hand-over` - `runs the cap from the hand-over, so a wedged run ends the phase without the overlap eating it` - `begins when a killed owner's lease is observed expired, without any hand-over` - `re-arms for a later batch, including runs the previous owner started after discovery` - `closes the gate at once when this server claims a run between two lease reads, dated from the hand-over` - plus `claimQueuedRun leaves a queued run queued and unstarted, in the admission gate's shape`, `is the same gate the assigned-work sweep and reconciled continuation delivery read`, `ends at the cap, counted from when the runs became claimable, so one wedged Runner cannot hold run starts` - `heartbeat-native-early-hand-off.test.ts`: `releases the remote controller lease of %i live runs at once` (1, 20, 40 runs; 40 runs in 56 ms), `leaves a run another server already took over alone`, `holds the incoming server's queued starts only from the hand-over, not while the outgoing server still drives its runs` - `heartbeat/run-output.test.ts`: `lets a reattach start before its existing log is re-verified` - `heartbeat/agent-directory-busy.test.ts`: `defers an ordinary start at once, with no wait added to the run-start path`, `lets a reattach wait its turn in process instead of a deferred full re-preparation`, `still defers a reattach once its bounded wait runs out` - `tests/restart-chaos/daytona-image.test.ts`: `accepts a mismatch only for the exact image content ID named by the test override` - Review fixes (red before the fix, green after): `reattach-phase.test.ts` `starts the claim of handed-over runs within a second of the hand-over notification`; `assigned-work-invariant.test.ts` `takes no action while handed-over live runs are being reached, and acts once the phase ends`; `heartbeat-native-early-hand-off.test.ts` `never lets the outgoing server claim back a run it handed off, while the incoming server may take it over`; `reattach-phase.test.ts` `retries a failed first listing instead of going quiet, and still finds the previous owner's runs`, `keeps a hand-over notification whose listing failed until a listing succeeds`, `moves the cap earlier when a claimed run turns out to have been handed over before its claim`; `queue.test.ts` `returns the claim to the queue when a reattach phase begins while the claim is being checked`; `run-completion.test.ts` `finalizes the run log in completeRun|failRun only after a reattach's deferred log recovery settles`. `native-session-executor.test.ts` `ends the reattach phase once a reattached %s session is driven by this server again, without the cap or manual settling` over codex_app_server, opencode_server, acpx_runtime, muse_external, grok_bot_mcp and openai_dot_mcp (6 of 6 red without the hook; the test drives the executor with a mocked session runtime, not each real driver). Lifecycle tests for the new worker: `does no database work and keeps no deadline on an instance with nothing to reattach`, `waits for the hand-over notification or the lease deadline instead of polling while the previous owner drives its runs`, `begins at a killed owner's lease deadline, without any hand-over or notification`, `stops with the delivery coordinator at shutdown and ignores a later hand-over`. Local runs on this branch: `tsc --noEmit` is clean for `server`. Passing on this branch: `reattach-phase.test.ts`, `heartbeat-native-early-hand-off.test.ts`, `run-output.test.ts` (53 tests together), `agent-directory-busy.test.ts`, `heartbeat-native-restart-suspension.test.ts` (115 of 115, alone), the new cases in `queue.test.ts` and `run-completion.test.ts`. Under load 30 to 96 on this shared machine, the full `queue.test.ts` and `recovery-wake-herd.test.ts` runs stalled in their embedded-Postgres setup; CI supplies them. Daytona results that exist (local servers with Daytona sandboxes, release-swap cells). They ran on a combined branch with this PR, #21462, #21442 and #21362 (merged), so they cannot be credited to this PR alone: - G5 baseline (masterd1d71a7755): SIGTERM to PRP authentication 21.5 to 38 s at swap 1. - G5c (combined branch 588c6ba267): SIGTERM to authentication 6.2 to 7.7 s at swap 1. All runs that crossed swap 2 were adopted on the same Runner process. The staging chain (`provider recovery timed out after 900000ms`, then `resumed_not_suspended`) did not recur. - Caveat: G5c ran before the phase timing fix in this PR. In G5c the phase opened at process start, its 180 s cap ran out during the overlap, and swap 2 ended `cap_reached` with 0 runs reached, 1 s before the lease claims. The timing fix (the phase begins when the runs become claimable) has not run on Daytona. - G6c (12 live runs and 20 queued, two graceful swaps, no injection, combined branch 588c6ba267): 0 failed runs at either swap; 11 of 11 survivors at both. - Swap 1: hand-off of 11 runs in 291 ms; claims 0.3 to 2.9 s after hand-off; authentication 7.6 to 12.5 s and identity 8.3 to 13.3 s after SIGTERM. The 30 s target was met. - Swap 2: hand-off took 8,562 ms and `hot_restart_prepare` timed out at 19 s, so the outgoing server drained gracefully. The incoming server did not claim on the hand-over; it claimed only when the outgoing server exited, 33 s after SIGTERM. Authentication was 46 to 54 s and identity 47 to 57 s after SIGTERM. The target was missed. Why the claims waited for the exit is not explained. - The host load was 49 to 70 from other work. 7 of 32 tasks timed out in the queue or budget after the swaps; we suspect the overload. ## Risks - Product trade-off: while handed-over live runs are being reached, queued starts wait, up to the 180 s cap. On an instance with no handed-over runs, nothing waits. - Not proven: two-server behavior with the phase timing fix and the notification-driven watch (no cell has run them); warm standby becoming active; runs that the outgoing server starts after discovery. - Early hand-off at SIGTERM orphans a server-side exec tool that is in flight. With #21442 the next controller settles it as interrupted with an unknown outcome; it is never run again. - Swap 2 in G6c: the incoming server claimed only at the outgoing server's exit. That is unexplained. - Cross-session ownership: the gates in `execution-recovery-resolution.ts` and `recovery/assigned-work-sweep.ts`, and the claim hook in `heartbeat/recovery.ts`, are in files that the restart-recovery work owns. They are one-line gates agreed with that owner. That owner said the gate did not need to be inside the claim transaction; that was before the phase could begin during a claim. After review, the in-transaction re-check in `heartbeat/queue.ts` also reads the phase, through the existing rollback. #21427 (open) also edits `execution-recovery-resolution.ts`, `heartbeat/queue.ts` and `recovery/assigned-work-sweep.ts`; whichever merges second needs a rebase. `native-runtime/native-restart-recovery.ts` (claim logic, owned by the restart-recovery work): a 3-line guard in `claimNativeRestartRecoveries` returns a run this process handed off at shutdown as `blocked` / `handed_off_to_next_controller` before takeover is evaluated, so the outgoing server never claims back a run it handed off. #21478 (merged) added a sweep path that starts an overdue saved-work recovery; it is deliberately not gated by the reattach phase, because it resumes an existing run (reattach-like work), which the phase makes room for rather than competes with. ## 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>
385 lines
21 KiB
TypeScript
385 lines
21 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { chmod, mkdir, mkdtemp, readFile, readlink, rm, stat, writeFile } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import { RUNNER_REVISION_LABEL, assertControllerMatchesImage, assertProviderPackMismatch, copyImageToDir, extractFromLayers, prepareDaytonaImageArtifacts, normalizeLayerPath, walkTar, type LayerSource } from "./daytona-image.js";
|
|
|
|
type Entry =
|
|
| { path: string; type: "file"; content: string; mode?: number }
|
|
| { path: string; type: "dir" }
|
|
| { path: string; type: "symlink" | "hardlink"; target: string };
|
|
|
|
function header(name: string, typeflag: string, size: number, mode: number, link = ""): Buffer {
|
|
const block = Buffer.alloc(512);
|
|
const field = (value: string, offset: number, length: number) => block.write(value, offset, length, "utf8");
|
|
const octal = (value: number, offset: number, length: number) => field(`${value.toString(8).padStart(length - 1, "0")}\0`, offset, length);
|
|
field(name, 0, 100);
|
|
octal(mode, 100, 8); octal(0, 108, 8); octal(0, 116, 8); octal(size, 124, 12); octal(0, 136, 12);
|
|
block.write(typeflag, 156, 1, "latin1");
|
|
field(link, 157, 100);
|
|
block.write("ustar\0", 257, 6, "latin1");
|
|
block.write("00", 263, 2, "latin1");
|
|
block.fill(0x20, 148, 156);
|
|
let sum = 0;
|
|
for (const byte of block) sum += byte;
|
|
field(`${sum.toString(8).padStart(6, "0")}\0 `, 148, 8);
|
|
return block;
|
|
}
|
|
|
|
const pad = (body: Buffer) => Buffer.concat([body, Buffer.alloc((512 - (body.length % 512)) % 512)]);
|
|
|
|
/** Minimal ustar writer; names over 100 bytes use a pax `path` record. */
|
|
function tar(entries: Entry[]): Buffer {
|
|
const blocks: Buffer[] = [];
|
|
for (const entry of entries) {
|
|
if (Buffer.byteLength(entry.path) > 100) {
|
|
const record = (value: string) => {
|
|
let length = value.length + 3;
|
|
while (`${length} ${value}\n`.length !== length) length = `${length} ${value}\n`.length;
|
|
return `${length} ${value}\n`;
|
|
};
|
|
const body = Buffer.from(record(`path=${entry.path}`));
|
|
blocks.push(header("PaxHeader", "x", body.length, 0o644), pad(body));
|
|
}
|
|
const name = Buffer.byteLength(entry.path) > 100 ? "long" : entry.path;
|
|
if (entry.type === "file") {
|
|
const body = Buffer.from(entry.content);
|
|
blocks.push(header(name, "0", body.length, entry.mode ?? 0o644), pad(body));
|
|
} else if (entry.type === "dir") blocks.push(header(name, "5", 0, 0o755));
|
|
else blocks.push(header(name, entry.type === "symlink" ? "2" : "1", 0, 0o777, entry.target));
|
|
}
|
|
blocks.push(Buffer.alloc(1024));
|
|
return Buffer.concat(blocks);
|
|
}
|
|
|
|
/** Chunk the archive oddly to exercise header/body boundaries. */
|
|
function layer(digest: string, entries: Entry[]): LayerSource {
|
|
const bytes = tar(entries);
|
|
return { digest, open: async function* () { for (let offset = 0; offset < bytes.length; offset += 333) yield bytes.subarray(offset, offset + 333); } };
|
|
}
|
|
|
|
const RUNNERD = "usr/local/bin/paperclip-runnerd";
|
|
const PACK = "opt/paperclip-runner/provider-pack";
|
|
const directories: string[] = [];
|
|
async function outDir() { const directory = await mkdtemp(path.join(os.tmpdir(), "chaos-layers-")); directories.push(directory); return directory; }
|
|
afterEach(async () => { await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true }))); });
|
|
const read = (root: string, relative: string) => readFile(path.join(root, relative), "utf8");
|
|
const exists = (root: string, relative: string) => stat(path.join(root, relative)).then(() => true, () => false);
|
|
|
|
describe("walkTar", () => {
|
|
it("reads ustar, pax long paths, links and normalizes ./ prefixes", async () => {
|
|
const long = `${PACK}/${"x".repeat(120)}/file.txt`;
|
|
const seen: Array<[string, string, string]> = [];
|
|
await walkTar(layer("l", [
|
|
{ path: "./usr/", type: "dir" },
|
|
{ path: long, type: "file", content: "deep" },
|
|
{ path: "a/link", type: "symlink", target: "../b" },
|
|
]).open(), async (entry, body) => {
|
|
let content = "";
|
|
if (entry.type === "file") await body.forward(chunk => { content += chunk.toString(); });
|
|
seen.push([entry.path, entry.type, content || entry.linkTarget]);
|
|
});
|
|
expect(seen).toEqual([["usr", "directory", ""], [long, "file", "deep"], ["a/link", "symlink", "../b"]]);
|
|
});
|
|
|
|
it("rejects parent-directory traversal", () => {
|
|
expect(() => normalizeLayerPath("opt/../../etc/passwd")).toThrow(/\.\./);
|
|
});
|
|
});
|
|
|
|
describe("extractFromLayers", () => {
|
|
it("takes the topmost version of each file and merges lower-only files", async () => {
|
|
const out = await outDir();
|
|
const report = await extractFromLayers([
|
|
layer("base", [{ path: "usr/local/bin/other", type: "file", content: "x" },
|
|
{ path: RUNNERD, type: "file", content: "old", mode: 0o755 },
|
|
{ path: `${PACK}/provider-pack.json`, type: "file", content: "{\"v\":1}" },
|
|
{ path: `${PACK}/lib/keep.js`, type: "file", content: "keep" }]),
|
|
layer("top", [{ path: RUNNERD, type: "file", content: "new", mode: 0o755 },
|
|
{ path: `${PACK}/provider-pack.json`, type: "file", content: "{\"v\":2}" }]),
|
|
], [RUNNERD, PACK], out);
|
|
expect(await read(out, RUNNERD)).toBe("new");
|
|
expect((await stat(path.join(out, RUNNERD))).mode & 0o111).not.toBe(0);
|
|
expect(await read(out, `${PACK}/provider-pack.json`)).toBe("{\"v\":2}");
|
|
expect(await read(out, `${PACK}/lib/keep.js`)).toBe("keep");
|
|
expect(await exists(out, "usr/local/bin/other")).toBe(false);
|
|
expect(report.layersWithMatches).toEqual(["top", "base"]);
|
|
});
|
|
|
|
it("honours .wh.<name> whiteouts for files and whole subtrees", async () => {
|
|
const out = await outDir();
|
|
await extractFromLayers([
|
|
layer("base", [{ path: RUNNERD, type: "file", content: "r" },
|
|
{ path: `${PACK}/provider-pack.json`, type: "file", content: "{}" },
|
|
{ path: `${PACK}/stale.js`, type: "file", content: "stale" },
|
|
{ path: `${PACK}/old-dir/a.js`, type: "file", content: "a" }]),
|
|
layer("top", [{ path: `${PACK}/.wh.stale.js`, type: "file", content: "" },
|
|
{ path: `${PACK}/.wh.old-dir`, type: "file", content: "" }]),
|
|
], [RUNNERD, PACK], out);
|
|
expect(await exists(out, `${PACK}/stale.js`)).toBe(false);
|
|
expect(await exists(out, `${PACK}/old-dir`)).toBe(false);
|
|
expect(await exists(out, `${PACK}/provider-pack.json`)).toBe(true);
|
|
});
|
|
|
|
it("honours opaque directories: only the opaque layer and above contribute children", async () => {
|
|
const out = await outDir();
|
|
await extractFromLayers([
|
|
layer("base", [{ path: RUNNERD, type: "file", content: "r" }, { path: `${PACK}/old.js`, type: "file", content: "old" }]),
|
|
layer("middle", [{ path: PACK, type: "dir" }, { path: `${PACK}/.wh..wh..opq`, type: "file", content: "" },
|
|
{ path: `${PACK}/provider-pack.json`, type: "file", content: "{}" }]),
|
|
layer("top", [{ path: `${PACK}/added.js`, type: "file", content: "added" }]),
|
|
], [RUNNERD, PACK], out);
|
|
expect(await exists(out, `${PACK}/old.js`)).toBe(false);
|
|
expect(await read(out, `${PACK}/provider-pack.json`)).toBe("{}");
|
|
expect(await read(out, `${PACK}/added.js`)).toBe("added");
|
|
});
|
|
|
|
it("deleting a target in a higher layer means it is missing", async () => {
|
|
const out = await outDir();
|
|
await expect(extractFromLayers([
|
|
layer("base", [{ path: RUNNERD, type: "file", content: "r" }, { path: `${PACK}/provider-pack.json`, type: "file", content: "{}" }]),
|
|
layer("top", [{ path: "usr/local/bin/.wh.paperclip-runnerd", type: "file", content: "" }]),
|
|
], [RUNNERD, PACK], out)).rejects.toThrow(/paperclip-runnerd was not found/);
|
|
});
|
|
|
|
it("a whiteout does not hide entries of its own layer", async () => {
|
|
const out = await outDir();
|
|
await extractFromLayers([
|
|
layer("base", [{ path: RUNNERD, type: "file", content: "old" }, { path: `${PACK}/provider-pack.json`, type: "file", content: "{}" }]),
|
|
layer("top", [{ path: `${PACK}/.wh..wh..opq`, type: "file", content: "" }, { path: `${PACK}/provider-pack.json`, type: "file", content: "{\"top\":1}" }]),
|
|
], [RUNNERD, PACK], out);
|
|
expect(await read(out, `${PACK}/provider-pack.json`)).toBe("{\"top\":1}");
|
|
});
|
|
|
|
it("a higher-layer file replacing a directory hides the lower tree", async () => {
|
|
const out = await outDir();
|
|
await extractFromLayers([
|
|
layer("base", [{ path: RUNNERD, type: "file", content: "r" }, { path: `${PACK}/sub/a.js`, type: "file", content: "a" }]),
|
|
layer("top", [{ path: `${PACK}/sub`, type: "file", content: "now a file" }]),
|
|
], [RUNNERD, PACK], out);
|
|
expect(await read(out, `${PACK}/sub`)).toBe("now a file");
|
|
});
|
|
|
|
it("resolves hard links and keeps symlinks inside the pack", async () => {
|
|
const out = await outDir();
|
|
await extractFromLayers([layer("only", [
|
|
{ path: RUNNERD, type: "file", content: "r", mode: 0o755 },
|
|
{ path: `${PACK}/node_modules/tool/cli.js`, type: "file", content: "cli", mode: 0o755 },
|
|
{ path: `${PACK}/node_modules/tool/cli-copy.js`, type: "hardlink", target: `${PACK}/node_modules/tool/cli.js` },
|
|
{ path: `${PACK}/node_modules/.bin/tool`, type: "symlink", target: "../tool/cli.js" },
|
|
])], [RUNNERD, PACK], out);
|
|
expect(await read(out, `${PACK}/node_modules/tool/cli-copy.js`)).toBe("cli");
|
|
expect(await readlink(path.join(out, PACK, "node_modules/.bin/tool"))).toBe("../tool/cli.js");
|
|
expect(await read(out, `${PACK}/node_modules/.bin/tool`)).toBe("cli");
|
|
});
|
|
|
|
it("refuses a parent directory replaced by a symlink", async () => {
|
|
const out = await outDir();
|
|
await expect(extractFromLayers([
|
|
layer("base", [{ path: RUNNERD, type: "file", content: "r" }, { path: `${PACK}/provider-pack.json`, type: "file", content: "{}" }]),
|
|
layer("top", [{ path: "opt/paperclip-runner", type: "symlink", target: "/elsewhere" }]),
|
|
], [RUNNERD, PACK], out)).rejects.toThrow(/replaces parent directory \/opt\/paperclip-runner/);
|
|
});
|
|
});
|
|
|
|
describe("assertControllerMatchesImage", () => {
|
|
const image = { image: "ghcr.io/x/y@sha256:" + "a".repeat(64), contentId: "c".repeat(64), sourceRevision: "d".repeat(40) };
|
|
it("passes when content IDs match", async () => {
|
|
await expect(assertControllerMatchesImage(image, "/unused", "c".repeat(64))).resolves.toEqual({ localContentId: "c".repeat(64) });
|
|
});
|
|
it("names both content IDs and the image revision when they differ", async () => {
|
|
await expect(assertControllerMatchesImage(image, "/unused", "e".repeat(64))).rejects.toThrow(/does not match the Daytona image[\s\S]*d{40}[\s\S]*e{64}/);
|
|
});
|
|
it("accepts a mismatch only for the exact image content ID named by the test override", async () => {
|
|
const previous = process.env.PAPERCLIP_CHAOS_TEST_ACCEPT_IMAGE_CONTENT_ID;
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
|
try {
|
|
process.env.PAPERCLIP_CHAOS_TEST_ACCEPT_IMAGE_CONTENT_ID = "f".repeat(64);
|
|
await expect(assertControllerMatchesImage(image, "/unused", "e".repeat(64))).rejects.toThrow(/does not match the Daytona image/);
|
|
process.env.PAPERCLIP_CHAOS_TEST_ACCEPT_IMAGE_CONTENT_ID = "c".repeat(64);
|
|
await expect(assertControllerMatchesImage(image, "/unused", "e".repeat(64))).resolves.toEqual({ localContentId: "e".repeat(64) });
|
|
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/TEST OVERRIDE[\s\S]*c{64}[\s\S]*e{64}/));
|
|
} finally {
|
|
warn.mockRestore();
|
|
if (previous === undefined) delete process.env.PAPERCLIP_CHAOS_TEST_ACCEPT_IMAGE_CONTENT_ID;
|
|
else process.env.PAPERCLIP_CHAOS_TEST_ACCEPT_IMAGE_CONTENT_ID = previous;
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("assertProviderPackMismatch", () => {
|
|
const controller = { image: "ghcr.io/x/y@sha256:" + "a".repeat(64), providerPackDigest: `sha256:${"1".repeat(64)}` };
|
|
it("accepts a sandbox image whose provider pack differs", () => {
|
|
expect(() => assertProviderPackMismatch(controller,
|
|
{ image: "ghcr.io/x/y@sha256:" + "b".repeat(64), providerPackDigest: `sha256:${"2".repeat(64)}` })).not.toThrow();
|
|
});
|
|
it("refuses another image that carries the same provider pack, which would skip the upload path", () => {
|
|
expect(() => assertProviderPackMismatch(controller,
|
|
{ image: "ghcr.io/x/y@sha256:" + "b".repeat(64), providerPackDigest: controller.providerPackDigest }))
|
|
.toThrow(/carries the controller's provider pack/);
|
|
});
|
|
});
|
|
|
|
describe("copyImageToDir", () => {
|
|
async function fakeSkopeo(root: string, failures: number): Promise<string> {
|
|
const script = path.join(root, "skopeo");
|
|
await writeFile(script, `#!/bin/sh
|
|
dest="\${9#dir:}"
|
|
if [ -n "$(ls -A "$dest")" ]; then echo "not a containers image directory, don't want to overwrite" >&2; exit 1; fi
|
|
n=$(cat "${root}/count" 2>/dev/null || echo 0); n=$((n+1)); echo $n > "${root}/count"
|
|
if [ $n -le ${failures} ]; then echo partial > "$dest/blob"; echo "read: operation timed out" >&2; exit 1; fi
|
|
echo '{}' > "$dest/manifest.json"
|
|
`);
|
|
await chmod(script, 0o755);
|
|
return script;
|
|
}
|
|
|
|
it("retries a copy that failed part-way from an empty directory", async () => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "daytona-skopeo-"));
|
|
try {
|
|
const blobs = path.join(root, "blobs");
|
|
await copyImageToDir({ skopeo: await fakeSkopeo(root, 2), image: "ghcr.io/x/y@sha256:" + "a".repeat(64), blobs });
|
|
expect(await readFile(path.join(root, "count"), "utf8")).toBe("3\n");
|
|
expect(await readFile(path.join(blobs, "manifest.json"), "utf8")).toBe("{}\n");
|
|
await expect(stat(path.join(blobs, "blob"))).rejects.toThrow();
|
|
} finally { await rm(root, { recursive: true, force: true }); }
|
|
});
|
|
|
|
it("kills an attempt that stalls past its time bound and retries from an empty directory", async () => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "daytona-skopeo-"));
|
|
try {
|
|
const script = path.join(root, "skopeo");
|
|
await writeFile(script, `#!/bin/sh
|
|
dest="\${9#dir:}"
|
|
n=$(cat "${root}/count" 2>/dev/null || echo 0); n=$((n+1)); echo $n > "${root}/count"
|
|
if [ $n -eq 1 ]; then echo partial > "$dest/blob"; exec sleep 30; fi
|
|
if [ -n "$(ls -A "$dest")" ]; then exit 1; fi
|
|
echo '{}' > "$dest/manifest.json"
|
|
`);
|
|
await chmod(script, 0o755);
|
|
const blobs = path.join(root, "blobs");
|
|
const started = Date.now();
|
|
await copyImageToDir({ skopeo: script, image: "i", blobs, attemptTimeoutMs: 500 });
|
|
expect(Date.now() - started).toBeLessThan(10_000);
|
|
expect(await readFile(path.join(root, "count"), "utf8")).toBe("2\n");
|
|
expect(await readFile(path.join(blobs, "manifest.json"), "utf8")).toBe("{}\n");
|
|
} finally { await rm(root, { recursive: true, force: true }); }
|
|
});
|
|
|
|
it("gives up after the last attempt with skopeo's error", async () => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "daytona-skopeo-"));
|
|
try {
|
|
await expect(copyImageToDir({ skopeo: await fakeSkopeo(root, 5), image: "i", blobs: path.join(root, "blobs"), attempts: 2 }))
|
|
.rejects.toThrow(/operation timed out/);
|
|
expect(await readFile(path.join(root, "count"), "utf8")).toBe("2\n");
|
|
} finally { await rm(root, { recursive: true, force: true }); }
|
|
});
|
|
});
|
|
|
|
describe("prepareDaytonaImageArtifacts with a shared cache", () => {
|
|
const sha = (bytes: Buffer | string) => createHash("sha256").update(bytes).digest("hex");
|
|
const revision = "a".repeat(40);
|
|
|
|
async function fakeImage(root: string, image: { packRevision?: string; labels?: Record<string, string> } = {}): Promise<string> {
|
|
const source = path.join(root, "image");
|
|
await mkdir(source, { recursive: true });
|
|
const elf = Buffer.alloc(64); elf.writeUInt32BE(0x7f454c46, 0); elf[4] = 2; elf[5] = 1; elf.writeUInt16LE(62, 18);
|
|
const pack = JSON.stringify({ schema: "paperclip-runner/remote-provider-pack/v1", digest: `sha256:${"b".repeat(64)}`,
|
|
payload: { runnerSourceRevision: image.packRevision ?? revision } });
|
|
const layerBytes = tar([
|
|
{ path: RUNNERD, type: "file", content: elf.toString("latin1"), mode: 0o755 },
|
|
{ path: `${PACK}/provider-pack.json`, type: "file", content: pack },
|
|
]);
|
|
const config = Buffer.from(JSON.stringify({ os: "linux", architecture: "amd64",
|
|
config: { Labels: { "io.paperclip.runner.content-id": "c".repeat(64), "org.opencontainers.image.revision": revision, ...image.labels } } }));
|
|
await writeFile(path.join(source, sha(layerBytes)), layerBytes);
|
|
await writeFile(path.join(source, sha(config)), config);
|
|
await writeFile(path.join(source, "manifest.json"), JSON.stringify({ config: { digest: `sha256:${sha(config)}` },
|
|
layers: [{ digest: `sha256:${sha(layerBytes)}`, mediaType: "application/vnd.oci.image.layer.v1.tar" }] }));
|
|
const barrier = path.join(root, "barrier");
|
|
await mkdir(barrier);
|
|
const script = path.join(root, "skopeo");
|
|
await writeFile(script, `#!/bin/sh
|
|
dest="\${9#dir:}"
|
|
touch "${barrier}/$$"
|
|
while [ "$(ls "${barrier}" | wc -l)" -lt 2 ]; do sleep 0.05; done
|
|
cp -R "${source}/." "$dest/"
|
|
`);
|
|
await chmod(script, 0o755);
|
|
return script;
|
|
}
|
|
|
|
it("lets two runs extract the same image at once; both get a usable receipt", async () => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "daytona-cache-"));
|
|
directories.push(root);
|
|
const skopeo = await fakeImage(root);
|
|
const image = `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:${"d".repeat(64)}`;
|
|
const cacheRoot = path.join(root, "cache");
|
|
const [first, second] = await Promise.all([
|
|
prepareDaytonaImageArtifacts({ image, cacheRoot, skopeo }),
|
|
prepareDaytonaImageArtifacts({ image, cacheRoot, skopeo }),
|
|
]);
|
|
expect(second.runnerdPath).toBe(first.runnerdPath);
|
|
for (const receipt of [first, second]) {
|
|
expect((await stat(receipt.runnerdPath)).isFile()).toBe(true);
|
|
expect(await readFile(path.join(receipt.providerPackPath, "provider-pack.json"), "utf8")).toContain(revision);
|
|
}
|
|
});
|
|
|
|
async function extract(image: { packRevision?: string; labels?: Record<string, string> }) {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "daytona-cache-"));
|
|
directories.push(root);
|
|
const skopeo = await fakeImage(root, image);
|
|
await writeFile(path.join(root, "barrier", "other"), "");
|
|
return prepareDaytonaImageArtifacts({ image: `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:${"9".repeat(64)}`, cacheRoot: path.join(root, "cache"), skopeo });
|
|
}
|
|
const runnerCommit = "b".repeat(40);
|
|
|
|
it("accepts a pack another commit built when the image names that commit as its Runner's, and reads an empty label as absent", async () => {
|
|
const receipt = await extract({ packRevision: runnerCommit, labels: { [RUNNER_REVISION_LABEL]: runnerCommit } });
|
|
expect(receipt).toMatchObject({ sourceRevision: revision, providerPackRunnerSourceRevision: runnerCommit });
|
|
await expect(extract({ labels: { [RUNNER_REVISION_LABEL]: "" } })).resolves.toMatchObject({ sourceRevision: revision, providerPackRunnerSourceRevision: revision });
|
|
});
|
|
|
|
it.each<[string, { packRevision?: string; labels?: Record<string, string> }, RegExp]>([
|
|
["the image names another Runner commit", { packRevision: runnerCommit, labels: { [RUNNER_REVISION_LABEL]: "e".repeat(40) } },
|
|
/built from b{40}, but the image label io\.paperclip\.runner\.source-revision is e{40}/],
|
|
["the image names its Runner and carries its own commit's pack", { labels: { [RUNNER_REVISION_LABEL]: runnerCommit } },
|
|
/built from a{40}, but the image label io\.paperclip\.runner\.source-revision is b{40}/],
|
|
["no Runner commit is named and the pack is another commit's", { packRevision: runnerCommit },
|
|
/built from b{40}, but the image label org\.opencontainers\.image\.revision is a{40}/],
|
|
["the Runner commit is not a full commit", { labels: { [RUNNER_REVISION_LABEL]: "bbbbbbb" } }, /io\.paperclip\.runner\.source-revision is not a full commit/],
|
|
])("refuses the image when %s", async (_label, image, message) => {
|
|
await expect(extract(image)).rejects.toThrow(message);
|
|
});
|
|
|
|
it("leaves a corrupt leftover in place and publishes beside it", async () => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "daytona-cache-"));
|
|
directories.push(root);
|
|
const skopeo = await fakeImage(root);
|
|
await writeFile(path.join(root, "barrier", "other"), "");
|
|
const image = `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:${"e".repeat(64)}`;
|
|
const cacheRoot = path.join(root, "cache");
|
|
await mkdir(path.join(cacheRoot, "e".repeat(64)), { recursive: true });
|
|
await writeFile(path.join(cacheRoot, "e".repeat(64), "junk"), "partial");
|
|
const receipt = await prepareDaytonaImageArtifacts({ image, cacheRoot, skopeo });
|
|
expect((await stat(receipt.runnerdPath)).isFile()).toBe(true);
|
|
expect(receipt.runnerdPath.startsWith(path.join(cacheRoot, `${"e".repeat(64)}.`))).toBe(true);
|
|
expect(await exists(cacheRoot, `${"e".repeat(64)}/junk`)).toBe(true);
|
|
});
|
|
|
|
it("two runs replacing a corrupt leftover at once both keep a usable cache", async () => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "daytona-cache-"));
|
|
directories.push(root);
|
|
const skopeo = await fakeImage(root);
|
|
const image = `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:${"f".repeat(64)}`;
|
|
const cacheRoot = path.join(root, "cache");
|
|
await mkdir(path.join(cacheRoot, "f".repeat(64)), { recursive: true });
|
|
await writeFile(path.join(cacheRoot, "f".repeat(64), "junk"), "partial");
|
|
const receipts = await Promise.all([1, 2].map(() => prepareDaytonaImageArtifacts({ image, cacheRoot, skopeo })));
|
|
for (const receipt of receipts) expect((await stat(receipt.runnerdPath)).isFile()).toBe(true);
|
|
expect(await exists(cacheRoot, `${"f".repeat(64)}/junk`)).toBe(true);
|
|
});
|
|
});
|