Files
PaperClipAI/tests/restart-chaos/contention-db.test.ts
DottaandClaude 400bb1f0f9 test(restart-chaos): one-row db pressure, bound accepted-Retry waits in U1, live L1 results (#20472)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The restart chaos harness grades real agent tasks on an isolated
control plane.
> - #20421 added the L1 contention workload, `--db-pressure`, and the
universal checks U1–U4.
> - The first live L1 waves showed two harness gaps and one missed
product shape.
> - The pressure writers locked several run rows per statement and
deadlocked with product transactions. A real stream does not do that.
> - U1 counted an accepted Retry that waits on the system as a live
owner forever. Ten tasks sat 8 minutes in that state with no run.
> - This pull request fixes both gaps, adds the owed direct test for
`collectContentionEvidence`, and records the live wave results.

## Linked Issues or Issue Description

Refs #20421, #20385.

**What happened?**

The live L1 waves (`w-20261110T040531-s20385` on the #20385 parent,
`w-20261110T044338-s20385` and `w-20261110T050818-s20386` on master)
produced harness deadlocks (40P01) from multi-row pressure statements.
U1 passed tasks whose accepted Retry waited on
`process_identity_missing` for 16 minutes without a run.

**Expected behavior**

Pressure writers behave like a run-log stream (one row per statement).
U1 flags an accepted Retry that waits on the system past the queue
bound.

**Steps to reproduce**

Run `node cli/node_modules/tsx/dist/cli.mjs
tests/restart-chaos/universal-audit.ts <results dirs>` over the saved
waves, or the L1 wave command in the README.

## What Changed

- `contention.ts`: each pressure statement updates one running run row.
The old statement updated every running row at once and deadlocked with
product transactions.
- `universal.ts` (U1): an accepted Retry that waits on the system
(`retryWait`) is an owner only for the queue bound (5 min of
server-ready time). While it waits, the Retry button, failed notice and
blocker do not count as actionable items, because the person already
acted. A scheduled retry is still a timer.
- `contention-db.test.ts`: a real PostgreSQL test for
`collectContentionEvidence` (receipt count, duplicate producer events,
terminal receipt, accounting fields, company scope).
- README: live wave results table, updated audit numbers and the U1
rule.

## Verification

- `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts`:
28 files, 345 tests pass.
- `node scripts/typecheck-test-projects.mjs tests/restart-chaos`:
passes.
- Audit over 79 saved waves (1,620 tasks, 1,483 passing): U1 17 flags,
none on a passing task or an all-pass wave. The longest accepted-Retry
wait on a passing task was 278 s. U2 1, U3 30 (3 on passing tasks,
warning only), U4 0.
- Live waves (codex and claude, `--workloads L1 --faults K1
--concurrency 4 --tasks 4 --db-pressure 4`):
- `w-20261110T040531-s20385`, #20385 parent: 117 receipt-write
serialization failures (40001) in the server log; 1 of 4 tasks passed.
Three runs failed `adapter_failed` after 40001 exhausted in
`createRunUsageRecorder`, `reserveRunBudget` and native finalization.
- `w-20261110T044338-s20385`, master `8004ad069e` with the harness: 2
serialization failures; 1 of 4 passed. Failures included 40001 in
`createRunUsageRecorder` and deadlocks caused by the old multi-row
writers (fixed here).
- `w-20261110T050818-s20386`, same build with one-row writers: 0 of 4
passed. Every first run failed in `reserveRunBudget` before spawn, and
every accepted Retry then waited on `process_identity_missing` without
starting a run.
- No wave reached the runner's commit stall, so none showed
`native_event_replay_conflict`.

## Risks

- U1 can now fail a task whose accepted Retry waits more than 8 minutes.
No passing task in 79 saved waves came close (longest 278 s).
- One-row writers produce fewer statements per second than the multi-row
statement did; `contention-db.test.ts` still reproduces the #20385
receipt race with them.
- Test-only change; no product code.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, 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-10 00:22:07 -06:00

112 lines
7.0 KiB
TypeScript

/**
* Harness-level check that `--db-pressure` reproduces the #20385 race against
* real PostgreSQL: under the pressure writers, a usage receipt written with the
* pre-#20385 repeatable-read transaction exhausts its retries with 40001,
* while the current READ COMMITTED writer (`persistUsageReceipt`) commits.
*/
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, heartbeatRuns, type Db } from "../../packages/db/src/index.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../server/src/__tests__/helpers/embedded-postgres.js";
import { withOperationAccountingTransaction } from "../../server/src/services/accounting-transaction.js";
import { persistUsageReceipt, persistUsageReceiptInTransaction, type UsageReceiptEnvelope } from "../../server/src/services/usage-receipts.js";
import { collectContentionEvidence, RunRowPressure } from "./contention.js";
const support = await getEmbeddedPostgresTestSupport();
const RECEIPTS = 8;
describe.skipIf(!support.supported)("--db-pressure against real PostgreSQL (#20385)", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("restart-chaos-contention-");
db = createDb(database.connectionString);
}, 120_000);
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
async function runningRun() {
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), sourceId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Contention fixture", issuePrefix: companyId.slice(0, 8) });
await db.insert(agents).values({ id: agentId, companyId, name: "Contention agent", adapterType: "process", status: "active" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running",
usageJson: { accountingReceiptSourceId: sourceId, accountingReceiptSequence: 0 } });
const receipt = (sequence: number): UsageReceiptEnvelope => ({ schema: "paperclip/accounting-receipt/v1",
id: randomUUID(), companyId, runId, sourceId, sequence, receivedAt: new Date().toISOString(), adapterType: "process",
receipt: { complete: false, usageBasis: "per_run", costUsd: sequence / 100, billingType: "metered_api" } });
return { companyId, runId, receipt };
}
async function underPressure<T>(companyId: string, work: () => Promise<T>) {
const pressure = new RunRowPressure(database.connectionString, companyId, 4).start();
// Let the writers reach steady state.
while (pressure.stats.rowsTouched < 50) await new Promise(resolve => setTimeout(resolve, 10));
try { return await work(); } finally {
const stats = await pressure.stop();
expect(stats.errors).toBe(0);
}
}
it("makes the pre-#20385 repeatable-read receipt writer exhaust its retries with 40001", async () => {
const f = await runningRun();
const outcomes = await underPressure(f.companyId, async () => {
const results: string[] = [];
for (let sequence = 1; sequence <= RECEIPTS; sequence += 1) {
// The pre-#20385 persistUsageReceipt: the same work in the default repeatable-read transaction.
results.push(await withOperationAccountingTransaction(db, f.companyId, tx => persistUsageReceiptInTransaction(tx, f.receipt(sequence)))
.then(() => "committed", (error: { code?: string; cause?: { code?: string } }) => error.code ?? error.cause?.code ?? "error"));
}
return results;
});
// Locally every one exhausts (8/8); at least half leaves room for a slow CI host.
expect(outcomes.filter(outcome => outcome === "40001").length).toBeGreaterThanOrEqual(RECEIPTS / 2);
}, 60_000);
it("commits every receipt with the current READ COMMITTED writer", async () => {
const f = await runningRun();
await underPressure(f.companyId, async () => {
for (let sequence = 1; sequence <= RECEIPTS; sequence += 1) await persistUsageReceipt(db, f.receipt(sequence));
});
const [row] = await db.$client.unsafe("select count(*)::int as n from run_usage_receipts where run_id = $1", [f.runId]) as Array<{ n: number }>;
expect(row?.n).toBe(RECEIPTS);
}, 60_000);
it("reads a task's accounting evidence from the wave database", async () => {
const f = await runningRun();
const sourceId = randomUUID();
const journal = (sequence: number, sourceEventId: string, eventType: string) => db.$client.unsafe(
`insert into run_usage_receipts (id, company_id, run_id, source_id, sequence, receipt_hash, receipt_json, complete, received_at)
values ($1, $2, $3, $4, $5, $6, $7::jsonb, false, now())`,
[randomUUID(), f.companyId, f.runId, sourceId, sequence, `hash-${sequence}`,
JSON.stringify({ producerEvent: { sourceEventId, eventType } })]);
await journal(1, "evt-1", "turn.started");
await journal(2, "evt-2", "usage.reported");
// The same producer event journaled twice for one source: the oracle's exactly-once check must see it.
await journal(3, "evt-2", "usage.reported");
await journal(4, "evt-3", "turn.completed");
await db.$client.unsafe(
`update heartbeat_runs set status = 'succeeded', error_code = null, log_bytes = 4096, cost_accounted_at = now(),
usage_json = usage_json || '{"accountingReceiptOwner":"native_producer","costUsd":0.25}'::jsonb where id = $1`, [f.runId]);
// Agent cost events name their agent; `agentOf` is the run whose agent is charged.
const cost = (companyId: string, runId: string | null, agentOf: string, cents: number) => db.$client.unsafe(
`insert into cost_events (company_id, agent_id, heartbeat_run_id, provider, model, cost_cents, occurred_at)
values ($1, (select agent_id from heartbeat_runs where id = $3), $2, 'openai', 'test-model', $4, now())`,
[companyId, runId, agentOf, cents]);
await cost(f.companyId, f.runId, f.runId, 10);
await cost(f.companyId, f.runId, f.runId, 15);
// A cost of the same company outside this run counts toward the company total only.
await cost(f.companyId, null, f.runId, 5);
// Another company's cost counts toward neither.
const elsewhere = await runningRun();
await cost(elsewhere.companyId, elsewhere.runId, elsewhere.runId, 1000);
const evidence = await collectContentionEvidence(db, f.companyId, [f.runId], { spendCents: 30, pendingRunCount: 0 });
expect(evidence.error).toBeNull();
expect(evidence.runs).toHaveLength(1);
expect(evidence.runs[0]).toMatchObject({ id: f.runId, status: "succeeded", receipts: 4, duplicateReceipts: [`${sourceId}:evt-2`],
terminalReceipt: true, nativeProducer: true, costAccounted: true, recordedCostCents: 25, costEventCents: 25, logBytes: 4096, logEvents: 0 });
expect(evidence.companyCostEventCents).toBe(30);
// A run of another company is never read, even when its id is passed.
const other = await runningRun();
expect((await collectContentionEvidence(db, f.companyId, [other.runId], null)).runs).toEqual([]);
}, 60_000);
});