mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-24 10:13:11 +02:00
## Thinking Path > - Paperclip manages agents and the work they perform. > - Product E2E tests exercise real agents, tools, setup and cleanup. > - Repeated runs need retained costs and traces, including failed attempts. > - A passing retry must not hide earlier spending or feedback. > - Recurring work also needs admission limits, private reports and failure detection. > - This change supplies those controls while keeping paid activation behind existing gates. ## Linked Issues or Issue Description Refs #16996 and #17158. This is the consolidated landing of the reviewed eval operations stack: #17019, #17024, #17025, #17027, #17030, #17033, #17035, #17038, #17043, #17044, #17048, #17050, #17051, #17092, #17096, #17100, #17107, #17109, #17112, #17115, #17117, #17121, #17123, #17127, #17130, #17133, #17134, #17137, #17140, #17143, #17154. The repository permits squash merges only. A local rehearsal showed that squashing each slice into master causes repeated conflicts in dependent slices. This PR preserves their commits and lands their combined implementation in one reviewed integration. Superseded slices will close after this merge. ## What Changed - Retain every attempt's cost receipt, including setup, failures, interruptions and retries. Separate reported amounts, estimates, missing costs and reserved capacity in reports and dashboards. - Add bounded request admission, exact model pricecards, gateway error accounting, cache policy and reconciliation evidence. Refuse unsupported routes and requests that cannot fit the allowance. - Integrate Braintrust gateway traces and OTLP correlation, with secret filtering and experiment imports. Record phase timing, including setup, feedback capture and cleanup. - Collect complaint and suggestion evidence after each attempt, including recovery after failures. Retain explicit review dispositions independently from the product grade. - Add gated daily and weekly selections, measured forecasts, setup/readiness checks, wall-time limits and retained monitor notifications. Include declared non-model overhead in admission while reporting the existing subscription separately. - Keep recurring history private, bound uploads and retention, and use isolated archive environments. Keep public publication an explicit operation. Report and publication jobs install only the committed lockfile, with scripts disabled and isolated stores; stale pins fail closed. - Integrate current master, preserve its Product E2E journey billing and privacy checks, and test that shared setup receipts do not double-count estimated agent usage. Preserve upstream fixture repairs. ## Verification - Complete integration baseline `0649a5ce7544ab20825c2183d2f421157db49f24` includes master `a3e1d915a7110a4e115b46396a3f79e6dfb4d05e` and every original stack head as ancestors. - On that integration baseline, `pnpm test:e2e:runner:unit`: 4,012 Vitest tests passed, two skipped, across 193 files; all 137 Node source-contract tests passed. - Focused billing and Product E2E journey contract checks: 24 tests passed. They cover estimates, unknown receipts, single-owner setup costs, browser-only execution and private publication guards. - Monitor and workflow wiring: all 96 Node tests passed. `node scripts/check-token-gates.mjs`: all gates clean. - `pnpm test:e2e:runner:typecheck` passes after the standard Runner TypeScript build refreshed local declarations. The first attempt rejected the new master `runner_prepared_launch` union member because this checkout retained an older generated declaration; the source union already contained that member. - Current head `492b0708a1c531a023d9ac10f0f3dc6383cc1754` removes dependency re-resolution from archive-authorized reporting jobs after the security scan flagged it. All 15 workflow-security tests pass after updating the old two-install assertion. - Hosted [CI run 39965460180](https://github.com/paperclipai/paperclip/actions/runs/39965460180) passes on the current repaired head, including typecheck, build, general tests, Runner checks, browser shards and canary dry run. Greptile is 5/5 on this exact head with no unresolved threads. The security scan passes after the fixed lockfile-resolution thread was resolved. - Paperclip Review returned a terminal neutral check but an incomplete 0-file assessment on the repaired head: its platform blocked both diff responses as prompt-injection content. This is not a successful code review. No bypass or fabricated pass was attempted; current-head Greptile, security and hosted CI are independent gates. - No paid test, reservation release or recurring-run activation accompanies this landing. Live route qualification and invoice reconciliation remain separate evidence. <details> <summary>Retained earlier validation failures</summary> Earlier broad local runs had two 15-second test timeouts (CLI poll cadence and Retry validation), one embedded-database setup timeout, and later PostgreSQL semaphore exhaustion. The exact timed-out tests passed separately without larger timeouts; the broad-run causes were not established. Those local failures remain distinct from subsequent hosted CI results. The independent #17158 fix records its Muse fixture collision, its UUID correction and hosted verification. Local Muse execution was also blocked by macOS embedded-PostgreSQL startup. No historical failure is treated as a successful paid qualification. </details> ## Risks - Admission is a local control, not a provider invoice cap. Missing provider receipts or resource charges retain unknown amounts and holds; estimates do not become billed dollars. - The bounded path admits only documented local suites and provider routes. Ordinary legacy or separate Runner protocol campaigns have different controls. Merging this code does not qualify additional routes. - Recurrence still needs the existing enable gates and current qualification/allowance evidence. Archive permissions and resources must match the documented private-environment contract. - Legacy reports may lack complete attempt or phase evidence. Reports preserve that limitation and do not infer zero usage from missing data. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools and code execution. The exact deployment variant and context-window size are not exposed by this session. ## 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 (targeted checks; full-suite host limitation disclosed above) - [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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
270 lines
15 KiB
TypeScript
270 lines
15 KiB
TypeScript
import type { ChildProcess } from "node:child_process";
|
|
import {
|
|
observeDescendantProcessTree, readProcessTable, revalidateObservedProcessGroups,
|
|
refreshContinuouslyLiveProcessGroups, safeProcessGroupTerminationOrder,
|
|
type ObservedProcessGroup, type ProcessObservation,
|
|
} from "./process-tree.js";
|
|
|
|
/** Supplied by the company-scoped run API, never by process-name discovery. */
|
|
export interface RestartRunnerIdentity {
|
|
processPid: number;
|
|
processGroupId: number;
|
|
processStartedAt: string;
|
|
}
|
|
export function parseRestartRunnerIdentity(value: unknown): RestartRunnerIdentity {
|
|
const v = value as RestartRunnerIdentity | null;
|
|
if (!v || !Number.isSafeInteger(v.processPid) || v.processPid <= 1
|
|
|| v.processGroupId !== v.processPid || typeof v.processStartedAt !== "string"
|
|
|| !Number.isFinite(Date.parse(v.processStartedAt))) throw new Error("Invalid restart runner identity");
|
|
return { processPid: v.processPid, processGroupId: v.processGroupId, processStartedAt: v.processStartedAt };
|
|
}
|
|
|
|
/** Linux run receipts retain milliseconds; ps lstart retains whole seconds. */
|
|
export function restartProcessStartMatches(observed: string, expected: string, platform = process.platform): boolean {
|
|
const actualTime = Date.parse(observed), expectedTime = Date.parse(expected);
|
|
if (!Number.isFinite(actualTime) || !Number.isFinite(expectedTime)) return false;
|
|
return platform === "linux"
|
|
? Math.floor(actualTime / 1000) === Math.floor(expectedTime / 1000)
|
|
: actualTime === expectedTime;
|
|
}
|
|
|
|
export function createProcessTreeOwner(root: ChildProcess, options: {
|
|
readTable?: () => Promise<ProcessObservation[] | null>;
|
|
signalGroup?: (pid: number, signal: NodeJS.Signals) => void;
|
|
} = {}) {
|
|
let groups: ObservedProcessGroup[] = [];
|
|
let table: ProcessObservation[] = [];
|
|
let rootStarted: string | undefined;
|
|
let preserved: ObservedProcessGroup[] = [];
|
|
let restartRunner: ProcessObservation | undefined;
|
|
let observing: Promise<void> | undefined;
|
|
const covered = new Set<number>();
|
|
const readTable = options.readTable ?? readProcessTable;
|
|
const signalGroup = options.signalGroup ?? ((pid, signal) => process.kill(-pid, signal));
|
|
const exited = () => root.exitCode !== null || root.signalCode !== null || !root.pid;
|
|
const running = (candidate: ProcessObservation) => !candidate.state?.startsWith("Z");
|
|
|
|
function observe(): Promise<void> {
|
|
if (process.platform === "win32") return Promise.resolve();
|
|
if (observing) return observing;
|
|
observing = (async () => {
|
|
const next = await readTable();
|
|
if (!next) throw new Error("Could not inspect owned process identities");
|
|
const callerGroup = next.find(row => row.pid === process.pid)?.processGroupId;
|
|
if (callerGroup === undefined) throw new Error("Cleanup caller group identity is unavailable");
|
|
const rootRow = next.find(row => row.pid === root.pid);
|
|
if (!rootStarted && !exited()) rootStarted = rootRow?.started;
|
|
const retained = revalidateObservedProcessGroups(groups, next);
|
|
const trustedAnchors = retained.flatMap(group => group.members
|
|
.filter(member => next.some(row => row.pid === member.pid && row.started === member.started
|
|
&& row.processGroupId === group.processGroupId)).map(member => member.pid));
|
|
if (rootRow && rootStarted === rootRow.started) trustedAnchors.push(rootRow.pid);
|
|
const ownedNow = new Set(trustedAnchors.flatMap(pid =>
|
|
observeDescendantProcessTree(next, pid).members.map(member => member.process.pid)));
|
|
// A short-lived leader can exit between polls while its replacement
|
|
// remains a descendant of a separately validated owner. Admit that
|
|
// ancestry, never a recycled numeric group or a mixed ownership group.
|
|
const lost = groups.filter(group => !retained.includes(group) && next.some(row => row.processGroupId === group.processGroupId && running(row)));
|
|
const uncertain = lost.filter(group => next.some(row => row.processGroupId === group.processGroupId
|
|
&& running(row) && !ownedNow.has(row.pid)));
|
|
if (uncertain.length) throw new Error(`Owned process group identity became uncertain: ${uncertain.map(group => group.processGroupId).join(",")}`);
|
|
const refreshed = refreshContinuouslyLiveProcessGroups([...retained, ...lost], next)
|
|
.filter(group => group.processGroupId !== callerGroup);
|
|
const anchors = refreshed.flatMap(group => group.members.map(member => member.pid));
|
|
if (rootRow && rootStarted === rootRow.started) anchors.push(rootRow.pid);
|
|
const byGroup = new Map(refreshed.map(group => [group.processGroupId, group]));
|
|
for (const pid of anchors) {
|
|
for (const group of observeDescendantProcessTree(next, pid).groups) {
|
|
if (group.processGroupId !== callerGroup) {
|
|
// A descendant traversal can cover only part of an already
|
|
// validated group. Keep every observed peer as an identity anchor.
|
|
const previous = byGroup.get(group.processGroupId);
|
|
const members = new Map(previous?.members.map(member => [member.pid, member]) ?? []);
|
|
for (const member of group.members) members.set(member.pid, member);
|
|
byGroup.set(group.processGroupId, { ...group,
|
|
depth: Math.max(group.depth, previous?.depth ?? group.depth),
|
|
members: [...members.values()],
|
|
});
|
|
if (covered.has(next.find(row => row.pid === pid)!.processGroupId)) covered.add(group.processGroupId);
|
|
}
|
|
}
|
|
}
|
|
groups = [...byGroup.values()];
|
|
// Follow only continuously owned members of the admitted daemon tree.
|
|
// Orphaned descendants stay owned, but unrelated controller children do not.
|
|
const retainedPreserved = refreshContinuouslyLiveProcessGroups(revalidateObservedProcessGroups(preserved, next), next);
|
|
const preservedIds = new Set(retainedPreserved.map(group => group.processGroupId));
|
|
for (const member of retainedPreserved.flatMap(group => group.members)) {
|
|
for (const group of observeDescendantProcessTree(next, member.pid).groups) preservedIds.add(group.processGroupId);
|
|
}
|
|
preserved = groups.filter(group => preservedIds.has(group.processGroupId));
|
|
table = next;
|
|
})().finally(() => { observing = undefined; });
|
|
return observing;
|
|
}
|
|
const timer = process.platform === "win32" ? undefined : setInterval(() => {
|
|
void observe().catch(() => { /* Stop must obtain a fresh successful inspection. */ });
|
|
}, 250);
|
|
timer?.unref();
|
|
void observe().catch(() => {});
|
|
|
|
function liveGroups() {
|
|
return groups.filter(group => table.some(row => row.processGroupId === group.processGroupId && running(row)));
|
|
}
|
|
async function preserveRunnerForRestart(identity: RestartRunnerIdentity) {
|
|
const expected = parseRestartRunnerIdentity(identity);
|
|
await observe();
|
|
if (restartRunner || exited()) throw new Error("Restart runner admission must precede controller exit");
|
|
const tree = observeDescendantProcessTree(table, root.pid!);
|
|
const candidate = tree.members.map(member => member.process).find(row => row.pid === expected.processPid);
|
|
if (!candidate || !running(candidate) || candidate.kind !== "paperclip-runnerd"
|
|
|| candidate.processGroupId !== expected.processGroupId
|
|
|| !restartProcessStartMatches(candidate.started, expected.processStartedAt)
|
|
|| candidate.processGroupId === root.pid) throw new Error("Restart runner is not the exact owned durable daemon");
|
|
const subtree = observeDescendantProcessTree(table, candidate.pid);
|
|
const members = new Set(subtree.members.map(member => member.process.pid));
|
|
const ids = new Set(subtree.groups.map(group => group.processGroupId));
|
|
if (table.some(row => ids.has(row.processGroupId) && !members.has(row.pid) && running(row))) {
|
|
throw new Error("Restart runner shares a process group with an unrelated process");
|
|
}
|
|
restartRunner = { ...candidate };
|
|
preserved = groups.filter(group => ids.has(group.processGroupId));
|
|
}
|
|
function assertRestartRunnerAlive() {
|
|
if (!restartRunner || !table.some(row => row.pid === restartRunner!.pid && row.started === restartRunner!.started
|
|
&& row.processGroupId === restartRunner!.processGroupId && running(row))) throw new Error("Admitted restart runner did not survive controller restart");
|
|
}
|
|
function restartCleanupGroups() {
|
|
const ids = new Set(preserved.map(group => group.processGroupId));
|
|
return new Set(liveGroups().filter(group => !ids.has(group.processGroupId)).map(group => group.processGroupId));
|
|
}
|
|
function signalSnapshot(signal: NodeJS.Signals, selected?: ReadonlySet<number>) {
|
|
const currentProcessGroupId = table.find(row => row.pid === process.pid)?.processGroupId ?? null;
|
|
if (currentProcessGroupId === null) throw new Error("Cleanup caller group identity is unavailable");
|
|
const live = liveGroups();
|
|
const ordered = safeProcessGroupTerminationOrder({ rootProcessGroupId: root.pid ?? -1, currentProcessGroupId, groups: live });
|
|
const signaled: number[] = [];
|
|
for (const pid of ordered) {
|
|
if (selected && !selected.has(pid)) continue;
|
|
try { signalGroup(pid, signal); }
|
|
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; else continue; }
|
|
signaled.push(pid);
|
|
}
|
|
return signaled;
|
|
}
|
|
async function signal(signal: NodeJS.Signals, selected?: ReadonlySet<number>) {
|
|
await observe();
|
|
return signalSnapshot(signal, selected);
|
|
}
|
|
function gracefulRoots() {
|
|
const live = liveGroups();
|
|
const ids = new Set(live.map(group => group.processGroupId));
|
|
if (root.pid && ids.has(root.pid)) return new Set([root.pid]);
|
|
// After the launcher's leader exits, request shutdown only from the
|
|
// outermost remaining owners; their wrappers still own child signaling.
|
|
const byPid = new Map(table.map(row => [row.pid, row]));
|
|
return new Set(live.filter(group => !table.some(row => {
|
|
if (row.processGroupId !== group.processGroupId) return false;
|
|
const seen = new Set<number>();
|
|
let parent = byPid.get(row.parentPid);
|
|
while (parent && !seen.has(parent.pid)) {
|
|
seen.add(parent.pid);
|
|
if (parent.processGroupId !== group.processGroupId && ids.has(parent.processGroupId)) return true;
|
|
parent = byPid.get(parent.parentPid);
|
|
}
|
|
return false;
|
|
})).map(group => group.processGroupId));
|
|
}
|
|
let graceComplete = false;
|
|
let directGraceDelivered = false;
|
|
async function signalGracefully(signal: "SIGTERM" | "SIGINT" = "SIGTERM") {
|
|
if (graceComplete) return;
|
|
await observe();
|
|
// Choose and deliver from one validated table. ESRCH grants no ownership
|
|
// coverage: the next grace poll can select that branch's surviving owner.
|
|
const selected = new Set([...gracefulRoots()].filter(pid => !covered.has(pid)));
|
|
const delivered = signalSnapshot(signal, selected);
|
|
for (const pid of delivered) {
|
|
if (pid === root.pid) directGraceDelivered = true;
|
|
covered.add(pid);
|
|
for (const member of table.filter(row => row.processGroupId === pid)) {
|
|
for (const group of observeDescendantProcessTree(table, member.pid).groups) covered.add(group.processGroupId);
|
|
}
|
|
}
|
|
// Never reselect descendants after their owner received grace, even if it
|
|
// exits before their asynchronous close completes.
|
|
graceComplete = selected.size > 0 && delivered.length === selected.size;
|
|
}
|
|
return { observe, signal, liveGroups, gracefulRoots, signalGracefully,
|
|
preserveRunnerForRestart, assertRestartRunnerAlive, restartCleanupGroups,
|
|
directGraceDelivered: () => directGraceDelivered, stopObserving: () => { if (timer) clearInterval(timer); } };
|
|
}
|
|
|
|
|
|
/** Inspection failure grants no group authority. The unreaped ChildProcess
|
|
* handle still owns its direct child, so retire only that child within the
|
|
* original grace deadline, then report the incomplete tree audit. */
|
|
export async function stopKnownDirectChild(child: ChildProcess, phase: { gracefulSent: boolean; forcedDeadline?: number },
|
|
deadline: number, forcedMs: number, signal: NodeJS.Signals = "SIGTERM") {
|
|
const exited = () => child.exitCode !== null || child.signalCode !== null || !child.pid;
|
|
const wait = () => new Promise(resolve => setTimeout(resolve, 25));
|
|
if (!exited() && !phase.gracefulSent) {
|
|
phase.gracefulSent = child.kill(signal);
|
|
}
|
|
while (!exited() && Date.now() < deadline) await wait();
|
|
if (exited()) return;
|
|
child.kill("SIGKILL");
|
|
phase.forcedDeadline ??= Date.now() + forcedMs;
|
|
while (!exited() && Date.now() < phase.forcedDeadline) await wait();
|
|
if (!exited()) throw new Error("Known direct child remained after bounded fallback");
|
|
}
|
|
|
|
export async function incompleteTreeFallback(error: unknown, child: ChildProcess,
|
|
phase: { gracefulSent: boolean; forcedDeadline?: number }, deadline: number, forcedMs: number,
|
|
signal: "SIGTERM" | "SIGINT" = "SIGTERM") {
|
|
let fallbackError: unknown;
|
|
try { await stopKnownDirectChild(child, phase, deadline, forcedMs, signal); }
|
|
catch (failure) { fallbackError = failure; }
|
|
throw new Error(`Owned tree cleanup incomplete: ${String(error)}${fallbackError ? `; ${String(fallbackError)}` : ""}`);
|
|
}
|
|
|
|
/** Give the launcher/wrapper chain sole graceful-signal ownership, then retire
|
|
* only still-observed descendants. Used on normal exit as well as cancellation. */
|
|
export async function stopOwnedProcessTree(
|
|
child: ChildProcess,
|
|
owner: ReturnType<typeof createProcessTreeOwner>,
|
|
gracefulMs = 45_000,
|
|
forcedMs = 5_000,
|
|
gracefulSignal: "SIGTERM" | "SIGINT" = "SIGTERM",
|
|
): Promise<void> {
|
|
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
|
const deadline = Date.now() + gracefulMs;
|
|
const phase: { gracefulSent: boolean; forcedDeadline?: number } = { gracefulSent: false };
|
|
try {
|
|
if (process.platform === "win32") {
|
|
await stopKnownDirectChild(child, phase, deadline, forcedMs, gracefulSignal);
|
|
return;
|
|
}
|
|
const stopped = async () => {
|
|
await owner.observe();
|
|
return (child.exitCode !== null || child.signalCode !== null) && owner.liveGroups().length === 0;
|
|
};
|
|
do {
|
|
await owner.signalGracefully(gracefulSignal);
|
|
phase.gracefulSent ||= owner.directGraceDelivered();
|
|
if (await stopped()) return;
|
|
await wait(50);
|
|
} while (Date.now() < deadline);
|
|
await owner.signal("SIGKILL");
|
|
phase.forcedDeadline = Date.now() + forcedMs;
|
|
do {
|
|
if (await stopped()) return;
|
|
await wait(50);
|
|
} while (Date.now() < phase.forcedDeadline);
|
|
throw new Error("Observed launcher descendants remained after bounded cleanup");
|
|
} catch (error) {
|
|
phase.gracefulSent ||= owner.directGraceDelivered();
|
|
await incompleteTreeFallback(error, child, phase, deadline, forcedMs, gracefulSignal);
|
|
}
|
|
}
|