mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness grades every task at the end of a release-swap wave, locally (RS1) and on a hosted staging instance (hosted mode) > - The first hosted 3-release run graded 79 / 80, and the one failure was a harness artefact: the drain declared quiet 20 s after a parent's run ended, before the product's children-completed wake created its continuation, so the task read as "nothing pending" and cleanup then cancelled the continuation > - The same run showed three more reporting gaps: per-turn product notices counted as duplicated comments, failed requests could not be broken down because request records stayed in memory (and the API count included the health probes), and the per-swap table charged every failed run to the last swap before it > - Separately, the local swap timeline marked the start of a swap with `fault_started` carrying `"signal":"SIGTERM"`, while the outgoing server's real SIGTERM was `fault_server_down`; that has led to wrong conclusions twice > - This pull request fixes the drain rule, the comment count, the request records, the release attribution and the swap timeline > - The benefit is that the one number and the per-swap table mean what they say ## Linked Issues or Issue Description Refs #21153 Refs #21126 **Describe the bug** 1. A task whose continuation is created after the drain declares quiet is graded `nothing pending`, and cleanup cancels the continuation. 2. "Prepared <document> for this response." notices, one per turn, count as duplicated agent comments. 3. Request failures cannot be broken down after the run, and the API continuity count includes health probes. 4. A failed run is attributed to the last swap before it, however long after. 5. `fault_started` carries `"signal":"SIGTERM"` for an overlap swap, though it marks the swap request; the outgoing SIGTERM is a different event. **Steps to reproduce** Run a hosted or local release-swap wave with parent tasks whose subtasks finish near the end of the wave. **Expected behavior** The grade waits for continuations, notices are informational, request records are saved, failed runs are attributed to a release only when live at it or soon after, and the timeline names each swap moment. ## What Changed - `release-swap-grade.ts`: shared `drainState` (quiet only when nothing is progressing and no run was created or finished for 90 s, `QUIET_PERIOD_MS`); `failedAtSwap` / `swapForFailedRun` / `failedOutsideSwaps` (a failed run counts at a swap if it was live at the outgoing SIGTERM or failed within 15 minutes of it, `RELEASE_FAILURE_WINDOW_MS`, and at most one swap); `isAutoNotice`; the summary lists failed runs outside any release window and the notice repeats as information. - `release-swap-finish.ts` (local RS1): uses `drainState` and the new attribution; the duplicate-comment query separates the notice. - `hosted-grade.ts`: uses `drainState` (`--hosted-quiet-seconds`, default 90); reads runs, tasks and task views again immediately before grading; breaks request failures down by status and by inside/outside the release windows. - `hosted-api.ts`, `hosted-main.ts`: every request record carries kind (health or API) and a path class with ids replaced; `requests.jsonl` is written to the results directory; API continuity no longer includes health probes. - `hosted-readers.ts`: duplicated agent comments and notice repeats are returned separately. - `release-swap-driver.ts`, `release-swap-moments.ts` (new): the timeline records `swap_incoming_spawned`, `swap_incoming_ready`, `swap_traffic_switched`, `swap_outgoing_sigterm` and `swap_outgoing_exited`; the summary prints the five times per swap and, for every run started during the swap, the two moments it started between and which server started it; `release-swap.json` carries both. - `supervisor.ts` (same line count, still 1,000 lines): `fault_started` for an overlap swap carries `marks: "swap_requested"` instead of a signal. No test reads that signal; `fault_server_down` stays. - `README.md`: documents the quiet period, attribution window, notice rule, request records and swap moments. ## Verification - `node server/node_modules/vitest/vitest.mjs run --config tests/restart-chaos/vitest.config.ts` on the hosted, release-swap and triggers test files: 105 tests pass across 12 files. - Red/green for the drain race (`hosted-drain.test.ts`): a parent's run ends, a children-completed continuation is created 20 s later and succeeds; with the old rule (quiet period 0) the task grades `still_working`/not by the continuation, with the new rule it grades `pass` after the continuation ends. - New tests for the notice filter, `pathClass` and the request breakdown, the 15-minute attribution, and the five swap moments (both the timeline events from the driver and the summary placement of runs between moments, with the starting server). - `node server/node_modules/typescript/bin/tsc -p tests/restart-chaos/tsconfig.json`: clean. ## Risks - Low risk: harness-only. The end-of-wave grade waits up to 90 s longer after the last run change, within the existing drain cap. - Per-swap failed-run counts change meaning: runs that failed more than 15 minutes after a stop and were not live at it move to the "failed outside a release window" line. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits). Default context window; no extended thinking mode. ## 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>
187 lines
9.3 KiB
TypeScript
187 lines
9.3 KiB
TypeScript
import type { HostedApi } from "./hosted-api.js";
|
|
import { isAutoNotice, type GradeRun, type GradeTaskInput } from "./release-swap-grade.js";
|
|
|
|
type Json = Record<string, any>;
|
|
export type ReadApi = Pick<HostedApi, "get">;
|
|
|
|
export const UNAVAILABLE_OVER_API = [
|
|
"queuedWakes: the API has no read of a task's queued wake requests, so a task whose only owner is a queued wake grades as having none",
|
|
"ownerPid / owning server process of each run: the API does not expose which server process (controller boot) owned a run",
|
|
"lostWhileOldAlive: needs the owning server process, so it is not computed",
|
|
"doubleExecutors: two Runner processes for one run come from database cross-server evidence, not the API",
|
|
"late-start and preparation-during-recovery evidence: the harness does not drive the release, so it cannot place probes on the outgoing server",
|
|
] as const;
|
|
|
|
export interface HostedRunRow {
|
|
runId: string;
|
|
agentId: string | null;
|
|
issueId: string | null;
|
|
status: string;
|
|
errorCode: string | null;
|
|
error: string | null;
|
|
createdAt: number | null;
|
|
startedAt: number | null;
|
|
finishedAt: number | null;
|
|
lastActivityAt: number | null;
|
|
ownerPid: null;
|
|
}
|
|
|
|
export interface HostedIssueRow {
|
|
id: string;
|
|
identifier: string | null;
|
|
title: string;
|
|
status: string;
|
|
parentId: string | null;
|
|
assigneeAgentId: string | null;
|
|
hidden: boolean;
|
|
}
|
|
|
|
const ms = (value: unknown): number | null => {
|
|
if (value === null || value === undefined || value === "") return null;
|
|
const parsed = typeof value === "number" ? value : Date.parse(String(value));
|
|
return Number.isFinite(parsed) ? parsed : null;
|
|
};
|
|
const text = (value: unknown): string | null => value === null || value === undefined ? null : String(value);
|
|
|
|
export function runRow(run: Json): HostedRunRow {
|
|
const activity = [ms(run.updatedAt), ms(run.lastOutputAt), ms(run.lastUsefulActionAt), ms(run.finishedAt)].filter((at): at is number => at !== null);
|
|
return {
|
|
runId: String(run.id), agentId: text(run.agentId), issueId: text(run.issueId ?? run.contextSnapshot?.issueId), status: String(run.status),
|
|
errorCode: text(run.errorCode), error: run.error ? String(run.error).slice(0, 400) : null,
|
|
createdAt: ms(run.createdAt), startedAt: ms(run.startedAt), finishedAt: ms(run.finishedAt),
|
|
lastActivityAt: activity.length ? Math.max(...activity) : null, ownerPid: null,
|
|
};
|
|
}
|
|
|
|
export const RUN_PAGE = 1_000;
|
|
export const ISSUE_PAGE = 500;
|
|
export const EVENT_PAGE = 500;
|
|
|
|
export async function hostedIssues(api: ReadApi, companyId: string, agentIds: readonly string[]): Promise<HostedIssueRow[]> {
|
|
const byId = new Map<string, HostedIssueRow>();
|
|
for (const agentId of agentIds) {
|
|
for (let offset = 0; ; offset += ISSUE_PAGE) {
|
|
const page = await api.get<Json[]>(`/api/companies/${companyId}/issues?assigneeAgentId=${encodeURIComponent(agentId)}&includeAgentCreatedTasks=true`
|
|
+ `&limit=${ISSUE_PAGE}&offset=${offset}`);
|
|
for (const issue of page) {
|
|
if (issue.assigneeAgentId !== agentId) continue;
|
|
byId.set(String(issue.id), { id: String(issue.id), identifier: text(issue.identifier), title: String(issue.title ?? ""), status: String(issue.status),
|
|
parentId: text(issue.parentId), assigneeAgentId: text(issue.assigneeAgentId), hidden: Boolean(issue.hiddenAt) });
|
|
}
|
|
if (page.length < ISSUE_PAGE) break;
|
|
}
|
|
}
|
|
return [...byId.values()];
|
|
}
|
|
|
|
export async function hostedCompanyRuns(api: ReadApi, companyId: string, agentIds: readonly string[]): Promise<HostedRunRow[]> {
|
|
const rows = new Map<string, HostedRunRow>();
|
|
let truncated = false;
|
|
for (const agentId of agentIds) {
|
|
const page = await api.get<Json[]>(`/api/companies/${companyId}/heartbeat-runs?agentId=${encodeURIComponent(agentId)}&limit=${RUN_PAGE}`);
|
|
if (page.length >= RUN_PAGE) truncated = true;
|
|
for (const run of page) if (run.agentId === agentId) rows.set(String(run.id), runRow(run));
|
|
}
|
|
if (!truncated) return [...rows.values()];
|
|
const ours = new Set(agentIds);
|
|
for (const issue of await hostedIssues(api, companyId, agentIds)) {
|
|
const runs = await api.get<Json[]>(`/api/issues/${issue.id}/runs`);
|
|
for (const run of runs) {
|
|
if (!ours.has(String(run.agentId)) || rows.has(String(run.runId))) continue;
|
|
rows.set(String(run.runId), runRow({ ...run, id: run.runId, issueId: issue.id }));
|
|
}
|
|
}
|
|
return [...rows.values()];
|
|
}
|
|
|
|
export function startedIssues(issues: readonly HostedIssueRow[], runs: readonly HostedRunRow[]): HostedIssueRow[] {
|
|
const withRun = new Set(runs.flatMap(run => run.issueId ? [run.issueId] : []));
|
|
return issues.filter(issue => !issue.hidden && withRun.has(issue.id));
|
|
}
|
|
|
|
export async function pendingPersonItems(api: ReadApi, issueIds: readonly string[]): Promise<{ questions: Set<string>; approvals: Set<string>; unreadable: string[] }> {
|
|
const questions = new Set<string>();
|
|
const approvals = new Set<string>();
|
|
const unreadable: string[] = [];
|
|
for (const id of issueIds) {
|
|
try {
|
|
const interactions = await api.get<Json[]>(`/api/issues/${id}/interactions`);
|
|
if (interactions.some(interaction => interaction.status === "pending")) questions.add(id);
|
|
const linked = await api.get<Json[]>(`/api/issues/${id}/approvals`);
|
|
if (linked.some(approval => ["pending", "revision_requested"].includes(String(approval.status ?? approval.approval?.status)))) approvals.add(id);
|
|
} catch {
|
|
unreadable.push(id);
|
|
}
|
|
}
|
|
return { questions, approvals, unreadable };
|
|
}
|
|
|
|
export function issueViewFields(issue: Json): Omit<GradeTaskInput, "issueId" | "identifier" | "title" | "runs" | "queuedWakes" | "retryClicks" | "pendingApproval" | "pendingQuestion"> {
|
|
const interruption = issue.interruption;
|
|
return {
|
|
status: String(issue.status),
|
|
scheduledRetry: Boolean(issue.scheduledRetry),
|
|
interruption: interruption ? { state: String(interruption.state), canRetry: interruption.canRetry === true, retryWait: Boolean(interruption.retryWait),
|
|
userAction: text(interruption.userAction), responsibility: text(interruption.responsibility), providerFailureCategory: text(interruption.providerFailure?.category) } : null,
|
|
activeRecoveryOwner: text(issue.activeRecoveryAction?.ownerType),
|
|
executionBlocker: Boolean(issue.executionBlocker),
|
|
openBlockers: (issue.blockedBy ?? []).filter((blocker: Json) => blocker.status !== "done" && blocker.status !== "cancelled").length,
|
|
};
|
|
}
|
|
|
|
export function gradeRuns(runs: readonly HostedRunRow[]): GradeRun[] {
|
|
return runs.map(run => ({ runId: run.runId, status: run.status, errorCode: run.errorCode, createdAt: run.createdAt, startedAt: run.startedAt,
|
|
finishedAt: run.finishedAt, lastActivityAt: run.lastActivityAt }));
|
|
}
|
|
|
|
export async function runEvents(api: ReadApi, runId: string): Promise<Json[]> {
|
|
const events: Json[] = [];
|
|
for (let afterSeq = 0; ;) {
|
|
const page = await api.get<Json[]>(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=${EVENT_PAGE}`);
|
|
events.push(...page);
|
|
const last = Number(page.at(-1)?.seq);
|
|
if (page.length < EVENT_PAGE || !Number.isFinite(last) || last <= afterSeq) return events;
|
|
afterSeq = last;
|
|
}
|
|
}
|
|
|
|
export async function failureChain(api: ReadApi, runId: string): Promise<string[]> {
|
|
const events = await runEvents(api, runId).catch(() => [] as Json[]);
|
|
return events.filter(event => event.level === "error" || event.level === "warn" || /fail|error|lost/i.test(String(event.eventType)))
|
|
.slice(-6).map(event => `${event.eventType}${event.message ? `: ${String(event.message).slice(0, 240)}` : ""}`);
|
|
}
|
|
|
|
export async function firstEventAfter(api: ReadApi, runId: string, after: number): Promise<number | null> {
|
|
const events = await runEvents(api, runId).catch(() => [] as Json[]);
|
|
const times = events.map(event => ms(event.createdAt)).filter((at): at is number => at !== null && at > after);
|
|
return times.length ? Math.min(...times) : null;
|
|
}
|
|
|
|
export async function duplicateAgentComments(api: ReadApi, issueIds: readonly string[]):
|
|
Promise<{ duplicateComments: Array<{ issueId: string; count: number }>; autoNoticeRepeats: Array<{ issueId: string; count: number }> }> {
|
|
const duplicateComments: Array<{ issueId: string; count: number }> = [];
|
|
const autoNoticeRepeats: Array<{ issueId: string; count: number }> = [];
|
|
for (const id of issueIds) {
|
|
const comments = await api.get<Json[]>(`/api/issues/${id}/comments`).catch(() => [] as Json[]);
|
|
const counts = new Map<string, { body: string; count: number }>();
|
|
for (const comment of comments) if (comment.authorAgentId) {
|
|
const key = `${comment.authorAgentId}\u0000${comment.body}`;
|
|
counts.set(key, { body: String(comment.body ?? ""), count: (counts.get(key)?.count ?? 0) + 1 });
|
|
}
|
|
for (const { body, count } of counts.values()) if (count > 1) (isAutoNotice(body) ? autoNoticeRepeats : duplicateComments).push({ issueId: id, count });
|
|
}
|
|
return { duplicateComments, autoNoticeRepeats };
|
|
}
|
|
|
|
export function duplicateChildren(issues: readonly HostedIssueRow[]): Array<{ parentId: string; title: string; count: number }> {
|
|
const counts = new Map<string, { parentId: string; title: string; count: number }>();
|
|
for (const issue of issues) {
|
|
if (!issue.parentId || issue.hidden) continue;
|
|
const key = `${issue.parentId}\u0000${issue.title}`;
|
|
const entry = counts.get(key) ?? { parentId: issue.parentId, title: issue.title, count: 0 };
|
|
entry.count += 1;
|
|
counts.set(key, entry);
|
|
}
|
|
return [...counts.values()].filter(entry => entry.count > 1);
|
|
}
|