Files
PaperClipAI/server/src/services/native-runtime/remote-runner-recovery-diagnostics.test.ts
T
DottaandClaude 80b2369f26 fix(native): keep remote runnerd exit evidence and report it on failed recovery (#20907)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native runs on Daytona start a detached `paperclip-runnerd` in the
sandbox, and the controller adopts it after a restart
> - On staging, recovery fails with
`runner_remote_process_identity_unavailable` when the Runner is gone,
but nobody can see why it exited
> - The launch script sends runnerd's stdout and stderr to `/dev/null`,
so only a panic or a graceful error reaches `runnerd.stderr.log`, and
the recovery event does not read that file
> - This pull request keeps runnerd's stderr in a bounded file in its
private diagnostics directory, and adds the exit reason to the
`native.remote_runner_recovery_failed` event
> - The benefit is that the reason a Runner exited shows in the run log
on staging without SSH, which the class R investigation needs

## Linked Issues or Issue Description

**What happened?**
Staging runs fail with `runner_remote_process_identity_unavailable`
after the remote Runner exits (`native.remote_runner_recovery_failed`
with `stage: process_verification`, `reason: process_not_running`). The
event does not say why the Runner exited.

**What did you expect?**
The run log names the Runner's exit reason: its durable
`recoverableFailure` and diagnostics, and what it wrote to stderr.

**Steps to reproduce**
Restart-chaos re-wake and stall cells reproduce the refusal. Each failed
run log shows only `runnerLifecycle` and `runnerSettled`.

Refs #20893

## What Changed

- `REMOTE_RUNNER_CHILD_LAUNCH_SCRIPT` sends runnerd's stderr to
`diagnostics/runnerd.process-stderr.log` (mode 0600, in the 0700
directory) instead of `/dev/null`.
  - At launch, a file above 1 MiB is rotated once to `.1`.
- While runnerd runs, a detached trimmer is a disk backstop. Past 8 MiB,
it keeps the last 1 MiB. It checks every 15 s and ends when runnerd
ends. It is double-forked with its own argv, so it is not a child of
runnerd and does not carry runnerd's arguments. runnerd's own exit
reason goes to `runnerd.stderr.log`, which is never trimmed.
- A symlink or non-file at that path keeps the old `/dev/null` behavior.
- Stdout is unchanged (`/dev/null`). Runnerd's PID is still the launch
shell's PID, so the identity marker and fingerprint are unchanged.
- `remote-runner-recovery-diagnostics.ts` has a read-only
`REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT`. It prints a 2 KiB tail of
`runnerd.stderr.log` and of `runnerd.process-stderr.log`. It reads the
session diagnostics directory first, then the shared runtime-root
directory used by external Runners (Dot, Muse, grok_bot). It never reads
through a symlink. Each file keeps its own share of the 4 KiB budget.
- When recovery's process verification finds `process_not_running`, the
diagnostic adds these fields:
- `runnerRecoverableFailure`: a code-shaped string from
`runner-state.json`;
- `runnerDiagnostics`: the last 4 entries, redacted, 500 characters
each;
  - `runnerExitEvidence`: the redacted file tails, 4 KiB at most.
  
  `native.remote_runner_recovery_failed` carries them.
- The live process monitor's exit report now puts the durable state
summary first, then the file tails. Before, it used one or the other.
- `run-failure-diagnostics.ts` is unchanged. It still copies only the
closed labels, so no free text reaches failure reports.

## Verification

- `pnpm exec vitest run
server/src/services/native-runtime/remote-runner-launch-stderr.test.ts`:
the launch writer keeps stderr in the file, writes the identity marker
with the child's PID, appends across relaunches, rotates an oversized
file, trims a growing file while the child runs, and never writes
through a symlink.
- `pnpm exec vitest run
server/src/services/native-runtime/remote-runner-recovery-diagnostics.test.ts`:
the evidence script output is bounded and refuses symlinks. Redaction
and bounds hold, and the new fields survive the event payload.
- `pnpm exec vitest run
server/src/services/native-runtime/native-session-executor.test.ts`
passes (1374 tests). One expectation was updated for the combined exit
report.
- `npx tsc --noEmit -p server/tsconfig.json` is clean.
- Older runner images: the script is server-side. It adds only `wc`,
`tr`, `tail`, `cat`, `mv`, `sleep` and `kill`. The script already needed
`node`, `date`, `chmod`, `mv` and `printf`, so any image that launched
runnerd before has these tools. The runner content ID is unchanged, so
the current Daytona image runs it unmodified. The restart-chaos waves
run on that image.

## Risks

- Low. A sandbox disk that is already full could make the stderr
redirect fail. `exec ... 2>>file` then fails, and the launch reports
`runner_remote_process_identity_unavailable` the same way a launch that
cannot write its identity marker does. The marker is written first, in
the same directory tree.
- Stderr content stays in the sandbox. Only a redacted 4 KiB tail goes
into the instance's own run log (run-log data path; not Telemetry and
not Observability).
- No wait is added before `turn.start`. The evidence read runs only on
the recovery failure path, with its own 10 s bound.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), 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 <noreply@anthropic.com>
2026-11-11 15:31:04 -06:00

