Files
PaperClipAI/tests/restart-chaos/evidence.ts
DottaandClaude Opus 5.5 edf7edac60 test(restart-chaos): keep wake evidence and early run events, and word staging-mix rounds unambiguously (#21173)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart chaos harness runs agent tasks across server swaps and
keeps evidence for each failure
> - Wave `w-20261112T181948-s7101` had two "run started after the task
was done" cases that could not be traced
> - The wave deleted its database before anyone saved which wake started
those runs, which server created them, or how the task status changed
> - The evidence bundle also kept only the last 200 events of a run, so
it dropped the first 291 events of a Retry run, including its wake
payload
> - The staging-mix wording made one Codex agent refuse to redo an
interrupted round, and the task blocked on a harness artefact
> - This pull request saves that evidence for every task, keeps a run's
first events, and rewords the round rules without changing the grade

## Linked Issues or Issue Description

Refs #21125, #21168.

**What existing behavior does this improve?**
Restart chaos evidence capture and the staging-mix task wording.

**Subsystem affected**
Test harness only: `tests/restart-chaos/`. No product code changes.

**Current behavior**
- The harness does not save a task's wake rows, run context snapshots or
status history before the wave database is deleted.
- `evidence.ts` keeps only the last 200 events per run.
- The task tells the agent "do not skip, repeat or shorten any" round,
and the follow-up says "do not restart any". An agent read that as
"never re-run an interrupted round".

**Proposed behavior**
- Save, for every task, the wake rows, run snapshots, status changes and
serving server generations.
- Keep a run's first 400 and last 200 events, with a marker between
them.
- Say plainly that every round must appear in the ledger exactly once,
that an interrupted round must be run again, and that a round already in
the ledger must never be run again.

**Reason and benefit**
Wake and run origins can be traced after the wave, and the wording no
longer creates failures that come only from the harness.

## What Changed

- New `wake-evidence.ts`, called once at the end of each wave while the
database still exists. It writes `wake-evidence/<task>.json` for every
task. Each file holds:
- for each run: its `context_snapshot`, invocation source, trigger and
wakeup request id;
- the `agent_wakeup_requests` rows for the issue and for each run:
reason, source, trigger detail, requesting actor, idempotency key,
payload and times;
  - the issue's status changes from `activity_log`.

Each wake and run names the server generations alive when it was created
(`servingAtCreate`): pid, boot id, epoch and process space from
`controller_instances`, plus the harness's primary or secondary role
during an overlap. Each run also names its owning controller (`owner`).
`wake-evidence/servers.json` lists every controller and harness server
window. Known secret values are redacted.
- `evidence.ts` keeps all of a run's events, or the first 400 and the
last 200 with an `omittedEvents` marker between them.
- `staging-mix.ts` only changes the wording; the grading is unchanged.
The new text:
- every round must appear in the ledger file exactly once, with the hash
the command printed;
- before a round, read the ledger; a round whose line is there is
finished and must never run again;
  - a round interrupted before its line was written must be run again.

  The follow-up comment says the same.
- `main.ts` gains one call; the file stays at 1,000 lines. README
updated.

## Verification

- `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts`:
59 files, 711 tests pass. That includes a real embedded PostgreSQL test
that writes a wake, a run, a status change and a controller row, then
checks the evidence file.
- `node scripts/typecheck-test-projects.mjs tests/restart-chaos`:
passes.
- Unit tests cover the serving-generation join during an overlap, the
per-issue join, the first 400 and last 200 events of a 1,291-event run,
and the new wording.
- Not run: a live wave with this change.

## Risks

- Low risk. Test harness only.
- Evidence capture is one set of reads per wave. A failure is recorded
as `wake_evidence_failed` and does not fail the wave.
- Known master CI failures, not touched here: the storage S3 multipart
throttle test and the Runner native-distribution-integrity test.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code
with tool use (shell, file edits). Extended reasoning was available.

## 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>
2026-11-12 13:41:14 -06:00

114 lines
6.6 KiB
TypeScript

import { mkdir, open, writeFile } from "node:fs/promises";
import path from "node:path";
import type { ChaosApi } from "./api.js";
import { replayCommand } from "./config.js";
import type { TimelineEntry } from "./timeline.js";
import type { FaultReceipt, OracleArtifacts, TaskGrade, TaskRecord, WavePlan } from "./types.js";
export { captureWakeEvidence, wakeEvidenceOnce } from "./wake-evidence.js";
const LOG_BEFORE_BYTES = 128 * 1024;
const LOG_AFTER_BYTES = 512 * 1024;
export const EVENTS_HEAD = 400;
export const EVENTS_TAIL = 200;
const OBSERVER_POLL_LINE = /INFO\S*: \S*(?:GET|HEAD) \/(?:issues\/[0-9a-f-]+(?:\/runs)?|ready|liveness|health) 200/;
type Json = Record<string, any>;
/** Canary (soak U7): never let a provider key reach an evidence file. */
export function redactKnownSecrets(text: string, secrets: readonly string[]): string {
let out = text;
for (const value of secrets) if (value.length >= 8) out = out.split(value).join("[REDACTED]");
return out;
}
export function knownSecretValues(env: NodeJS.ProcessEnv = process.env): string[] {
// Any *KEY, *TOKEN, *SECRET or *PASSWORD name, including PAPERCLIP_AGENT_PRIVATE_KEY and AWS_SECRET_ACCESS_KEY.
return Object.entries(env).filter(([key, value]) => value && /(?:KEY|TOKEN|SECRET|PASSWORD)$/.test(key)).map(([, value]) => value!);
}
export async function runEvents(api: ChaosApi, runId: string): Promise<Json[]> {
const head: Json[] = [], tail: Json[] = [];
let total = 0, afterSeq = 0, omittedFrom: unknown = null, omittedTo: unknown = null;
for (let page = 0; page < 200; page += 1) {
const rows = await api.get<Json[]>(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=500`);
if (!rows?.length) break;
for (const row of rows) {
total += 1;
if (head.length < EVENTS_HEAD) { head.push(row); continue; }
tail.push(row);
if (tail.length > EVENTS_TAIL) { const dropped = tail.shift()!; omittedFrom ??= dropped.seq ?? null; omittedTo = dropped.seq ?? null; }
}
const next = Number(rows[rows.length - 1]?.seq);
if (!Number.isFinite(next) || next <= afterSeq || rows.length < 500) break;
afterSeq = next;
}
const omitted = total - head.length - tail.length;
return omitted > 0 ? [...head, { omittedEvents: omitted, fromSeq: omittedFrom, toSeq: omittedTo }, ...tail] : [...head, ...tail];
}
async function logWindow(serverLogPath: string, faults: readonly FaultReceipt[]): Promise<string> {
if (!faults.length) return "";
const handle = await open(serverLogPath, "r").catch(() => null);
if (!handle) return "";
try {
const size = (await handle.stat()).size;
const parts: string[] = [];
for (const fault of faults) {
const start = Math.max(0, fault.serverLogOffsetAtStart - LOG_BEFORE_BYTES);
const end = Math.min(size, (fault.serverLogOffsetAtReady ?? fault.serverLogOffsetAtStart) + LOG_AFTER_BYTES);
const buffer = Buffer.alloc(Math.max(0, end - start));
await handle.read(buffer, 0, buffer.length, start);
// Drop the observer's own polling request lines; they bury the recovery log.
const text = buffer.toString("utf8").split("\n").filter(line => !OBSERVER_POLL_LINE.test(line)).join("\n");
parts.push(`===== ${fault.faultId} ${fault.kind} bytes ${start}-${end} (observer GET lines removed) =====\n${text}`);
}
return parts.join("\n");
} finally { await handle.close(); }
}
/** Bundle everything a fix-failed-paperclip-run session needs to start (plan §5.7). */
export async function writeEvidenceBundle(input: {
directory: string; api: ChaosApi; plan: WavePlan; record: TaskRecord; grade: TaskGrade; artifacts: OracleArtifacts | null;
faults: readonly FaultReceipt[]; timeline: readonly TimelineEntry[]; serverLogPath: string; gitSha: string; gitDirty: boolean;
issue: Json | null; secrets: readonly string[];
}): Promise<string> {
const { directory, api, record } = input;
await mkdir(directory, { recursive: true, mode: 0o700 });
const write = (name: string, value: unknown) => writeFile(path.join(directory, name),
redactKnownSecrets(typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`, input.secrets), { mode: 0o600 });
const errors: string[] = [];
const attempt = async (label: string, work: () => Promise<void>) => {
try { await work(); } catch (error) { errors.push(`${label}: ${error instanceof Error ? error.message : String(error)}`); }
};
const relevant = input.faults.filter(fault => input.grade.crossingFaults.includes(fault.faultId) || record.faultIds.includes(fault.faultId));
await write("meta.json", {
schema: "paperclip.restart-chaos.evidence/v1", waveId: input.plan.waveId, seed: input.plan.seed, taskId: record.plan.taskId,
gitSha: input.gitSha, gitDirty: input.gitDirty, signature: input.grade.signature, replay: replayCommand(input.plan.waveId, record.plan.taskId),
issueId: record.issueId, identifier: record.identifier, task: record.plan, options: input.plan.options,
});
await write("grade.json", input.grade);
await write("task-record.json", record);
await write("faults.json", relevant.length ? relevant : input.faults);
await write("startup-phases.json", (relevant.length ? relevant : input.faults).map(fault => ({ faultId: fault.faultId, kind: fault.kind,
startedAt: fault.startedAt, stoppedAt: fault.stoppedAt, restartedAt: fault.restartedAt, healthyAt: fault.healthyAt, readyAt: fault.readyAt, phases: fault.phases,
...(fault.repeatedRestart ? { repeatedRestarts: fault.repeatedRestart.restarts } : {}) })));
await write("timeline.json", input.timeline);
if (input.artifacts) await write("oracle-artifacts.json", input.artifacts);
await attempt("server-log", async () => write("server-log-window.txt", await logWindow(input.serverLogPath, relevant.length ? relevant : input.faults)));
if (record.issueId) {
await attempt("issue", async () => write("issue.json", input.issue ?? await api.get(`/api/issues/${record.issueId}`)));
let runs: Json[] = [];
await attempt("runs", async () => { runs = await api.get<Json[]>(`/api/issues/${record.issueId}/runs`); await write("runs.json", runs); });
for (const run of runs) {
const runId = String(run.runId ?? run.id);
await attempt(`events ${runId}`, async () => write(`run-${runId}-events.json`, await runEvents(api, runId)));
await attempt(`workspace-operations ${runId}`, async () => write(`run-${runId}-workspace-operations.json`,
await api.get(`/api/heartbeat-runs/${runId}/workspace-operations`)));
}
await attempt("comments", async () => write("comments.json", await api.get(`/api/issues/${record.issueId}/comments`)));
}
if (errors.length) await write("collection-errors.json", errors);
return directory;
}