mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 21:21:27 +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/`) proves that a release swap (two servers that overlap, then the old one stops) does not break running agent work > - The staging twin runs that swap with two local servers and real Daytona sandboxes, and it is the gate before any hosted proof > - A loaded twin wave (48 tasks, 20 runs plus 20 queued, 2 swaps) reported 31 per-task failures and 2 extra turns, but the product did the correct thing in almost all of them > - Three harness defects made the noise: the graders called a required follow-up run an extra turn, called a healthy queued run an orphan, and called a parent that waited for its subtasks a stall. Cleanup also left archived Daytona sandboxes in the shared org on every wave > - This pull request lands the twin harness work and fixes the three grader defects and the cleanup gap, each with a red/green harness test > - The benefit is a stop-rule grade that shows only real failures (here: 1 Retry banner) and makes the follow-up wait visible, and a wave that leaves no sandbox behind ## Linked Issues or Issue Description Refs #21175 and #21227 (the server's comment and child-result delivery rules; this harness takes their outcome from the server's wake record and does not re-check them). **What happened?** Wave `w-20261113T052703-s7301` (loaded twin L1, on Daytona) graded 31 tasks FAIL and listed 2 extra turns. The release-swap grade was 82 / 82 tasks completed without human action. - t007 and t010 (OpenCode): a person posted a follow-up comment during the first run (05:44:56 and 05:49:21). OpenCode takes no input mid-turn. The first run finished `done` at 05:53 and said "No board comments arrived". The deferred wake was promoted, and the second run answered the comment after 16 to 17 minutes in the 20-deep queue. The graders counted the second run as an extra turn and as a `completion_once` duplicate. - t021 to t048: each waited about 483 s queued for a slot in the deliberate 20-deep queue. U1 allows 5 minutes queued plus 3 minutes without an owner, so all 28 failed `no_owner_no_action`. - t001: a parent ended its turn `yielded` to wait for its two subtasks. The observer saw no run for 3 minutes, called it a stall, and rested it `in_progress`. The parent completed later through its `issue_children_completed` wake. R1, R3, R5 and U1 failed. - Cleanup: every Daytona wave left 1 to 8 archived `paperclip-create-*` setup sandboxes and reported `remainingSandboxes: []`. Daytona does not delete archived sandboxes. **Expected behavior** - A run that starts with a person's comment that no earlier run received is required. Only a run that starts with no undelivered input is an extra turn. - A run queued while every slot of its agent is taken is healthy for the declared queue time. A run queued while its agent has a free slot still fails. - A parent that waits for open subtasks is in a named wait, not a stall. - Cleanup deletes the sandboxes that this wave created and fails when one remains. **Steps to reproduce** 1. Run the L1 loaded twin (command in the README section "Staging twin cells"). 2. Read `staging-mix-summary.md` and `SUMMARY.md`. ## What Changed - Cherry-picked the 8 twin harness commits from `fastloop/staging-twin-loaded`: staging-mix under the release-swap driver on Daytona, `--server-from` on Daytona, probe agents verified while the first tasks run, image matched to the `--server-from` checkout, and the knobs `RESTART_CHAOS_K15_KILL_OLD_AFTER_SECONDS` / `_KILL_OLD_SWAPS`, `RESTART_CHAOS_K15_FREEZE_NEW_SECONDS` / `_FREEZE_SWAPS`, `RESTART_CHAOS_MIX_BANNER_REST_SECONDS` and `RESTART_CHAOS_MIX_FIRST_SLOT_SECONDS`. A misplaced doc block in `supervisor.ts` is moved back to its function. No code comments are added. - Cleanup (`daytona-sweep.ts`): after the environment delete, the harness deletes every sandbox that carries both of this wave's UUID labels (company and environment), archived ones included. `assertHarnessMayMutate` still refuses any sandbox without both labels and any `fleet-sbx-*` snapshot. The `paperclip-create-*` name refusal is removed, because every plugin sandbox (the fleet's included) has that name, so the labels are the real ownership proof. A sandbox left after deletion fails the wave (`undeletedSandboxes`, warm-shutdown verdict, `ttft-baseline`). - Follow-ups (`follow-up-delivery.ts`, `wake-evidence.ts`, `staging-mix-retry.ts`, `staging-mix.ts`): delivery comes from the server's own record. A comment that the server judged delivered never becomes a run. A run that the server started from a wake carrying a person's comment posted after the first run started (a retry included) is required, not an extra turn. `completion_once` keeps the first completion as the baseline and does not count a later completion by such a run (truth-table test). The grader does not re-check the server's delivery rule; the server's tests cover it. The summary adds `extra turns: N` and `follow-up answered in a later run: n, queued wait p50/max, posted to answered p50/max`. - Declared queue (`universal.ts`, `agent-slots.ts`, `wave-grade-inputs.ts`): with `--mix-queue` above 0, U1 allows ceil(queue / runs) × (longest turn + 5 min) queued (27 minutes for L1). Only queued time while the run's agent has a free slot counts against the 5-minute bound. Slot use comes from a new `wake-evidence/agent-slots.json` (run start/finish and each agent's `maxConcurrentRuns`). - Subtask wait (`child-wait.ts`, `observer.ts`, `grader.ts`): an idle parent after a `yielded` or `blocked` turn, until its `issue_children_completed` wake, is a named wait (`waitingOnChildren`) for R5 and U1. The observer no longer gives up on a parent while a subtask is open. An older record that rested during that wait takes the completion from the wake evidence. - Review follow-ups: the first staging-mix slot moves earlier without adding a swap; each sandbox delete pass has a deadline; a frozen incoming server is always resumed (`server-freeze.ts`); the first completion is always the baseline for `completion_once` (truth-table test); a follow-up run that failed before its turn keeps the answer owed for its retry; `agent-slots.json` saves the server's effective run cap (`maxConcurrentRunsSql`); the wave-end cleanup flow moved to `daytona-cleanup.ts` (`main.ts` stays under 1,000 lines). - README: one-command entries for the twin cell (G, G2, G3) and L1, the knobs, the stop-rule grading, the new summary lines, the U1 queue rule, the subtask wait and the cleanup rule. ## Verification - Red/green tests (red = new tests against the previous source): - Cleanup, `daytona-sweep.test.ts`: red 4 failed (for example "expected [] to deeply equal [ 'archived', 'archiving', 'started' ]": nothing was deleted). Green: pass. - Follow-ups, declared queue, subtask wait (`staging-mix-retry.test.ts`, `universal.test.ts`, `child-wait.test.ts`, `wake-evidence.test.ts`): red 6 failed (for example the t010 run listed as an extra turn, U1 fail for the t030 queue shape, t001 "rested_not_done"). Green: pass. The tests use the real timings of t001, t010 and t030. - Full harness suite: `npx vitest run --config tests/restart-chaos/vitest.config.ts`: 71 files, 811 tests pass. `npx tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean. - `pnpm verify` exits 2 (the harness README is a global CI input). Required CI supplies the broad coverage. - One-off offline analysis (a scratch script, not part of this PR): the saved wave `w-20261113T052703-s7301` regraded with these graders, from a copy of its results: | | Before | After | | --- | --- | --- | | Per-task FAIL | 31 (t001 R1, t007 and t010 `completion_once`, t021 to t048 U1) | 0 | | Extra turns | 2 (t007, t010) | 0 | | Retry banner shown | 1 (t020, 3 s, completed without a click) | 1 (t020) | | Follow-up answered in a later run | not shown | 4: t001, t007, t010, t012. Queued wait p50 983 s, max 1739 s. Posted to answered p50 1420 s, max 2255 s | t001 and t012 started their follow-up run before completion, so they were never extra turns. They are listed because the wait is real. This wave predates `agent-slots.json`, so the regrade used only the declared queue bound for U1. - No Daytona wave ran for this PR. There is no live proof here that the cleanup deletes archived sandboxes in the real org or that the new evidence file is written on a live wave. The delete path uses the same `DELETE /sandbox/<id>` call as the Daytona SDK's `deleteSandbox`. ## Risks - The harness now deletes Daytona sandboxes in an org that the Cloud fleet shares. The guard is the wave's two freshly minted UUID labels, filtered on the server and checked again on every row, plus the `fleet-sbx-*` refusal. A sandbox without both labels is never deleted. - When the server wrongly re-delivers a comment that a finished run already received, the harness counts that run as a required follow-up, not as an extra turn. The server's own delivery tests catch that class, not this grader. `completion_once` still fails when that run also reports completion and is not the first. - The declared queue bound is generous (27 minutes for L1). A stuck queue with full slots for longer than that still fails. A queue with a free slot fails after 5 minutes when slot evidence exists. Without slot evidence only the declared bound applies. - Test harness only. No product code changes. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## 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>
635 lines
39 KiB
TypeScript
635 lines
39 KiB
TypeScript
/**
|
||
* Phase 0 speed baseline driver (doc/plans/2026-11-07-ttft-baseline.md).
|
||
*
|
||
* Starts one isolated control plane through the restart chaos supervisor,
|
||
* seeds the Chaos Lab, and per adapter runs:
|
||
* - cold: a new task (fresh provider session);
|
||
* - warm: a follow-up comment on the same task (provider session reuse);
|
||
* - restart: a task in a provider tool call when the control plane is killed
|
||
* (K1, SIGKILL) or stopped gracefully (K2, SIGTERM).
|
||
* It then writes every run's run log to `<out>/baseline-data.json`. All timing
|
||
* comes from the run log, never from Telemetry (rules/data-paths.mdc).
|
||
*
|
||
* set -a; source ~/.secrets; set +a
|
||
* node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/ttft-baseline.ts \
|
||
* --adapters codex,claude,opencode --samples 5 --restarts 2
|
||
* node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/ttft-baseline.ts --report <out>/baseline-data.json
|
||
*/
|
||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||
import path from "node:path";
|
||
import { parseArgs } from "node:util";
|
||
import { setTimeout as delay } from "node:timers/promises";
|
||
import { releaseInstance } from "../runner-e2e/instance-retention.js";
|
||
import { ChaosApi } from "./api.js";
|
||
import { CREDENTIAL_FOR_ADAPTER, DAYTONA_VCPU_BUDGET } from "./config.js";
|
||
import { ACTIVE_RUN_STATUSES } from "./grader.js";
|
||
import { chaosLifecycleOverrides, seedChaosLab, type ChaosLab } from "./seed.js";
|
||
import { ChaosSupervisor } from "./supervisor.js";
|
||
import { createDb } from "../../packages/db/src/index.js";
|
||
import { prepareDaytonaController } from "./daytona-controller.js";
|
||
import { DaytonaWaveSweeper } from "./daytona-sweep.js";
|
||
import { Timeline } from "./timeline.js";
|
||
import type { AdapterId, FaultKind } from "./types.js";
|
||
import {
|
||
baselineRows, rankPreTurnSteps, recoverySamples, distribution, openShellExecutions, daytonaBaselineHolders, daytonaRetainsSandboxes, parseBaselineEnvironment, parseBaselinePhases,
|
||
type BaselineEvent, type BaselineFault, type BaselineRun,
|
||
} from "./ttft-baseline-stats.js";
|
||
|
||
type Json = Record<string, unknown>;
|
||
const repositoryRoot = path.resolve(import.meta.dirname, "../..");
|
||
const TASK_TIMEOUT_MS = 8 * 60_000;
|
||
|
||
const coldTask = (nonce: string) => [
|
||
`Baseline ${nonce}. Reply on this task with a one-line comment that says \`READY ${nonce}\`.`,
|
||
"Do not create files, documents or other tasks. Then mark this task done.",
|
||
].join("\n");
|
||
const warmFollowUp = (nonce: string) =>
|
||
`Follow-up ${nonce}: reply with one more one-line comment that says \`AGAIN ${nonce}\`, then mark the task done again.`;
|
||
/** The long call a restart sample must interrupt. */
|
||
const RESTART_SLEEP_MARKER = "time.sleep(75)";
|
||
const restartTask = (nonce: string) => [
|
||
// Claude Code's Bash tool refuses a bare long \`sleep\`; a Python sleep is one ordinary shell call everywhere.
|
||
`Baseline restart ${nonce}. First run the shell command \`python3 -c "import time; time.sleep(75)"\` and wait for it to finish.`,
|
||
`Then reply with a one-line comment that says \`DONE ${nonce}\` and mark this task done.`,
|
||
"Do not create files, documents or other tasks.",
|
||
].join("\n");
|
||
|
||
const MIDTURN_SLEEP_SECONDS = 40;
|
||
const midturnTask = (nonce: string) => [
|
||
`Baseline mid-turn ${nonce}. First run the shell command \`python3 -c "import time; time.sleep(${MIDTURN_SLEEP_SECONDS})"\` and wait for it to finish.`,
|
||
`Then reply with a one-line comment that says \`DONE ${nonce}\` and mark this task done.`,
|
||
"Do not create files, documents or other tasks.",
|
||
].join("\n");
|
||
const midturnFollowUp = (nonce: string) =>
|
||
`Mid-turn follow-up ${nonce}: also reply with a one-line comment that says \`HELLO ${nonce}\`.`;
|
||
|
||
/** The agent's replies naming `marker`, oldest first. A failed read throws: it is not a lost reply. */
|
||
async function agentReplies(api: ChaosApi, issueId: string, marker: string): Promise<Json[]> {
|
||
const comments = await api.get<Json[]>(`/api/issues/${issueId}/comments`, 10_000);
|
||
return comments.filter(comment => Boolean(comment.authorAgentId) && String(comment.body ?? "").includes(marker))
|
||
.sort((a, b) => Date.parse(String(a.createdAt)) - Date.parse(String(b.createdAt)));
|
||
}
|
||
|
||
/**
|
||
* Steer a queued comment into the live turn once the runner reports steering
|
||
* available. Returns the acknowledgement time, or the disposition that blocked it.
|
||
*/
|
||
async function steerQueuedComment(api: ChaosApi, issueId: string, commentId: string): Promise<{ acknowledgedAt: string | null; disposition: string }> {
|
||
const deadline = Date.now() + 60_000;
|
||
let disposition = "none";
|
||
while (Date.now() < deadline) {
|
||
const queue = await api.get<Json>(`/api/issues/${issueId}/queued-comments`, 10_000).catch(() => null);
|
||
disposition = String(queue?.steeringDisposition ?? "none");
|
||
if (queue && disposition === "available" && queue.queueId && queue.targetRunId) {
|
||
await api.post(`/api/issues/${issueId}/queued-comments/${commentId}/steer`,
|
||
{ queueId: queue.queueId, revision: queue.revision, targetRunId: queue.targetRunId });
|
||
return { acknowledgedAt: new Date().toISOString(), disposition };
|
||
}
|
||
if (disposition === "unsupported") break;
|
||
await delay(500);
|
||
}
|
||
return { acknowledgedAt: null, disposition };
|
||
}
|
||
|
||
/** Set by --workspace-repo: tasks then run in the project's isolated workspace of that repository. */
|
||
let projectScopedTasks = false;
|
||
|
||
async function createTask(api: ChaosApi, lab: ChaosLab, adapter: AdapterId, title: string, description: string) {
|
||
const issue = await api.post<Json>(`/api/companies/${lab.companyId}/issues`, {
|
||
title, description, status: "todo", priority: "medium", assigneeAgentId: lab.agents[adapter].id,
|
||
...(projectScopedTasks ? { projectId: lab.projectId } : {}),
|
||
});
|
||
return String(issue.id);
|
||
}
|
||
|
||
/** `/api/issues/:id/runs` rows carry `runId`, not `id`. */
|
||
const runIdOf = (run: Json) => String(run.runId ?? run.id);
|
||
|
||
async function runsFor(api: ChaosApi, issueId: string): Promise<Json[]> {
|
||
return await api.get<Json[]>(`/api/issues/${issueId}/runs`, 10_000).catch(() => []);
|
||
}
|
||
|
||
/**
|
||
* Wait until the task has at least `minRuns` runs and none is active. Returns
|
||
* `timedOut: true` at the deadline, so the caller never treats an active run
|
||
* as a finished sample.
|
||
*/
|
||
async function waitForRest(api: ChaosApi, supervisor: ChaosSupervisor, issueId: string, minRuns: number): Promise<{ runs: Json[]; timedOut: boolean }> {
|
||
const deadline = Date.now() + TASK_TIMEOUT_MS;
|
||
let restSince: number | null = null;
|
||
while (Date.now() < deadline) {
|
||
if (supervisor.serverReady) {
|
||
const runs = await runsFor(api, issueId);
|
||
const resting = runs.length >= minRuns && runs.every(run => !ACTIVE_RUN_STATUSES.has(String(run.status)));
|
||
restSince = resting ? (restSince ?? Date.now()) : null;
|
||
// A finished run can queue a continuation; confirm the rest for a few seconds.
|
||
if (restSince !== null && Date.now() - restSince >= 6_000) return { runs, timedOut: false };
|
||
}
|
||
await delay(2_000);
|
||
}
|
||
return { runs: await runsFor(api, issueId), timedOut: true };
|
||
}
|
||
|
||
async function allEvents(api: ChaosApi, runId: string): Promise<BaselineEvent[]> {
|
||
const events: BaselineEvent[] = [];
|
||
let afterSeq = 0;
|
||
for (;;) {
|
||
const page = await api.get<Json[]>(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=500`, 15_000);
|
||
for (const row of page) {
|
||
events.push({ eventType: String(row.eventType), createdAt: String(row.createdAt),
|
||
payload: (row.payload ?? null) as Json | null });
|
||
}
|
||
if (page.length < 500) return events;
|
||
afterSeq = Number(page[page.length - 1]!.seq);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The running run of the task, when it is inside the long sleep call. A tool
|
||
* that exposes its command must show the sleep marker. A tool that exposes no
|
||
* command text (OpenCode's `bash`) counts as inside an open shell call, and the
|
||
* sample is marked `commandUnverified`.
|
||
*/
|
||
async function runInShellCall(api: ChaosApi, issueId: string, marker = RESTART_SLEEP_MARKER): Promise<{ runId: string; commandUnverified: boolean } | null> {
|
||
const active = (await runsFor(api, issueId)).find(run => String(run.status) === "running");
|
||
if (!active) return null;
|
||
const events = await allEvents(api, runIdOf(active)).catch(() => []);
|
||
const open = openShellExecutions(events, marker);
|
||
if (open.some(call => call.matched)) return { runId: runIdOf(active), commandUnverified: false };
|
||
if (open.length && open.every(call => call.unlabelled)) return { runId: runIdOf(active), commandUnverified: true };
|
||
return null;
|
||
}
|
||
|
||
/** Wait until the run is inside its shell tool call (started, not ended). */
|
||
async function waitForShellCall(api: ChaosApi, issueId: string, marker = RESTART_SLEEP_MARKER): Promise<{ runId: string; commandUnverified: boolean } | null> {
|
||
const deadline = Date.now() + 4 * 60_000;
|
||
while (Date.now() < deadline) {
|
||
const inside = await runInShellCall(api, issueId, marker);
|
||
if (inside) return inside;
|
||
await delay(1_500);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Wait for each agent to pass lifecycle verification. An agent that never
|
||
* reaches `ready` is reported as not measured, never waited on per task.
|
||
*/
|
||
async function readyAdapters(api: ChaosApi, lab: ChaosLab, adapters: AdapterId[], timeline: Timeline): Promise<AdapterId[]> {
|
||
const deadline = Date.now() + 4 * 60_000;
|
||
const pending = new Set(adapters);
|
||
const ready: AdapterId[] = [];
|
||
while (pending.size && Date.now() < deadline) {
|
||
for (const adapter of [...pending]) {
|
||
const agent = await api.get<Json>(`/api/agents/${lab.agents[adapter].id}`).catch(() => null);
|
||
const state = String(agent?.lifecycleState ?? "unknown");
|
||
if (state === "ready") { ready.push(adapter); pending.delete(adapter); }
|
||
else if (agent?.status === "paused" && agent?.lifecycleError) {
|
||
timeline.add("baseline_adapter_not_ready", { adapter, state, error: String(agent.lifecycleError).slice(0, 300) });
|
||
pending.delete(adapter);
|
||
}
|
||
}
|
||
if (pending.size) await delay(3_000);
|
||
}
|
||
for (const adapter of pending) timeline.add("baseline_adapter_not_ready", { adapter, state: "timeout" });
|
||
return ready;
|
||
}
|
||
|
||
function report(runs: BaselineRun[], faults: BaselineFault[]): string {
|
||
const ms = (value: number | null) => value === null ? "—" : `${(value / 1000).toFixed(2)} s`;
|
||
const lines = ["| Adapter | Env | Start | n | TTFT p50 | TTFT p95 | Wait behind live turn p50 / p95 (n) | First activity from run created p50 / p95 (budget) | TTFT from run created p50 / p95 | Boot p50 | Boot p95 | TTFT anchors |", "|---|---|---|---|---|---|---|---|---|---|---|---|"];
|
||
const rowLine = (row: ReturnType<typeof baselineRows>[number]) => `| ${row.adapter} | ${row.environment} | ${row.warmth} | ${row.ttft.n}/${row.boot.n} | ${ms(row.ttft.p50)} | ${ms(row.ttft.p95)} | ${ms(row.inputWait.p50)} / ${ms(row.inputWait.p95)} (${row.inputWait.n}) | ${ms(row.firstActivityAfterRunCreated.p50)} / ${ms(row.firstActivityAfterRunCreated.p95)} | ${ms(row.ttftAfterRunCreated.p50)} / ${ms(row.ttftAfterRunCreated.p95)} | ${ms(row.boot.p50)} | ${ms(row.boot.p95)} | ${Object.entries(row.anchors).map(([k, v]) => `${k}×${v}`).join(", ") || "—"} |`;
|
||
for (const row of baselineRows(runs)) lines.push(rowLine(row));
|
||
// New agents wait for harness verification before their run is created:
|
||
// their own rows, so that wait never blends into ordinary cold starts.
|
||
const verifyRuns = runs.filter(run => run.phase === "verify").map(run => ({ ...run, phase: "cold" as const }));
|
||
if (verifyRuns.length) {
|
||
lines.push("", "New agent behind harness verification (TTFT counts from run creation; the verification wait precedes it):", "", lines[0]!, lines[1]!);
|
||
for (const row of baselineRows(verifyRuns)) lines.push(rowLine(row));
|
||
}
|
||
const postfault = runs.filter(run => run.phase === "postfault").map(run => ({ ...run, phase: "cold" as const }));
|
||
if (postfault.length) {
|
||
lines.push("", "First follow-up after an idle control-plane restart (K1):", "", lines[0]!, lines[1]!);
|
||
for (const row of baselineRows(postfault)) lines.push(rowLine(row));
|
||
}
|
||
|
||
lines.push("", "| Pre-turn step | n | p50 | p95 | Adapters |", "|---|---|---|---|---|");
|
||
for (const step of rankPreTurnSteps(runs).slice(0, 25)) lines.push(`| \`${step.step}\` | ${step.n} | ${ms(step.p50)} | ${ms(step.p95)} | ${step.adapters.join(", ")} |`);
|
||
const samples = recoverySamples(runs, faults);
|
||
lines.push("", "| Adapter | Fault | Disposition | n | Recovery p50 | Recovery p95 | Paperclip share p50 / p95 | No provider event |", "|---|---|---|---|---|---|---|---|");
|
||
const groups = new Map<string, typeof samples>();
|
||
for (const sample of samples) {
|
||
const key = `${sample.adapter}|${sample.kind}|${sample.disposition}`;
|
||
groups.set(key, [...(groups.get(key) ?? []), sample]);
|
||
}
|
||
for (const [key, group] of [...groups.entries()].sort()) {
|
||
const [adapter, kind, disposition] = key.split("|");
|
||
const d = distribution(group.flatMap(sample => sample.latencyMs === null ? [] : [sample.latencyMs]));
|
||
const control = distribution(group.flatMap(sample => sample.controlPlaneMs === null ? [] : [sample.controlPlaneMs]));
|
||
lines.push(`| ${adapter} | ${kind} | ${disposition} | ${d.n} | ${ms(d.p50)} | ${ms(d.p95)} | ${ms(control.p50)} / ${ms(control.p95)} | ${group.length - d.n} |`);
|
||
}
|
||
return `${lines.join("\n")}\n`;
|
||
}
|
||
|
||
async function main() {
|
||
const { values } = parseArgs({ options: {
|
||
adapters: { type: "string", default: "codex,claude,opencode" },
|
||
samples: { type: "string", default: "5" },
|
||
restarts: { type: "string", default: "2" },
|
||
phases: { type: "string", default: "coldwarm,restart" },
|
||
out: { type: "string" },
|
||
report: { type: "string" },
|
||
// Runner lifecycle for every seeded agent: per_turn, warm, or default (no stored
|
||
// lifecycle, so the server resolves the product default). Absent keeps the
|
||
// catalog profile's setting.
|
||
lifecycle: { type: "string" },
|
||
// Mid-turn follow-up delivery: queue (default, wait for the turn) or steer (into the live turn).
|
||
"midturn-mode": { type: "string", default: "queue" },
|
||
// Fault the control plane right after a steered comment is acknowledged (K1, K2 or K6).
|
||
"midturn-fault": { type: "string" },
|
||
// verify phase: fault the control plane while a newly hired agent runs harness verification.
|
||
"verify-fault": { type: "string" },
|
||
// A real repository (for example a fresh clone of paperclip) as the project's
|
||
// primary workspace; every task then runs in its isolated git worktree.
|
||
"workspace-repo": { type: "string" },
|
||
// local (default) or daytona; daytona needs --daytona-image (the signed Runner image).
|
||
env: { type: "string", default: "local" },
|
||
"daytona-image": { type: "string" },
|
||
"daytona-cpu": { type: "string", default: "4" },
|
||
// Use the reusable warm Daytona environment (reuseLease, warm runner) instead of the per-turn one.
|
||
"daytona-warm": { type: "boolean", default: false },
|
||
// A Daytona environment as a user creates it by default: lifecycle inherited, lease reuse unset.
|
||
"daytona-inherit": { type: "boolean", default: false },
|
||
"idle-ms": { type: "string", default: "600000" },
|
||
} });
|
||
if (values.report) {
|
||
const data = JSON.parse(await readFile(values.report, "utf8")) as { runs: BaselineRun[]; faults: BaselineFault[] };
|
||
process.stdout.write(report(data.runs, data.faults));
|
||
return;
|
||
}
|
||
const phases = parseBaselinePhases(values.phases!);
|
||
const requested = values.adapters!.split(",").map(value => value.trim()) as AdapterId[];
|
||
const samples = Math.max(1, Number(values.samples));
|
||
const restarts = Math.max(0, Number(values.restarts));
|
||
const lifecycle = values.lifecycle;
|
||
if (lifecycle !== undefined && lifecycle !== "per_turn" && lifecycle !== "warm" && lifecycle !== "default") {
|
||
throw new Error("--lifecycle must be per_turn, warm or default");
|
||
}
|
||
const { env, cpu } = parseBaselineEnvironment({ env: values.env, image: values["daytona-image"], cpu: values["daytona-cpu"],
|
||
warm: values["daytona-warm"] === true, inherit: values["daytona-inherit"] === true });
|
||
if (env === "daytona") {
|
||
const budget = Number(process.env.RESTART_CHAOS_DAYTONA_VCPU_BUDGET ?? DAYTONA_VCPU_BUDGET);
|
||
const retainsSandboxes = daytonaRetainsSandboxes({ warmEnvironment: values["daytona-warm"] === true,
|
||
inheritEnvironment: values["daytona-inherit"] === true, lifecycle });
|
||
const holders = daytonaBaselineHolders({ adapters: requested.length, samples, phases, restarts, retainsSandboxes });
|
||
if (holders * cpu > budget) {
|
||
throw new Error(`${holders} ${retainsSandboxes ? "sampled tasks (warm sandboxes outlive their task)" : "concurrent tasks"} × --daytona-cpu ${cpu} vCPU can be held at once, `
|
||
+ `exceeding the Daytona vCPU budget of ${budget}. Lower --samples, --adapters or --daytona-cpu (RESTART_CHAOS_DAYTONA_VCPU_BUDGET sets the budget).`);
|
||
}
|
||
}
|
||
const missing = [...requested.map(adapter => CREDENTIAL_FOR_ADAPTER[adapter]), ...(env === "daytona" ? ["DAYTONA_API_KEY"] : [])]
|
||
.filter(key => !process.env[key]);
|
||
if (missing.length) throw new Error(`Missing ${missing.join(", ")}; run: set -a; source ~/.secrets; set +a`);
|
||
const midturnMode = values["midturn-mode"];
|
||
if (midturnMode !== "queue" && midturnMode !== "steer") throw new Error("--midturn-mode must be queue or steer");
|
||
const midturnFault = values["midturn-fault"] as FaultKind | undefined;
|
||
if (midturnFault !== undefined && !["K1", "K2", "K6"].includes(midturnFault)) throw new Error("--midturn-fault must be K1, K2 or K6");
|
||
if (midturnFault && midturnMode !== "steer") throw new Error("--midturn-fault applies to --midturn-mode steer");
|
||
const verifyFault = values["verify-fault"] as FaultKind | undefined;
|
||
if (verifyFault !== undefined && !["K1", "K2", "K6"].includes(verifyFault)) throw new Error("--verify-fault must be K1, K2 or K6");
|
||
// default removes the catalog's pinned per_turn so the server resolves the
|
||
// product default; absent keeps the catalog setting.
|
||
const adapterConfigOverrides = lifecycle === "warm"
|
||
? { lifecycleMode: "warm", idleTimeoutMs: Math.max(1, Number(values["idle-ms"])) }
|
||
: chaosLifecycleOverrides(lifecycle);
|
||
const waveId = `ttft-${new Date().toISOString().replace(/[-:.]/g, "").slice(0, 15)}`;
|
||
const outDir = path.resolve(values.out ?? path.join(import.meta.dirname, "results", waveId));
|
||
await mkdir(outDir, { recursive: true, mode: 0o700 });
|
||
const timeline = new Timeline(path.join(outDir, "timeline.jsonl"));
|
||
const supervisor = await ChaosSupervisor.create({ repositoryRoot, waveDir: outDir, timeline });
|
||
const tasks: Array<{ issueId: string; adapter: AdapterId; phase: BaselineRun["phase"] }> = [];
|
||
const faults: BaselineFault[] = [];
|
||
const runPhase = new Map<string, BaselineRun["phase"]>();
|
||
const agentLifecycles: Record<string, string> = {};
|
||
const midturn: Json[] = [];
|
||
const timedOutIssues = new Set<string>();
|
||
let sweeper: DaytonaWaveSweeper | null = null;
|
||
const workspaceOperations: Array<{ runId: string; adapter: string; phase: string; operation: string; status: string;
|
||
durationMs: number | null; command: string | null }> = [];
|
||
// Every coldwarm sample that finished at rest gets its own post-restart follow-up.
|
||
const followUpTasks: Array<{ adapter: AdapterId; issueId: string; nonce: string; runs: number }> = [];
|
||
// One shutdown path for normal completion and for SIGINT/SIGTERM: the server
|
||
// runs in a detached process group and the embedded Postgres has no exit hook.
|
||
let stopping: Promise<void> | null = null;
|
||
// Daytona resources are released while the server still runs, before it stops;
|
||
// the same path serves normal completion and SIGINT/SIGTERM.
|
||
const releaseDaytona = async () => {
|
||
if (!sweeper) return;
|
||
const owned = sweeper as DaytonaWaveSweeper;
|
||
sweeper = null;
|
||
try {
|
||
const cleanup = await owned.cleanUp();
|
||
timeline.add("daytona_cleanup", cleanup);
|
||
await writeFile(path.join(outDir, "sandbox-cleanup.json"), `${JSON.stringify(cleanup, null, 2)}\n`, { mode: 0o600 });
|
||
if (cleanup.remainingSandboxes.length || cleanup.undeletedSandboxes.length || cleanup.errors.length || cleanup.environmentDeleteBlocked || !cleanup.environmentDeleted) {
|
||
process.stderr.write(`Daytona cleanup incomplete: remaining ${cleanup.remainingSandboxes.join(", ") || "none"}; left after deletion ${cleanup.undeletedSandboxes.join(", ") || "none"}; `
|
||
+ `environment deleted ${cleanup.environmentDeleted}${cleanup.environmentDeleteBlocked ? ` (blocked: ${String(cleanup.environmentDeleteBlocked)})` : ""}; ${cleanup.errors.join("; ")}\n`);
|
||
process.exitCode = 1;
|
||
}
|
||
} catch (error) {
|
||
timeline.add("daytona_cleanup_failed", { error: String(error) });
|
||
process.exitCode = 1;
|
||
}
|
||
};
|
||
const shutdown = () => (stopping ??= releaseDaytona().then(() => supervisor.stop()).then(() => false, error => {
|
||
process.stderr.write(`supervisor stop: ${String(error)}\n`);
|
||
return true;
|
||
}).then(stopFailed => releaseInstance(supervisor.paths.temporaryRoot, { keep: false, stopFailed, owner: "ttft-baseline" }))
|
||
.then(() => undefined, error => { process.stderr.write(`instance cleanup: ${String(error)}\n`); }));
|
||
const onSignal = (signal: NodeJS.Signals) => {
|
||
timeline.add("baseline_interrupted", { signal });
|
||
void shutdown().finally(() => process.exit(signal === "SIGINT" ? 130 : 143));
|
||
};
|
||
process.once("SIGINT", onSignal);
|
||
process.once("SIGTERM", onSignal);
|
||
try {
|
||
await supervisor.start(env === "daytona"
|
||
? await prepareDaytonaController({ image: values["daytona-image"]!, repositoryRoot, timeline }) : {});
|
||
const api = new ChaosApi(supervisor.baseUrl);
|
||
const workspaceRepo = values["workspace-repo"] ? path.resolve(values["workspace-repo"]) : undefined;
|
||
projectScopedTasks = Boolean(workspaceRepo);
|
||
const lab = await seedChaosLab({ api, env, daytonaImage: values["daytona-image"], daytonaCpu: cpu,
|
||
daytonaWarm: values["daytona-warm"], daytonaInherit: values["daytona-inherit"],
|
||
adapters: requested, concurrency: requested.length, budgetCents: 3000,
|
||
masks: ["rc06"], fixtureRoot: supervisor.paths.temporaryRoot, waveId, timeline, adapterConfigOverrides, workspaceRepo,
|
||
onEnvironment: owned => {
|
||
sweeper = new DaytonaWaveSweeper({ apiKey: process.env.DAYTONA_API_KEY!, companyId: owned.companyId, environmentId: owned.environmentId, api });
|
||
} });
|
||
const adapters = await readyAdapters(api, lab, requested, timeline);
|
||
if (!adapters.length) throw new Error("No agent passed lifecycle verification");
|
||
// Record what each agent actually stores: "unset" means the server resolves
|
||
// the product default, so a label alone cannot misdescribe the wave.
|
||
for (const adapter of adapters) {
|
||
const agent = await api.get<Json>(`/api/agents/${lab.agents[adapter].id}`, 10_000);
|
||
const stored = (agent.adapterConfig as Json | undefined)?.lifecycleMode;
|
||
agentLifecycles[adapter] = typeof stored === "string" ? stored : "unset";
|
||
}
|
||
timeline.add("baseline_agent_lifecycles", agentLifecycles);
|
||
|
||
// Cold then warm, one task per adapter at a time, adapters in parallel.
|
||
if (phases.has("coldwarm")) await Promise.all(adapters.map(async adapter => {
|
||
for (let index = 0; index < samples; index += 1) {
|
||
const nonce = `${adapter}-${index}-${Date.now().toString(36)}`;
|
||
const issueId = await createTask(api, lab, adapter, `TTFT baseline ${nonce}`, coldTask(nonce));
|
||
tasks.push({ issueId, adapter, phase: "cold" });
|
||
const cold = await waitForRest(api, supervisor, issueId, 1);
|
||
for (const run of cold.runs) runPhase.set(runIdOf(run), "cold");
|
||
if (cold.timedOut) {
|
||
// Never send the follow-up into an active turn; drop the whole sample.
|
||
timedOutIssues.add(issueId);
|
||
timeline.add("baseline_sample_timeout", { adapter, issueId, phase: "cold" });
|
||
continue;
|
||
}
|
||
timeline.add("baseline_cold_done", { adapter, issueId, runs: cold.runs.length });
|
||
await api.post(`/api/issues/${issueId}/comments`, { body: warmFollowUp(nonce), reopen: true });
|
||
const warm = await waitForRest(api, supervisor, issueId, cold.runs.length + 1);
|
||
for (const run of warm.runs) if (!runPhase.has(runIdOf(run))) runPhase.set(runIdOf(run), "warm");
|
||
if (warm.timedOut) {
|
||
timedOutIssues.add(issueId);
|
||
timeline.add("baseline_sample_timeout", { adapter, issueId, phase: "warm" });
|
||
continue;
|
||
}
|
||
timeline.add("baseline_warm_done", { adapter, issueId, runs: warm.runs.length - cold.runs.length });
|
||
followUpTasks.push({ adapter, issueId, nonce, runs: warm.runs.length });
|
||
}
|
||
}));
|
||
|
||
// New agent: hire an agent identical to the seeded one and assign it a task
|
||
// at once, so the task waits for harness verification. Optionally restart
|
||
// the control plane while it verifies. TTFT is comment-to-first-token.
|
||
if (phases.has("verify")) for (const adapter of adapters) {
|
||
const source = lab.agents[adapter];
|
||
if (!source.body) continue;
|
||
for (let index = 0; index < samples; index += 1) {
|
||
const nonce = `${adapter}-v${index}-${Date.now().toString(36)}`;
|
||
const hired = await api.post<Json>(`/api/companies/${lab.companyId}/agents`, { ...source.body, name: `${source.name} verify ${nonce}` });
|
||
const agentId = String(hired.id);
|
||
const issue = await api.post<Json>(`/api/companies/${lab.companyId}/issues`, {
|
||
title: `TTFT verify ${nonce}`, description: coldTask(nonce), status: "todo", priority: "medium", assigneeAgentId: agentId,
|
||
...(projectScopedTasks ? { projectId: lab.projectId } : {}) });
|
||
const issueId = String(issue.id);
|
||
tasks.push({ issueId, adapter, phase: "verify" });
|
||
let fault: Awaited<ReturnType<typeof supervisor.fault>> | null = null;
|
||
if (verifyFault) {
|
||
const deadline = Date.now() + 60_000;
|
||
let state = "unknown";
|
||
while (Date.now() < deadline && (state = String((await api.get<Json>(`/api/agents/${agentId}`).catch(() => null))?.lifecycleState)) !== "verifying"
|
||
&& state !== "ready") await delay(200);
|
||
// Fault only while a verifier holds the lifecycle lease, read from the
|
||
// instance database; otherwise the sample is skipped, not faulted.
|
||
const config = JSON.parse(await readFile(supervisor.paths.configPath, "utf8")) as { database?: { connectionString?: string } };
|
||
const db = createDb(config.database!.connectionString!);
|
||
let held = false;
|
||
try {
|
||
while (state === "verifying" && Date.now() < deadline && !held) {
|
||
const rows = await db.$client`select 1 from agents where id = ${agentId}
|
||
and lifecycle_state = 'verifying' and lifecycle_operation ? 'leaseOwner'`;
|
||
held = rows.length > 0;
|
||
if (!held) await delay(100);
|
||
}
|
||
} finally { await db.$client.end({ timeout: 5 }).catch(() => undefined); }
|
||
timeline.add("baseline_verify_fault_point", { adapter, agentId, state, leaseHeld: held });
|
||
if (!held) timeline.add("baseline_verify_sample_skipped", { adapter, agentId, reason: "no_held_verification_lease" });
|
||
if (held) {
|
||
fault = await supervisor.fault(verifyFault, 0, `verify-${index}`);
|
||
}
|
||
}
|
||
const settled = await waitForRest(api, supervisor, issueId, 1);
|
||
if (settled.timedOut) {
|
||
timedOutIssues.add(issueId);
|
||
timeline.add("baseline_sample_timeout", { adapter, issueId, phase: "verify" });
|
||
continue;
|
||
}
|
||
// The task's run is created only after verification, so name it once it
|
||
// exists: the recovery table then measures fault ready to first event.
|
||
if (fault) faults.push({ kind: verifyFault!, readyAt: fault.readyAt ?? Date.now(), runIds: settled.runs.map(runIdOf) });
|
||
timeline.add("baseline_verify_done", { adapter, agentId, issueId, faulted: Boolean(fault), runs: settled.runs.length });
|
||
}
|
||
}
|
||
|
||
// First turn after an idle control-plane restart: K1 while nothing runs,
|
||
// then one more follow-up on each task the cold/warm phase left at rest.
|
||
// The fault must be idle: no timed-out sample may still be running.
|
||
// A failed runs read counts as not at rest: the fault must never land on a live turn.
|
||
const allAtRest = timedOutIssues.size === 0 && (await Promise.all(tasks.map(async task =>
|
||
(await api.get<Json[]>(`/api/issues/${task.issueId}/runs`, 10_000).catch(() => null))
|
||
?.every(run => !ACTIVE_RUN_STATUSES.has(String(run.status))) ?? false))).every(Boolean);
|
||
if (phases.has("postfault") && followUpTasks.length && !allAtRest) {
|
||
timeline.add("baseline_postfault_skipped", { reason: "work_not_at_rest", timedOut: timedOutIssues.size });
|
||
}
|
||
if (phases.has("postfault") && followUpTasks.length && allAtRest) {
|
||
// One idle K1 per round, then the first follow-up on one task per adapter, so each
|
||
// sample is a genuine first turn after a restart. A timed-out follow-up may still be
|
||
// running, so it ends the rounds: the next fault must stay idle.
|
||
const rounds = Math.max(...adapters.map(adapter => followUpTasks.filter(entry => entry.adapter === adapter).length));
|
||
for (let round = 0; round < rounds; round += 1) {
|
||
const batch = adapters.flatMap(adapter => followUpTasks.filter(entry => entry.adapter === adapter).slice(round, round + 1));
|
||
const receipt = await supervisor.fault("K1", 0, `ttft-baseline-postfault-${round}`);
|
||
faults.push({ kind: "K1", readyAt: receipt.readyAt ?? Date.now(), runIds: [] });
|
||
let timedOut = false;
|
||
await Promise.all(batch.map(async entry => {
|
||
const { adapter } = entry;
|
||
await api.post(`/api/issues/${entry.issueId}/comments`, { body: warmFollowUp(`${entry.nonce}-postfault`), reopen: true });
|
||
const after = await waitForRest(api, supervisor, entry.issueId, entry.runs + 1);
|
||
for (const run of after.runs) if (!runPhase.has(runIdOf(run))) runPhase.set(runIdOf(run), "postfault");
|
||
if (after.timedOut) {
|
||
timedOut = true;
|
||
timedOutIssues.add(entry.issueId);
|
||
timeline.add("baseline_sample_timeout", { adapter, issueId: entry.issueId, phase: "postfault" });
|
||
}
|
||
else timeline.add("baseline_postfault_done", { adapter, issueId: entry.issueId, round });
|
||
}));
|
||
if (timedOut) {
|
||
if (round + 1 < rounds) timeline.add("baseline_postfault_skipped", { reason: "work_not_at_rest", round: round + 1 });
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// Mid-turn follow-up: a comment posted while the agent is inside a long
|
||
// tool call. Records when the comment landed and every run of the task,
|
||
// so the wait splits into "rest of the turn" and "hand-off".
|
||
const runMidturn = async (adapter: (typeof adapters)[number]) => {
|
||
for (let index = 0; index < samples; index += 1) {
|
||
const nonce = `${adapter}-m${index}-${Date.now().toString(36)}`;
|
||
const issueId = await createTask(api, lab, adapter, `TTFT mid-turn ${nonce}`, midturnTask(nonce));
|
||
tasks.push({ issueId, adapter, phase: "midturn" });
|
||
const inside = await waitForShellCall(api, issueId, `time.sleep(${MIDTURN_SLEEP_SECONDS})`);
|
||
if (!inside) {
|
||
timeline.add("baseline_midturn_sample_skipped", { adapter, issueId });
|
||
continue;
|
||
}
|
||
const comment = await api.post<Json>(`/api/issues/${issueId}/comments`, { body: midturnFollowUp(nonce) });
|
||
const steer = midturnMode === "steer" ? await steerQueuedComment(api, issueId, String(comment.id)) : null;
|
||
// Restart right after the steered comment was acknowledged: it must be answered exactly once.
|
||
const fault = midturnFault && steer?.acknowledgedAt
|
||
? await supervisor.fault(midturnFault, 0, `midturn-${index}`) : null;
|
||
if (fault) faults.push({ kind: midturnFault!, readyAt: fault.readyAt ?? Date.now(), runIds: [inside.runId] });
|
||
// A steered comment is answered inside the same run; a queued one needs a second run.
|
||
const settled = await waitForRest(api, supervisor, issueId, steer?.acknowledgedAt ? 1 : 2);
|
||
if (settled.timedOut) {
|
||
timedOutIssues.add(issueId);
|
||
timeline.add("baseline_sample_timeout", { adapter, issueId, phase: "midturn" });
|
||
continue;
|
||
}
|
||
// Read the replies once; a failed read is recorded, not counted as a lost reply.
|
||
const replies = await agentReplies(api, issueId, `HELLO ${nonce}`)
|
||
.catch((error: unknown) => ({ error: error instanceof Error ? error.message : String(error) }));
|
||
midturn.push({ adapter, issueId, mode: midturnMode, interruptedRunId: inside.runId, commentId: String(comment.id),
|
||
commentCreatedAt: String(comment.createdAt), steer, fault: fault ? midturnFault : null,
|
||
replyCount: Array.isArray(replies) ? replies.length : null,
|
||
replyReadError: Array.isArray(replies) ? null : replies.error,
|
||
replyCreatedAt: Array.isArray(replies) && replies[0] ? String(replies[0].createdAt) : null,
|
||
runs: settled.runs });
|
||
timeline.add("baseline_midturn_done", { adapter, issueId, runs: settled.runs.length });
|
||
}
|
||
};
|
||
// Every fault restarts the one shared server, so faulted samples run one
|
||
// at a time: a restart must never land in another sample's comment or steer.
|
||
if (phases.has("midturn")) {
|
||
if (midturnFault) for (const adapter of adapters) await runMidturn(adapter);
|
||
else await Promise.all(adapters.map(runMidturn));
|
||
}
|
||
|
||
// Restart recovery: one in-flight tool call per adapter, then one fault crosses all of them.
|
||
const kinds: FaultKind[] = ["K1", "K2"];
|
||
for (let index = 0; phases.has("restart") && index < restarts * kinds.length; index += 1) {
|
||
const kind = kinds[index % kinds.length]!;
|
||
const inFlight = await Promise.all(adapters.map(async adapter => {
|
||
const nonce = `${adapter}-r${index}-${Date.now().toString(36)}`;
|
||
const issueId = await createTask(api, lab, adapter, `TTFT restart ${nonce}`, restartTask(nonce));
|
||
tasks.push({ issueId, adapter, phase: "restart" });
|
||
const inside = await waitForShellCall(api, issueId);
|
||
return { issueId, adapter, runId: inside?.runId ?? null };
|
||
}));
|
||
// Recheck right before the fault: a fast adapter may have finished its call
|
||
// while a slower one was still starting. Only runs still inside it count.
|
||
const stillInside = await Promise.all(inFlight.map(async entry => {
|
||
if (!entry.runId) return null;
|
||
const inside = await runInShellCall(api, entry.issueId);
|
||
return inside?.runId === entry.runId ? inside : null;
|
||
}));
|
||
for (const [position, entry] of inFlight.entries()) {
|
||
const inside = stillInside[position];
|
||
if (!inside) timeline.add("baseline_restart_sample_skipped", { adapter: entry.adapter, issueId: entry.issueId });
|
||
else if (inside.commandUnverified) {
|
||
timeline.add("baseline_restart_command_unverified", { adapter: entry.adapter, issueId: entry.issueId });
|
||
}
|
||
}
|
||
const runIds = stillInside.flatMap(inside => inside ? [inside.runId] : []);
|
||
for (const runId of runIds) runPhase.set(runId, "restart");
|
||
const receipt = await supervisor.fault(kind, 0, `ttft-baseline-${index}`);
|
||
faults.push({ kind, readyAt: receipt.readyAt ?? Date.now(), runIds });
|
||
const settled = await Promise.all(inFlight.map(entry => waitForRest(api, supervisor, entry.issueId, 1)));
|
||
for (const [position, entry] of inFlight.entries()) {
|
||
if (settled[position]!.timedOut) {
|
||
timedOutIssues.add(entry.issueId);
|
||
timeline.add("baseline_sample_timeout", { adapter: entry.adapter, issueId: entry.issueId, phase: "restart" });
|
||
}
|
||
}
|
||
}
|
||
|
||
const runs: BaselineRun[] = [];
|
||
for (const task of tasks) {
|
||
// A sample that never came to rest is reported, not measured.
|
||
if (timedOutIssues.has(task.issueId)) continue;
|
||
for (const run of await runsFor(api, task.issueId)) {
|
||
const runId = runIdOf(run);
|
||
runs.push({ runId, adapter: task.adapter, environment: env,
|
||
phase: runPhase.get(runId) ?? task.phase, events: await allEvents(api, runId) });
|
||
// Workspace commands (worktree, provision, sync) the run waited on, with their durations.
|
||
const operations = await api.get<Json[]>(`/api/heartbeat-runs/${runId}/workspace-operations`, 10_000).catch((error: unknown) => {
|
||
// A failed read is recorded as such, never as "no workspace operations".
|
||
workspaceOperations.push({ runId, adapter: task.adapter, phase: runPhase.get(runId) ?? task.phase,
|
||
operation: "read_failed", status: error instanceof Error ? error.message.slice(0, 160) : String(error), durationMs: null, command: null });
|
||
return [] as Json[];
|
||
});
|
||
for (const operation of operations) workspaceOperations.push({ runId, adapter: task.adapter,
|
||
phase: runPhase.get(runId) ?? task.phase, operation: String(operation.phase), status: String(operation.status),
|
||
durationMs: operation.startedAt && operation.finishedAt
|
||
? Date.parse(String(operation.finishedAt)) - Date.parse(String(operation.startedAt)) : null,
|
||
command: typeof operation.command === "string" ? operation.command.slice(0, 120) : null });
|
||
}
|
||
}
|
||
const data = { workspaceOperations, waveId, lifecycle: lifecycle ?? "catalog", agentLifecycles, adapters, notReady: requested.filter(adapter => !adapters.includes(adapter)),
|
||
timedOutTasks: timedOutIssues.size, samples, restarts, midturn, gitSha: process.env.GIT_SHA ?? null, runs, faults };
|
||
await writeFile(path.join(outDir, "baseline-data.json"), `${JSON.stringify(data)}\n`, { mode: 0o600 });
|
||
await writeFile(path.join(outDir, "baseline-report.md"), report(runs, faults), { mode: 0o600 });
|
||
process.stdout.write(report(runs, faults));
|
||
if (workspaceOperations.length) {
|
||
const table = ["", "| Run phase | Adapter | Workspace operation | Status | Duration | Command |", "|---|---|---|---|---|---|",
|
||
...workspaceOperations.slice().sort((a, b) => (b.durationMs ?? 0) - (a.durationMs ?? 0))
|
||
.map(op => `| ${op.phase} | ${op.adapter} | ${op.operation} | ${op.status} | ${op.durationMs === null ? "—" : `${(op.durationMs / 1000).toFixed(2)} s`} | ${op.command ? `\`${op.command}\`` : "—"} |`)].join("\n");
|
||
process.stdout.write(`${table}\n`);
|
||
await writeFile(path.join(outDir, "workspace-operations.md"), `${table}\n`, { mode: 0o600 });
|
||
}
|
||
if (timedOutIssues.size) process.stdout.write(`\n${timedOutIssues.size} sample(s) timed out and were left out.\n`);
|
||
// Every answered mid-turn comment must be answered exactly once.
|
||
const wrongReplies = midturn.filter(sample => sample.replyCount !== 1);
|
||
for (const sample of wrongReplies) {
|
||
process.stdout.write(`\nMid-turn sample ${String(sample.adapter)} ${String(sample.issueId)}: ${sample.replyReadError
|
||
? `reply read failed (${String(sample.replyReadError)})` : `${String(sample.replyCount)} replies, expected 1`}\n`);
|
||
}
|
||
if (wrongReplies.length) process.exitCode = 1;
|
||
process.stdout.write(`\nWrote ${outDir}\n`);
|
||
} finally {
|
||
// Every Daytona sandbox this run created is archived or destroyed before the server
|
||
// stops, then the wrapper-owned embedded Postgres stops (SysV shared memory is scarce).
|
||
await shutdown();
|
||
process.off("SIGINT", onSignal);
|
||
process.off("SIGTERM", onSignal);
|
||
}
|
||
}
|
||
|
||
main().catch(error => { process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`); process.exitCode = 1; });
|