mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 01:50:13 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart chaos harness (`tests/restart-chaos/`) restarts the control plane during real agent tasks and grades each task on rules R1–R6 > - One known product bug (RC-06) leaves a completed run "awaiting accounting". The company hard stop then refuses all new work, so one stuck row fails every later task in the wave > - That masks every other restart bug in the wave. Waves also had no record of what they spent > - This pull request adds an opt-in RC-06 mask, records wave spend, and lets a replay keep or add the mask > - The benefit is that chaos waves can find new restart bugs while RC-06 is open, and stay inside a known spend ## Linked Issues or Issue Description Refs #19477 (the Phase 1 harness this extends). **What existing behavior does this improve?** Restart chaos waves. One stuck accounting row (RC-06) hard-stops the isolated Chaos Lab company. All later tasks then rest blocked "over budget", and a Retry is refused with "Company cannot start work while completed runs await accounting". Two waves went 2/6 and 0/6 for this one reason. **Subsystem affected** Test harness only: `tests/restart-chaos/` (config, seed, scheduler, ledger, supervisor, main, README). **Current behavior** - No way to see past RC-06 without disabling the budget. - Wave spend is not recorded. - `--replay` rejected any mask flag, and it was not documented that the saved plan carries the mask. **Proposed behavior** - `--rc06-masked` keeps the budget amount and turns off only the hard stop on the isolated company. Masked tasks are labeled in the ledger and summary. - Each wave records its spend. - A replay keeps the source plan's masks and may add the RC-06 mask. ## What Changed - `--rc06-masked` (wave mode): after the company is created, the seed upserts the company budget policy with the same amount and `hardStopEnabled: false`. It writes `seed_mask_rc06` to the timeline. The plan stores `options.masks = ["rc06"]`. - The accounting gate in `budgets.ts` (`observedBlocks`) applies only when `hardStopEnabled` is true, so the mask lifts it. No product code changes. - Ledger lines carry `masks`. `SUMMARY.md` labels the cell and the latest-wave row `rc06-masked`. - Wave spend: before the sweep, `main.ts` reads `/api/companies/:id/costs/summary?period=all` (each wave owns its company), writes `wave_spend` to the timeline and prints it. If the wave stops early, cleanup records it once, best effort, before the server stops. - Load: #19513 already records `loadAvg1m` on each fault receipt. This branch first added the same value under another name, and the rebase removed it. The README now documents `loadAvg1m` and the load-suspect threshold. - Replay: `--replay <wave>/<task>` keeps the masks saved in the source `plan.json`. `--replay … --rc06-masked` adds the RC-06 mask. A replay never drops a mask. - README documents the flag, spend, load and the replay rule. - New unit tests: replay keeps saved masks and the replay flag adds the mask; the masked seed posts the company policy with the same amount and `hardStopEnabled: false` and records `seed_mask_rc06`, and an unmasked seed makes no policy call. ## Verification - `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts`: 71/71 pass (after rebase onto master with #19513). - `node scripts/typecheck-test-projects.mjs tests/restart-chaos`: pass. - Live: 4 masked local waves ran with this code (seeds 3307, 4409, 5501, 6619; Codex, ACPX Claude and OpenCode). - `seed_mask_rc06` appeared and no task was blocked by the accounting gate, even though `pendingRunCount` was 1–8 at wave end. - `wave_spend` was recorded each time (38¢–127¢ per wave). - The 1-minute load average was recorded on every fault (15–58). - Before the mask, the same harness gave 2/6 and 0/6, every failure RC-06. With the mask, the waves found other restart failures, all since fixed on master: RC-14, RC-16, RC-20 and RC-21. ## Risks - Low risk. Test harness only, and the mask is opt-in. - A masked wave has no product hard stop. The harness still records spend for each wave, and the operator must watch it. The mask applies only to the isolated, temporary Chaos Lab company. It never touches another instance. - Masked results do not count as RC-06 coverage. The ledger labels them so they are not mixed with unmasked cells. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edit). Extended reasoning on. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
139 lines
6.7 KiB
TypeScript
139 lines
6.7 KiB
TypeScript
import { workloadDefinitions } from "./workloads.js";
|
||
import type { AdapterId, FaultKind, ScheduledFault, TaskPlan, TriggerId, WavePlan, WaveOptions, WorkloadId } from "./types.js";
|
||
import type { ReplayRef } from "./config.js";
|
||
|
||
/** mulberry32: small, fast and fully determined by its 32-bit seed. */
|
||
export function createRng(seed: number) {
|
||
let state = seed >>> 0;
|
||
const next = () => {
|
||
state = (state + 0x6d2b79f5) >>> 0;
|
||
let t = state;
|
||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||
};
|
||
return {
|
||
next,
|
||
int(min: number, max: number) { return min + Math.floor(next() * (max - min + 1)); },
|
||
hex(length: number) { let out = ""; while (out.length < length) out += Math.floor(next() * 16).toString(16); return out; },
|
||
shuffle<T>(values: readonly T[]): T[] {
|
||
const copy = [...values];
|
||
for (let index = copy.length - 1; index > 0; index -= 1) {
|
||
const swap = Math.floor(next() * (index + 1));
|
||
[copy[index], copy[swap]] = [copy[swap]!, copy[index]!];
|
||
}
|
||
return copy;
|
||
},
|
||
};
|
||
}
|
||
|
||
export const K4_HOLD_RANGE_MS: readonly [number, number] = [120_000, 300_000];
|
||
|
||
export const TRIGGER_DELAY_RANGE_MS: Record<Exclude<TriggerId, "time">, readonly [number, number]> = {
|
||
comment: [0, 5_000],
|
||
retry: [0, 2_000],
|
||
queued: [0, 0],
|
||
tool: [15_000, 60_000],
|
||
};
|
||
|
||
export function triggerFitsWorkload(trigger: TriggerId, workload: WorkloadId): boolean {
|
||
if (trigger === "comment") return workload === "C1";
|
||
if (trigger === "tool") return workload === "B5";
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* Pairwise-friendly sampling: cycle a seeded shuffle of the full
|
||
* workload × adapter × fault product so small waves still spread across cells.
|
||
*/
|
||
export function planTasks(options: Pick<WaveOptions, "seed" | "tasks" | "workloads" | "adapters" | "faults" | "triggers">): TaskPlan[] {
|
||
const rng = createRng(options.seed);
|
||
const triggers = options.triggers?.length ? options.triggers : ["time" as const];
|
||
for (const trigger of triggers) {
|
||
if (!options.workloads.some(workload => triggerFitsWorkload(trigger, workload))) {
|
||
throw new Error(`Trigger "${trigger}" needs workload ${trigger === "comment" ? "C1" : "B5"} in --workloads`);
|
||
}
|
||
}
|
||
const cells: Array<{ workload: WorkloadId; adapter: AdapterId; fault: FaultKind; trigger: TriggerId }> = [];
|
||
for (const workload of options.workloads) for (const adapter of options.adapters) for (const fault of options.faults) {
|
||
for (const trigger of triggers) if (triggerFitsWorkload(trigger, workload)) cells.push({ workload, adapter, fault, trigger });
|
||
}
|
||
const tasks: TaskPlan[] = [];
|
||
let order = rng.shuffle(cells);
|
||
for (let index = 0; index < options.tasks; index += 1) {
|
||
if (index > 0 && index % cells.length === 0) order = rng.shuffle(cells);
|
||
const cell = order[index % cells.length]!;
|
||
const definition = workloadDefinitions[cell.workload];
|
||
const [fireMin, fireMax] = definition.fireWindowMs;
|
||
const { trigger, ...cellRest } = cell;
|
||
tasks.push({
|
||
taskId: `t${String(index + 1).padStart(2, "0")}`,
|
||
index,
|
||
...cellRest,
|
||
...(trigger === "time" ? {} : { trigger, triggerDelayMs: rng.int(...TRIGGER_DELAY_RANGE_MS[trigger]) }),
|
||
fireAfterMs: rng.int(fireMin, fireMax),
|
||
holdMs: cell.fault === "K4" ? rng.int(K4_HOLD_RANGE_MS[0], K4_HOLD_RANGE_MS[1]) : 0,
|
||
followUpAfterMs: definition.followUpWindowMs ? rng.int(definition.followUpWindowMs[0], definition.followUpWindowMs[1]) : null,
|
||
nonce: rng.hex(8),
|
||
});
|
||
}
|
||
return tasks;
|
||
}
|
||
|
||
/** A replay keeps the source wave's masks and may add more; it never drops one. */
|
||
function replayMasks(source: readonly string[] | undefined, added: readonly string[] | undefined) {
|
||
const masks = [...new Set([...(source ?? []), ...(added ?? [])])];
|
||
return masks.length ? { masks } : {};
|
||
}
|
||
|
||
export function planWave(waveId: string, options: WaveOptions, createdAt = new Date()): WavePlan {
|
||
return { schema: "paperclip.restart-chaos.wave-plan/v1", waveId, seed: options.seed,
|
||
createdAt: createdAt.toISOString(), options, tasks: planTasks(options) };
|
||
}
|
||
|
||
/** Faults that actually crossed a task, as offsets from its launch. */
|
||
export function observedFaultSchedule(createdAt: number | null, faultIds: readonly string[],
|
||
faults: ReadonlyArray<{ faultId: string; kind: FaultKind; holdMs: number; startedAt: number; requestedBy?: string;
|
||
trigger?: TriggerId; triggerDelayMs?: number }>, taskId?: string): ScheduledFault[] {
|
||
if (createdAt === null) return [];
|
||
return faults.filter(fault => faultIds.includes(fault.faultId))
|
||
.map((fault): ScheduledFault => ({ kind: fault.kind, holdMs: fault.holdMs, atMs: Math.max(0, fault.startedAt - createdAt),
|
||
...(fault.trigger && fault.trigger !== "time" && fault.requestedBy === taskId
|
||
? { trigger: fault.trigger, delayMs: fault.triggerDelayMs ?? 0 } : {}) }))
|
||
.sort((a, b) => a.atMs - b.atMs);
|
||
}
|
||
|
||
/** The faults a task schedules: its replayed sequence, or its one planned fault. */
|
||
export function taskFaultSchedule(task: TaskPlan): ScheduledFault[] {
|
||
if (task.replayFaults?.length) return task.replayFaults;
|
||
const planned: ScheduledFault = { kind: task.fault, holdMs: task.holdMs, atMs: task.fireAfterMs };
|
||
const trigger = task.trigger ?? "time";
|
||
if (trigger === "time") return [planned];
|
||
const delayMs = task.triggerDelayMs ?? 0;
|
||
if (trigger === "retry") return [planned, { kind: "K1", holdMs: 0, atMs: 0, trigger, delayMs }];
|
||
return [{ ...planned, trigger, delayMs }];
|
||
}
|
||
|
||
/**
|
||
* A replay keeps the saved cell, hold and nonce and runs alone. When the source
|
||
* wave recorded which faults crossed the task (including other tasks' faults),
|
||
* the replay fires that same sequence at the same offsets from launch.
|
||
*/
|
||
export function replayWave(source: WavePlan, ref: ReplayRef, now = Date.now(),
|
||
overrides: Partial<Pick<WaveOptions, "pollMs" | "budgetCents" | "masks">> = {}, observed: ScheduledFault[] = []): WavePlan {
|
||
if (source.schema !== "paperclip.restart-chaos.wave-plan/v1") throw new Error("Unsupported wave plan schema");
|
||
if (source.waveId !== ref.waveId) throw new Error(`Plan is for ${source.waveId}, not ${ref.waveId}`);
|
||
const task = source.tasks.find(candidate => candidate.taskId === ref.taskId);
|
||
if (!task) throw new Error(`Wave ${ref.waveId} has no task ${ref.taskId}`);
|
||
const base = source.waveId.replace(/-replay-t[0-9]{2,3}-[0-9]+$/, "");
|
||
return {
|
||
schema: source.schema,
|
||
waveId: `${base}-replay-${task.taskId}-${now}`,
|
||
seed: source.seed,
|
||
createdAt: new Date(now).toISOString(),
|
||
options: { ...source.options, ...overrides, tasks: 1, concurrency: 1, ...replayMasks(source.options.masks, overrides.masks) },
|
||
tasks: [{ ...task, ...(observed.length ? { replayFaults: observed.map(fault => ({ ...fault })) } : {}) }],
|
||
replayOf: { ...ref },
|
||
};
|
||
}
|