160 lines
10 KiB
TypeScript

import { execFileSync } from "node:child_process";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
REMOTE_RECOVERY_MARKER_READ_SCRIPT, REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT, REMOTE_RUNNER_EXIT_EVIDENCE_MAX_CHARS,
REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, RemoteRunnerRecoveryError, boundRemoteRunnerExitEvidence, describeExitedRemoteRunnerReason,
readRemoteRunnerRecoveryDiagnostic, readRemoteRunnerRecoveryError,
} from "./remote-runner-recovery-diagnostics.js";
function shellExit(script: string, args: string[]) {
try {
execFileSync("sh", ["-c", script, "recovery-test", ...args], { stdio: "pipe", timeout: 2_000 });
return 0;
} catch (error) {
return (error as { status: number }).status;
}
}
describe("remote recovery diagnostic shell receipts", () => {
it("keeps permission-denied liveness uncertain", async () => {
const root = await mkdtemp(join(tmpdir(), "remote-probe-denied-"));
const marker = join(root, "marker");
const hook = join(root, "denied.cjs");
try {
await writeFile(marker, `nonce\n${process.pid}\n2026-10-26T00:00:00.000Z\nrunner\n`);
await writeFile(hook, 'process.kill = () => { throw Object.assign(new Error("denied"), { code: "EPERM" }); };');
const script = `NODE_OPTIONS="--require=${hook}"; export NODE_OPTIONS; kill() { return 1; }; ` + REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT;
expect(shellExit(script, [marker, "nonce", "runner", String(process.pid)])).toBe(46);
expect(() => process.kill(process.pid, 0)).not.toThrow();
} finally { await rm(root, { recursive: true, force: true }); }
});
it.each([
{ fingerprint: "linux:abcd-1234:100", code: 45 },
{ fingerprint: "linux:abcd-1234:101", code: 47 },
{ fingerprint: "", code: 44 },
])("requires the saved generation before accepting a zombie receipt (%j)", async ({ fingerprint, code }) => {
const root = await mkdtemp(join(tmpdir(), "remote-probe-zombie-"));
const marker = join(root, "marker");
try {
await writeFile(marker, `nonce\n${process.pid}\n2026-10-26T00:00:00.000Z\nrunner\n`);
await writeFile(join(root, "cmdline"), "");
await writeFile(join(root, "stat"), `${process.pid} (runner (child)) ${["Z", ...Array(18).fill("0"), 100].join(" ")}\n`);
await writeFile(join(root, "boot_id"), "abcd-1234\n");
const script = REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT
.replaceAll('"/proc/$pid/cmdline"', JSON.stringify(join(root, "cmdline")))
.replaceAll('"/proc/" + pid + "/cmdline"', JSON.stringify(join(root, "cmdline")))
.replaceAll('"/proc/" + pid + "/stat"', JSON.stringify(join(root, "stat")))
.replaceAll('"/proc/sys/kernel/random/boot_id"', JSON.stringify(join(root, "boot_id")));
expect(shellExit(script, [marker, "nonce", "runner", String(process.pid), fingerprint])).toBe(code);
} finally { await rm(root, { recursive: true, force: true }); }
});
it("distinguishes missing, unsafe and valid marker reads without exposing their contents", async () => {
const root = await mkdtemp(join(tmpdir(), "remote-recovery-read-"));
const marker = join(root, "marker");
try {
expect(shellExit(REMOTE_RECOVERY_MARKER_READ_SCRIPT, [marker])).toBe(31);
await writeFile(join(root, "target"), "private marker");
await symlink(join(root, "target"), marker);
expect(shellExit(REMOTE_RECOVERY_MARKER_READ_SCRIPT, [marker])).toBe(32);
await rm(marker);
await writeFile(marker, "private marker");
expect(shellExit(REMOTE_RECOVERY_MARKER_READ_SCRIPT, [marker])).toBe(0);
} finally { await rm(root, { recursive: true, force: true }); }
});
it("distinguishes a torn marker from a changed identity before signalling any process", async () => {
const root = await mkdtemp(join(tmpdir(), "remote-recovery-check-"));
const marker = join(root, "marker");
const args = [marker, "nonce", "runner", String(process.pid)];
try {
expect(shellExit(REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT, args)).toBe(41);
await writeFile(marker, "nonce\n");
expect(shellExit(REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT, args)).toBe(43);
await writeFile(marker, `other-nonce\n${process.pid}\n2026-10-14T00:00:00.000Z\nrunner\n`);
expect(shellExit(REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT, args)).toBe(44);
} finally { await rm(root, { recursive: true, force: true }); }
});
it("reads only closed labels through bounded causes and contains hostile getters", () => {
const diagnostic = { stage: "process_verification", reason: "process_generation_changed" } as const;
const error = new RemoteRunnerRecoveryError(diagnostic);
expect(readRemoteRunnerRecoveryError(new Error("private outer text", { cause: error }))).toEqual(diagnostic);
expect(readRemoteRunnerRecoveryError(Object.assign(new Error("private"), {
code: error.code, remoteRunnerRecovery: { stage: "private", reason: "process_generation_changed" },
}))).toBeNull();
expect(readRemoteRunnerRecoveryError(Object.defineProperty({}, "code", { get() { throw new Error("private"); } }))).toBeNull();
const cyclic: { cause?: unknown } = {};
cyclic.cause = cyclic;
expect(readRemoteRunnerRecoveryError(cyclic)).toBeNull();
});
it("reports a retired owned child as unavailable before checking its command line", async () => {
const root = await mkdtemp(join(tmpdir(), "remote-recovery-retired-"));
const marker = join(root, "marker");
const pid = execFileSync("sh", ["-c", "printf '%s' $$"], { encoding: "utf8" }).trim();
try {
await writeFile(marker, `nonce\n${pid}\n2026-10-14T00:00:00.000Z\nrunner\n`);
expect(shellExit(REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT, [marker, "nonce", "runner", pid])).toBe(45);
} finally { await rm(root, { recursive: true, force: true }); }
});
});
describe("exited remote runner evidence", () => {
it("prints bounded tails of the exit diagnostic and redirected stderr, never through a symlink", async () => {
const root = await mkdtemp(join(tmpdir(), "remote-exit-evidence-"));
const directory = join(root, "diagnostics");
try {
expect(execFileSync("sh", ["-c", REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, "t", directory], { encoding: "utf8" })).toBe("");
await mkdir(directory);
await writeFile(join(directory, "runnerd.stderr.log"), "paperclip-runnerd: transport reconnect grace exceeded");
await writeFile(join(directory, "runnerd.process-stderr.log"), `${"x".repeat(10_000)}\nlast stderr line`);
const output = execFileSync("sh", ["-c", REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, "t", directory], { encoding: "utf8" });
expect(output).toContain("== runnerd.stderr.log\npaperclip-runnerd: transport reconnect grace exceeded");
expect(output).toContain("== runnerd.process-stderr.log\n");
expect(output).toContain("last stderr line");
expect(output.length).toBeLessThan(4_200);
// Each file keeps its share: a long stderr tail cannot crowd out the exit diagnostic.
const bounded = boundRemoteRunnerExitEvidence(output, text => text)!;
expect(bounded.length).toBeLessThanOrEqual(REMOTE_RUNNER_EXIT_EVIDENCE_MAX_CHARS);
expect(bounded).toContain("paperclip-runnerd: transport reconnect grace exceeded");
expect(bounded).toContain("last stderr line");
// The first candidate directory with evidence wins; a later shared directory is read only when it has none.
const shared = join(root, "shared");
await mkdir(shared);
await writeFile(join(shared, "runnerd.stderr.log"), "shared runner exit");
expect(execFileSync("sh", ["-c", REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, "t", directory, shared], { encoding: "utf8" })).not.toContain("shared runner exit");
expect(execFileSync("sh", ["-c", REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, "t", join(root, "missing"), shared], { encoding: "utf8" }))
.toBe("== runnerd.stderr.log\nshared runner exit\n");
await writeFile(join(root, "secret"), "private");
await rm(join(directory, "runnerd.stderr.log"));
await symlink(join(root, "secret"), join(directory, "runnerd.stderr.log"));
expect(execFileSync("sh", ["-c", REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, "t", directory], { encoding: "utf8" })).not.toContain("private");
} finally { await rm(root, { recursive: true, force: true }); }
});
it("names the durable exit reason, redacted and bounded", () => {
const redact = (text: string) => text.replaceAll("sk-secret", "[redacted]");
expect(describeExitedRemoteRunnerReason({ lifecycle: "suspended", recoverableFailure: "transport_reconnect_grace_exceeded",
diagnostics: ["a", "b", "c", "d", "token sk-secret", 7] }, redact)).toEqual({
runnerRecoverableFailure: "transport_reconnect_grace_exceeded", runnerDiagnostics: ["b", "c", "d", "token [redacted]"] });
expect(describeExitedRemoteRunnerReason({ recoverableFailure: "free text with spaces" }, redact)).toEqual({});
expect(describeExitedRemoteRunnerReason(null, redact)).toEqual({});
expect(boundRemoteRunnerExitEvidence(" ", redact)).toBeNull();
expect(boundRemoteRunnerExitEvidence("y".repeat(9_000), redact)!.length).toBeLessThanOrEqual(REMOTE_RUNNER_EXIT_EVIDENCE_MAX_CHARS);
});
it("keeps the exit reason through the recorded event payload", () => {
const diagnostic = { stage: "process_verification", reason: "process_not_running", runnerLifecycle: "ready", runnerSettled: false,
runnerRecoverableFailure: "lease_expired_requires_bootstrap", runnerDiagnostics: ["connection lease expired"],
runnerExitEvidence: "== runnerd.stderr.log\npaperclip-runnerd: connection lease expired" };
expect(readRemoteRunnerRecoveryDiagnostic(JSON.parse(JSON.stringify(diagnostic)))).toEqual(diagnostic);
expect(readRemoteRunnerRecoveryDiagnostic({ ...diagnostic, runnerRecoverableFailure: "bad value", runnerDiagnostics: [1],
runnerExitEvidence: 4 })).toEqual({ stage: "process_verification", reason: "process_not_running", runnerLifecycle: "ready", runnerSettled: false });
});
});