Files
PaperClipAI/tests/restart-chaos/invariants.ts
DottaandClaude 5ab98b0063 test(restart-chaos): add database contention workload and universal checks U1-U4 (#20421)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The restart chaos harness (`tests/restart-chaos/`) runs real agent
tasks on an isolated control plane and grades them.
> - Two production failures on 2026-11-09 passed the harness. Its tasks
made little output and little accounting, so database write contention
never happened (#20385). Its grading was per workload, so a task stuck
for a reason no scenario targeted was not caught (#20361).
> - The harness needs a contention workload and checks that apply to
every task.
> - This pull request adds the L1 workload, a `--db-pressure` knob, and
the universal checks U1–U4.
> - The benefit is that the #20385 failure class and unexplained stuck
or misleading tasks now fail a wave.

## Linked Issues or Issue Description

Refs #20385, #20383, #20361.

**What happened?**

The harness ran real embedded PostgreSQL, but no task streamed enough
run-log output while usage receipts committed. The #20385 receipt race
(SQLSTATE 40001, retained outbox, `native_event_replay_conflict`) could
not occur. Also, no rule checked every task for an owner or an
actionable item, for retry loops, for diagnosable failures, or for stale
notices.

**Expected behavior**

A chaos wave can create run-row contention between run-log writes and
accounting writes and check that accounting stays exact. Every task of
every wave gets scenario-independent liveness and notice checks.

**Steps to reproduce**

Run an L1 wave with `--db-pressure 4` against the parent of the #20385
merge (red), then against master (green). Commands are in Verification.

## What Changed

- `contention.ts` (new): workload L1 (five 3,000-line shell outputs as
five tool calls, then a brief), its accounting oracle, and
`RunRowPressure`, the `--db-pressure <writers>` knob. The writers run
`update heartbeat_runs set updated_at = updated_at` on the wave
company's running runs, in the wave's own isolated database only.
- L1 oracle: no `native_event_replay_conflict` or
`runner_event_commit_stalled`; each producer event journaled once; a
terminal receipt for each succeeded native run; finished runs accounted;
per-run cost equals its cost events; the board's spend equals the
cost-event sum with no runs pending accounting; and proof that the task
produced contention.
- `universal.ts` (new): U1 liveness, U2 no silent retry loop, U3
diagnosable failures, U4 no stale notices. `grader.ts` grades them on
every task. U1, U2 and U4 fail a task. U3 is a warning.
- `invariants.ts`: `readUniversalDbEvidence` reads failed-run error text
and recovery-action causes from the wave database at wave end, for U3.
- `universal-audit.ts` (new): runs U1–U4 over saved wave evidence to
measure false positives and bound headroom.
- `contention-db.test.ts` (new): on real PostgreSQL, under the pressure
writers, the pre-#20385 repeatable-read receipt write exhausts its
retries with 40001 and the current writer commits.
- Small registry edits: `types.ts` (L1 id, `dbPressure`, optional
`contention` and `universal` fields), `workloads.ts` (L1 entry),
`config.ts` (`--db-pressure`, L1 not a default), `main.ts` (start and
stop the writers, read database evidence before teardown), `ledger.ts`
(universal verdicts and warnings in the ledger and `SUMMARY.md`).
- README: "Database contention" and "Universal checks" sections, with
the audit table and bound reasons.

## Verification

- `contention-db.test.ts` (real embedded PostgreSQL): with
`--db-pressure` writers (4), the pre-#20385 repeatable-read receipt
write exhausted its retries with 40001 in 8 of 8 attempts; the current
READ COMMITTED `persistUsageReceipt` committed 8 of 8. This is the
harness-level red/green for #20385.
- Live L1 waves (`--env local --adapters codex,claude --workloads L1
--faults K1 --concurrency 4 --tasks 4 --seed 20385 --db-pressure 4`),
red on the #20385 parent `bf818280f2` with this harness overlaid and
green on this branch: queued behind the shared one-wave-at-a-time lock
and not yet run. The first red attempt failed at startup (the fresh
checkout lacked a built plugin SDK; no tasks ran). Live results are not
claimed here.

- `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts`:
all harness unit tests pass, including the new `universal.test.ts`,
`contention.test.ts` and `contention-db.test.ts`.
- `node scripts/typecheck-test-projects.mjs tests/restart-chaos`:
passes.
- Universal-check audit over 74 saved waves (1,592 tasks): U1 7 flags
(one C1 stall and six R1 runs queued 8 min behind a retry row, the
#20361 shape), U2 1, U3 22, U4 0. None of U1, U2 or U4 flags a passing
task or an all-pass wave. U3 flags 3 passing tasks (all
`adapter_failed`), so it ships as a warning.

## Risks

- U1, U2 and U4 can now fail a task that passed R1–R6 and T. The audit
found no such case in 70 saved waves. The bounds are
environment-configurable.
- `--db-pressure` is opt-in and writes no values. It writes only to the
wave's own temporary database.
- Other agents edit the same harness. This change keeps registry edits
small; `grader.ts` and `invariants.ts` changes are additive.
- No product code changes.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file editing, GitHub CLI).

## 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 <noreply@anthropic.com>
2026-11-09 22:02:57 -06:00

209 lines
13 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Plan invariants I1–I8 for one wave (durable ownership plan, "Invariants").
*
* Runs the Phase 1 report-only ownership reconciler against the wave's own
* database after every task rested. Nothing is written: `record: false`.
*
* I1, I2 two passes at the real clock: a record with no owner stamp (I1),
* or whose owner was proven gone on both passes and is still in
* progress (I2: "settled within one reconciler pass").
* I3, I4, I7 one more pass with the clock moved past every grace window
* (accounting closure 10 min, next action 5 min). The tasks are at
* rest, so anything still waiting then would wait forever.
* I6 run-log proxy: a run that failed on a stale-generation event.
* Since #19960 an earlier generation's event is history and never
* fails the current turn (runner code `stale_generation_event`).
* I8 run-log check: every `run.performance.budget_exceeded` event the
* speed budgets wrote (TTFT, agent boot, restart recovery; #19863).
* I5 not measured: see I5_GAP. R3 (one Retry at most) bounds it.
*
* I6 and I8 are company-wide scans keyed by run or event id, so the per-point
* baseline diff in main.ts charges each one to the point that produced it.
*/
import { createDb, type Db } from "../../packages/db/src/index.js";
import {
createOwnershipReportState,
runOwnershipReconciliationPass,
type InvariantViolation,
} from "../../server/src/services/recovery/ownership-invariant-report.js";
export type PlanInvariant = "I1" | "I2" | "I3" | "I4" | "I5" | "I6" | "I7" | "I8";
export type SuiteRule = InvariantViolation["rule"] | "I6_generation_fencing" | "I8_fast_turns";
/** A violation with the state of its record and run, so a failure is diagnosable after the instance is gone. */
export type EvidencedViolation = Omit<InvariantViolation, "rule"> & { rule: SuiteRule; evidence?: Record<string, unknown> };
/**
* Why I5 (work-based budgets) is not asserted. A charge is decided per restart
* claim from the attempt's event window (provider-attempt-outcome.ts, #19948)
* and recorded only indirectly in the finalization's bounded recovery
* history (progressAttempt, attemptKeptForProgress). Asserting it needs either
* an explicit per-claim charge record or reading that history per run. The
* cheap check that exists is R3, and the pre-spawn and pre-accept points
* (native.process_start.*, runner.process.*, runner.turn_start.*) recover
* without a Retry today.
*/
export const I5_GAP = "Charge decisions are not recorded per restart claim; needs an explicit charge record (section F follow-up). "
+ "R3 bounds it: no point needed a Retry.";
export interface InvariantCheck {
violations: EvidencedViolation[];
byInvariant: Partial<Record<PlanInvariant, number>>;
inProgress: Record<string, { inProgress: number; gone: number; alive: number; unprovable: number }>;
notMeasured: Partial<Record<PlanInvariant, string>>;
errors: string[];
}
/** Grace windows the shifted pass must exceed (ownership-invariant-report.ts). */
export const GRACE_SHIFT_MS = 15 * 60_000;
export const invariantOf = (violation: Pick<EvidencedViolation, "rule">): PlanInvariant => violation.rule.slice(0, 2) as PlanInvariant;
export function summarizeViolations(violations: readonly Pick<EvidencedViolation, "rule">[]): Partial<Record<PlanInvariant, number>> {
const counts: Partial<Record<PlanInvariant, number>> = {};
for (const violation of violations) counts[invariantOf(violation)] = (counts[invariantOf(violation)] ?? 0) + 1;
return counts;
}
/**
* Local-disk kinds (usage-receipt and orphan-cleanup spools) resolve their
* directories from the environment when listed. Point them at the wave's
* instance, not the operator's, for the duration of the check.
*/
async function withWaveInstance<T>(instance: { paperclipHome: string; instanceId: string }, run: () => Promise<T>): Promise<T> {
const keys = ["PAPERCLIP_HOME", "PAPERCLIP_INSTANCE_ID", "SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR"] as const;
const saved = Object.fromEntries(keys.map(key => [key, process.env[key]]));
process.env.PAPERCLIP_HOME = instance.paperclipHome;
process.env.PAPERCLIP_INSTANCE_ID = instance.instanceId;
delete process.env.SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR;
try { return await run(); } finally {
for (const key of keys) {
if (saved[key] === undefined) delete process.env[key]; else process.env[key] = saved[key];
}
}
}
const clip = (value: unknown) => typeof value === "string" ? value.slice(0, 300) : value ?? null;
type Row = Record<string, unknown>;
const text = (value: unknown) => (typeof value === "string" ? value : "");
/** I6 and I8 from the run log of `companyId` (all companies when null). */
export async function runLogViolations(db: Db, companyId: string | null): Promise<EvidencedViolation[]> {
const breaches = await db.$client.unsafe(
`select e.id::text as id, e.company_id::text as "companyId", e.run_id::text as "runId", r.issue_id::text as "issueId", e.payload
from heartbeat_run_events e join heartbeat_runs r on r.id = e.run_id
where e.event_type = 'run.performance.budget_exceeded' and ($1::text is null or e.company_id::text = $1)`, [companyId]) as Row[];
const stale = await db.$client.unsafe(
`select id::text as id, company_id::text as "companyId", issue_id::text as "issueId", status, error_code as "errorCode", error
from heartbeat_runs
where status in ('failed', 'timed_out', 'interrupted')
and (coalesce(error_code, '') ~* 'generation' or coalesce(error, '') ~* 'stale_generation|earlier generation')
and ($1::text is null or company_id::text = $1)`, [companyId]) as Row[];
return [
...breaches.map(row => {
const payload = (row.payload ?? {}) as Record<string, unknown>;
return { rule: "I8_fast_turns" as const, kind: "speed_budget", recordId: text(row.id), companyId: text(row.companyId) || null,
runId: text(row.runId) || null, issueId: text(row.issueId) || null, reason: `${text(payload.metric) || "unknown"}_over_p95`,
evidence: { budget: { metric: payload.metric, measuredMs: payload.measuredMs, budgetP95Ms: payload.budgetP95Ms,
adapter: payload.adapter, startKind: payload.startKind } } };
}),
...stale.map(row => ({ rule: "I6_generation_fencing" as const, kind: "run", recordId: text(row.id),
companyId: text(row.companyId) || null, runId: text(row.id), issueId: text(row.issueId) || null,
reason: "run_failed_on_earlier_generation_event" })),
];
}
async function withEvidence(db: Db, violations: EvidencedViolation[]): Promise<EvidencedViolation[]> {
if (!violations.length) return violations;
const wakeIds = violations.filter(violation => violation.kind === "wake_request" || violation.kind === "wake_request_claimed")
.map(violation => violation.recordId);
const runIds = [...new Set(violations.flatMap(violation => violation.runId ? [violation.runId] : []))];
const wakes = (wakeIds.length ? await db.$client.unsafe(
"select id::text, status, reason, error, run_id::text as \"runId\" from agent_wakeup_requests where id::text = any($1)", [wakeIds]) : []) as Row[];
const runs = (runIds.length ? await db.$client.unsafe(
"select id::text, status, error_code as \"errorCode\", error from heartbeat_runs where id::text = any($1)", [runIds]) : []) as Row[];
const wakeById = new Map(wakes.map(wake => [wake.id, wake]));
const runById = new Map(runs.map(run => [run.id, run]));
return violations.map(violation => {
const wake = wakeById.get(violation.recordId);
const run = violation.runId ? runById.get(violation.runId) : undefined;
const evidence = {
...(wake ? { wake: { status: wake.status, reason: clip(wake.reason), error: clip(wake.error), runId: wake.runId } } : {}),
...(run ? { run: { status: run.status, errorCode: run.errorCode, error: clip(run.error) } } : {}),
};
return Object.keys(evidence).length ? { ...violation, evidence } : violation;
});
}
export async function checkPlanInvariants(input: {
connectionString: string; companyId: string | null; paperclipHome: string; instanceId: string; now?: Date;
}): Promise<InvariantCheck> {
const db = createDb(input.connectionString);
const errors: string[] = [];
try {
const now = input.now ?? new Date();
const pass = (state: ReturnType<typeof createOwnershipReportState>, at: Date) =>
withWaveInstance(input, () => runOwnershipReconciliationPass(db, { state, now: at, record: false }));
const state = createOwnershipReportState();
// I2 needs the same record proven gone on both passes: a kind that failed
// to list on the first pass has only one proof, so report it as incomplete.
const first = await pass(state, now);
for (const kind of first.kinds) if (kind.error) errors.push(`${kind.kind} (first I1/I2 pass): ${kind.error}`);
if (first.retryNeeded) errors.push("the first I1/I2 pass did not finish (retryNeeded)");
const second = await pass(state, new Date(now.getTime() + 1_000));
// A failed I3/I4/I7 query is only logged by the pass and sets retryNeeded.
// Retry once; a pass that still could not finish is an incomplete check.
let shifted = await pass(createOwnershipReportState(), new Date(now.getTime() + GRACE_SHIFT_MS));
if (shifted.retryNeeded) shifted = await pass(createOwnershipReportState(), new Date(now.getTime() + GRACE_SHIFT_MS));
for (const kind of [...second.kinds, ...shifted.kinds]) if (kind.error) errors.push(`${kind.kind}: ${kind.error}`);
if (second.retryNeeded) errors.push("the I1/I2 pass did not finish (retryNeeded)");
if (shifted.retryNeeded) errors.push("the I3/I4/I7 pass did not finish after one retry (retryNeeded)");
const ownCompany = (violation: InvariantViolation) => input.companyId === null || violation.companyId === null
|| violation.companyId === input.companyId;
const fromClock = second.violations.filter(violation => violation.rule === "I1_owned" || violation.rule === "I2_settled");
const fromShift = shifted.violations.filter(violation => violation.rule !== "I1_owned" && violation.rule !== "I2_settled");
let runLog: EvidencedViolation[] = [];
try { runLog = await runLogViolations(db, input.companyId); } catch (error) {
errors.push(`I6/I8 run-log check: ${error instanceof Error ? error.message : String(error)}`);
}
const violations = await withEvidence(db, [...fromClock, ...fromShift].filter(ownCompany));
violations.push(...runLog);
const inProgress = Object.fromEntries(second.kinds.filter(kind => kind.inProgress > 0)
.map(kind => [kind.kind, { inProgress: kind.inProgress, ...kind.verdicts }]));
return {
violations, byInvariant: summarizeViolations(violations), inProgress, errors,
notMeasured: { I5: I5_GAP },
};
} finally {
await db.$client.end({ timeout: 5 }).catch(() => undefined);
}
}
/**
* U3 evidence from the wave database (universal.ts): every failed run's error
* text and every recovery action's cause, so a bare "Error" or an empty
* message is caught even where the board's run list hides the text. Read once
* at wave end, before the instance is removed; grouped by issue.
*/
export async function readUniversalDbEvidence(db: Db, companyId: string): Promise<Map<string, import("./universal.js").UniversalDbEvidence>> {
const runs = await db.$client.unsafe(
`select id::text as id, coalesce(context_snapshot->>'issueId', '') as "issueId", left(error, 400) as error
from heartbeat_runs where company_id::text = $1 and status in ('failed', 'timed_out')`, [companyId]) as Row[];
const actions = await db.$client.unsafe(
`select id::text as id, source_issue_id::text as "issueId", kind, left(cause, 400) as cause, left(next_action, 400) as "nextAction"
from issue_recovery_actions where company_id::text = $1`, [companyId]) as Row[];
const byIssue = new Map<string, { runMessages: Map<string, string | null>; recoveryActions: Array<{ id: string; kind: string; cause: string | null; nextAction: string | null }> }>();
const entry = (issueId: string) => {
let value = byIssue.get(issueId);
if (!value) byIssue.set(issueId, value = { runMessages: new Map(), recoveryActions: [] });
return value;
};
// A run is matched to its task by id in the grader, so runs without an issue id are kept under "".
for (const run of runs) entry(text(run.issueId)).runMessages.set(text(run.id), typeof run.error === "string" ? run.error : null);
for (const action of actions) entry(text(action.issueId)).recoveryActions.push({ id: text(action.id), kind: text(action.kind),
cause: typeof action.cause === "string" ? action.cause : null, nextAction: typeof action.nextAction === "string" ? action.nextAction : null });
return byIssue;
}