Files
PaperClipAI/server/src/__tests__/closed-native-receipt-accounting.test.ts
T
DottaandClaude Opus 5.5 4938a930d6 fix(budgets): stop pending or restart-lost accounting from hard-stopping companies (#19497)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Budget admission and run accounting decide whether any task in a
company may start
> - A control-plane restart that kills a provider turn mid-flight can
lose that turn's final usage receipt. ACPX Claude reports usage only at
turn end, so the receipt never becomes complete
> - Accounting kept such a run "awaiting receipt" forever. Every later
admission in the company then refused with "completed runs await
accounting", and the budget evaluator opened a hard-stop incident that
paused the company. No product action could clear it: raising the budget
refuses while runs await accounting, accounting retry finds no new data,
and allowing unpriced usage does not apply to pending runs
> - Restart chaos waves showed this as a dead task Retry, a new task
blocked as "over budget" at 22 of 500 cents, and a hard stop that
cancelled queued Retries and an unrelated running task
> - This pull request closes the debt from evidence: once native
recovery reaches terminal failure and the provider stop is verified, the
known part settles as an unpriced charge. Until then the run holds new
work as recovering accounting, without a hard stop
> - The benefit is that a restart no longer bricks a company with a hard
budget. The operator's unpriced-usage policy decides admission, and
unknown spend still never shows as zero cost

## Linked Issues or Issue Description

Refs #19399, #19426, #19431 (earlier restart Retry fixes; this is the
budget layer under the same journey).

**What happened?**
After a control-plane SIGKILL during an ACPX Claude turn, the killed run
ended `native_provider_terminal_failed` with
`usage_json.accountingReceiptReady = false` and `cost_accounting_pending
= true`. It stayed that way for good. The task Retry was accepted but
parked with `budget.blocked` ("Company cannot start work while completed
runs await accounting"), which the UI showed as "Retry is waiting for
execution checks". A new Codex task was escalated to `blocked` with "the
original recovery target is over budget" while the company had spent 22
of 500 cents. After the next restart the budget evaluator opened a
hard-stop incident (`amount_observed` 22.08 < 500), paused the company
and cancelled both queued Retries.

**What did you expect?**
A restart should not stop the company. Unknown usage from a stopped
provider should become an honest, operator-governed state, and Retry
should start a run.

**Steps to reproduce**
1. Give a company a hard-stop budget.
2. Start an ACPX Claude task and SIGKILL the control plane mid-turn, so
the resumed turn fails.
3. Observe the run stay `cost_accounting_pending` with an incomplete
receipt, and every new admission refuse.

## What Changed

- `budgets.ts`: completed runs that await accounting now hold new work
only. They no longer open a hard-stop incident, pause the company, place
an agent budget hold, or deliver Stop to running work. Only spend at the
limit, or unpriced usage under a blocking policy, does that. Chaos wave
A and a pre-restart lifecycle cell showed the wedge: a run that had just
succeeded stayed terminal for about 100 ms before its charge committed,
the evaluator paused the company in that gap, and the Stop it delivered
left a cancelled run whose receipt never closed.
- `run-cost-accounting.ts`: a failed native run is a closed receipt
source only with positive stop evidence: its finalization is
`terminal_failure` with no result (not a finalization-deadline failure),
it no longer records a process identity, and its latest server-authored
process event is `native.local_process_stopped`. One SQL predicate
serves the reconciler scan and settlement. Accounting now settles its
known part as an `unpriced` charge instead of waiting forever. The
background reconciler selects these runs. The reservation settles. Other
incomplete receipts stay pending as before. A cancelled run keeps its
existing accounting drain, so Stop recovery can still deliver its final
receipt.
- `native-local-process-stop.ts` and its transactional callers:
releasing a verified local or remote process stop wakes the accounting
worker, so the closed debt settles promptly.
- `usage-receipts.ts`: a charge settled without its receipt is marked
`accountingReceiptUnavailable`. A later complete receipt that carries
its own price (including a rate-card price) corrects it. A receipt with
no own price and unchanged usage does not reopen the hold.
- `budget-exposure.ts`: the blocking unpriced-usage policy no longer
counts a charge settled from a lost receipt with no observed usage. That
is unknown, not "usage with no reliable price". Complete receipts that
report no tokens (for example Cursor Cloud) still count. A live wave
under the default policy hard-stopped its company at 0 of 500 cents on
one such charge.
- `budget-exposure.ts`: a terminal-failure native run with an
incomplete, not capture-failed receipt counts as recovering accounting.
Admission holds new work ("New work must wait while a native run
recovers its unfinished accounting") without a hard-stop incident, a
company pause or cancellation of running work.
- `recovery/service.ts`: the stranded-work comment names the actual
budget gate instead of always saying "over budget".
- `task-interruption-presentation.ts`: a Retry parked by
`budget.blocked` says it waits for the budget, not for "execution
checks".
- `doc/SPEC-implementation.md`: documents the closed-receipt contract
next to the existing incomplete-receipt rule.

## Verification

- New embedded-Postgres suite
`server/src/__tests__/closed-native-receipt-accounting.test.ts`, built
from the persisted shape of the killed run:
- Red before the fix: the run stayed pending, `reconcileRunCosts`
accounted 0, and admission refused with "completed runs await
accounting".
- Debt stays pending with no verified stop event, with a
finalization-deadline failure, with a recorded process identity, and
while the coordinator can still produce a result.
- Under a blocking policy, a lost receipt with no usage does not
hard-stop; one with tokens still blocks. A run with a still-recorded
process identity paused the company with a hard-stop incident.
- Green after: the stopped run settles as one `unpriced` charge with the
reservation settled; admission is clear under an `allow` policy and
names "no reliable price" under `block`; a run with a recorded process
identity or a non-terminal coordinator stays pending; the closing window
holds admission without an incident or pause; a final receipt that
arrives later still enters late-receipt reconciliation.
- Pending accounting from a run that just finished holds admission with
no incident, no pause, no enforcement version bump, and an unrelated
running run stays running. Red before the `budgets.ts` change: the
company was paused.
- A later priced receipt corrects the unavailable charge to its price;
an unpriced one leaves it settled.
- `task-interruption-presentation.test.ts`: the `budget.blocked` Retry
wait message.
- `budget-enforcement-scoping.test.ts`: the accounting-hold release
cases now assert that pending accounting places no budget hold and that
admission clears after settlement.
- Existing suites pass locally: all budget suites (control publication,
enforcement scoping, enforcement worker, evaluation work, live attempts,
history, service, live usage, budget cancellation),
native-stop-accounting, explicit-native-continuation,
native-case-handoff, cost-data-quality, heartbeat-cost-accounting,
run-cost-accounting, native-usage-delivery. Server typecheck passes.
- Runner e2e cell
`lifecycle-baseline.runner-codex.local.lifecycle-dependency-restart-neutral`,
which failed on master with a false agent budget hold before any
restart, passes on this branch.
- Live restart-chaos wave (local runner, K1 SIGKILL, codex + 2× ACPX
Claude + OpenCode, 4 restarts, company policy `unpricedUsagePolicy:
allow`) with the accounting fix: every killed run settled (no
`cost_accounting_pending` left), the company stayed active, the OpenCode
Retry completed the task on the first click and the Codex Retry finished
its task. That wave also exposed a 1-second false hard stop in the
closing window (observed 0 of 500 cents) that cancelled the running
OpenCode turn; the `budget-exposure.ts` change fixes it and has its own
red/green test.
- Confirming live wave with both commits, same plan (2× ACPX Claude,
OpenCode, Codex; 4 K1 restarts): both Claude tasks passed R3 (one Retry
click started a run that completed the task), OpenCode passed R1
(continued by itself), and the Codex Retry completed its task. Zero
budget incidents, zero cancelled runs, zero runs left pending
accounting, company active; three killed runs recorded as `unpriced`
charges. The only open signature is an unrelated workspace-durability
check (`R2:pre_fault_files_lost` on the Codex long-bench task).

## Risks

- Behavior change: a stopped native run's lost receipt now becomes an
`unpriced` ledger charge with its known usage. If that usage has tokens,
the default `block` policy still stops new work with "recorded usage has
no reliable price". If it has none, the charge is visible in Costs but
does not stop the company. Other unpriced charges keep their existing
effect. Unknown spend is never recorded as a priced receipt. Budget
enforcement stays best effort, as the spec says; killed OpenCode and
Codex requests already lose their in-flight usage.
- Remote runs and runs without a verified local stop keep their debt
pending (an admission hold only, no hard stop).
- Contract change: pending accounting no longer pauses a scope or stops
running work. New work still waits with "completed runs await
accounting". A scope's real hard stop (spend at the limit, or blocked
unpriced usage) is unchanged.
- If a provider stop can never be verified, the run stays "recovering
accounting": new work waits without a hard-stop incident. Before, the
same state paused the company. The hold is visible in admission errors
and Costs.
- A receipt that arrives after settlement posts a late correction. The
original unpriced charge stays in the ledger.
- No schema or migration change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file editing, embedded Postgres tests, live
restart-chaos harness).

## 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>
2026-11-06 14:27:51 -06:00

285 lines
18 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
agents, budgetIncidents, budgetPolicies, budgetReservations, companies, costEvents, createDb, heartbeatRunEvents, heartbeatRuns, issues,
nativeRunFinalizations, type Db,
} from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { budgetService, flushBudgetEvaluationWork } from "../services/budgets.js";
import { accountRunCost, reconcileRunCosts } from "../services/run-cost-accounting.js";
import { persistUsageReceipt } from "../services/usage-receipts.js";
// A control-plane SIGKILL during a provider turn that reports usage only at
// turn end leaves the run terminal with an incomplete receipt. Once native
// recovery has given up and verified the provider process stopped, no producer
// can deliver that receipt. The debt must leave "awaiting receipt" or every
// later admission in the company refuses forever, whatever the budget allows.
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("closed native receipt accounting", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("closed-native-receipt-");
db = createDb(database.connectionString);
}, 60_000);
afterEach(async () => { await db.transaction(async tx => {
await tx.execute(sql`SET LOCAL client_min_messages = warning`);
await tx.execute(sql`TRUNCATE companies CASCADE`);
}); });
afterAll(async () => { await database?.cleanup(); });
async function fixture(options: {
unpricedUsagePolicy?: "block" | "allow";
phase?: string;
processPid?: number | null;
stopEvidence?: boolean;
failureCode?: string;
} = {}) {
const companyId = randomUUID(), agentId = randomUUID(), otherAgentId = randomUUID(), sourceId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Chaos Lab", issuePrefix: "CHA" });
await db.insert(agents).values([
{ id: agentId, companyId, name: "Claude", role: "engineer", status: "idle", adapterType: "paperclip_runner" },
{ id: otherAgentId, companyId, name: "Codex", role: "engineer", status: "idle", adapterType: "paperclip_runner" },
]);
const [policy] = await db.insert(budgetPolicies).values({ companyId, scopeType: "company", scopeId: companyId,
metric: "billed_cents", windowKind: "calendar_month_utc", amount: 500, notifyEnabled: false,
unpricedUsagePolicy: options.unpricedUsagePolicy ?? "allow" }).returning();
const [issue] = await db.insert(issues).values({ companyId, title: "Interrupted task", status: "blocked",
assigneeAgentId: agentId }).returning();
// The shape persisted for the killed ACPX Claude run: the final provider
// turn failed without a per-turn usage report, so the receipt never closed.
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, invocationSource: "automation",
scopeKind: "issue", issueId: issue.id, nativeIssueId: issue.id, runtimeMode: "native", status: "failed",
errorCode: "native_provider_terminal_failed", finishedAt: new Date(), costAccountingPending: true,
processPid: options.processPid ?? null, processGroupId: options.processPid ?? null,
processStartedAt: options.processPid ? new Date() : null,
usageJson: { accountingReceiptOwner: "native_producer", accountingReceiptSourceId: sourceId,
accountingReceiptSequence: 1, accountingReceiptReady: false, provider: "anthropic", biller: "anthropic",
model: "claude-sonnet-5", billingType: "metered_api", costStatus: "unpriced", costUsd: null,
inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, cacheWriteTokens: 0, usageSource: "per_run",
budgetExposure: { sourceId, sequence: 1, costCents: "0.0000000" },
ledgerScope: { issueId: issue.id, projectId: null, billingCode: null } } }).returning();
await db.insert(nativeRunFinalizations).values({ companyId, issueId: issue.id, runId: run.id,
phase: options.phase ?? "terminal_failure", attempt: 3, failureCode: options.failureCode ?? "native_provider_terminal_failed" });
// Server-authored process trail: launch, recorded identity, then the
// verified local stop recovery writes before clearing the identity.
await db.insert(heartbeatRunEvents).values([
{ companyId, runId: run.id, agentId, seq: 1, eventType: "native.process_start_requested", stream: "system" },
{ companyId, runId: run.id, agentId, seq: 2, eventType: "native.process_identity_recorded", stream: "system" },
...(options.stopEvidence === false ? [] : [
{ companyId, runId: run.id, agentId, seq: 3, eventType: "native.local_process_stopped", stream: "system" }]),
]);
await db.insert(budgetReservations).values({ companyId, runId: run.id, agentId, amountCents: "0",
state: "held", providerStartedAt: new Date() });
const readRun = async () => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0];
const charges = () => db.select().from(costEvents).where(and(eq(costEvents.companyId, companyId),
eq(costEvents.heartbeatRunId, run.id)));
const reservation = async () => (await db.select().from(budgetReservations)
.where(eq(budgetReservations.runId, run.id)))[0];
const block = () => budgetService(db).getInvocationBlock(companyId, otherAgentId, { issueId: null, projectId: null });
return { companyId, agentId, otherAgentId, sourceId, policy, issue, run, readRun, charges, reservation, block };
}
it("settles a stopped native terminal failure without a final receipt as unpriced usage", async () => {
const f = await fixture();
expect(await f.block()).toMatchObject({ reason: "New work must wait while a native run recovers its unfinished accounting." });
// The background reconciler must select this debt; it is not merely retryable by hand.
expect(await reconcileRunCosts(db)).toMatchObject({ accounted: 1 });
await flushBudgetEvaluationWork(db);
const settled = await f.readRun();
expect(settled.costAccountingPending).toBe(false);
expect(settled.costAccountedAt).not.toBeNull();
const charges = await f.charges();
expect(charges).toHaveLength(1);
// Unknown spend is never presented as a zero-cost receipt.
expect(charges[0]).toMatchObject({ costStatus: "unpriced", model: "claude-sonnet-5", provider: "anthropic" });
expect((await f.reservation()).state).toBe("settled");
// The operator's unpriced-usage policy now decides admission.
expect(await f.block()).toBeNull();
});
// Chaos wave: under the default blocking policy, a lost zero-token receipt
// opened a hard stop at 0 of 500 cents and blocked every task.
it("does not hard-stop a blocking policy for a lost receipt with no usage", async () => {
const f = await fixture({ unpricedUsagePolicy: "block" });
expect(await accountRunCost(db, f.run.id)).toBe(true);
await budgetService(db).evaluateAffectedScopes(f.companyId, f.agentId, null);
await flushBudgetEvaluationWork(db);
expect(await f.charges()).toMatchObject([{ costStatus: "unpriced" }]);
const [company] = await db.select().from(companies).where(eq(companies.id, f.companyId));
expect(company).toMatchObject({ status: "active", pauseReason: null });
expect(await f.block()).toBeNull();
});
it("keeps a blocking policy for lost-receipt usage that has tokens but no price", async () => {
const f = await fixture({ unpricedUsagePolicy: "block" });
await db.update(heartbeatRuns).set({ usageJson: sql`${heartbeatRuns.usageJson} || '{"inputTokens":1200,"outputTokens":80}'::jsonb` })
.where(eq(heartbeatRuns.id, f.run.id));
expect(await accountRunCost(db, f.run.id)).toBe(true);
await flushBudgetEvaluationWork(db);
expect((await f.block())?.reason).toMatch(/no reliable price|budget hard-stop/);
});
it("keeps the debt pending while the provider process identity is still recorded", async () => {
const f = await fixture({ processPid: 424242 });
expect(await reconcileRunCosts(db)).toMatchObject({ accounted: 0 });
expect(await accountRunCost(db, f.run.id)).toBe(false);
expect((await f.readRun()).costAccountingPending).toBe(true);
expect(await f.charges()).toHaveLength(0);
expect((await f.reservation()).state).toBe("held");
});
// Between a native terminal failure and the verified provider stop, the debt
// is closing, not over budget. A hard stop here paused the company and
// cancelled an unrelated running task in the live restart wave.
it("holds new work without a hard stop while a terminal native receipt is closing", async () => {
const f = await fixture({ processPid: 424242 });
await budgetService(db).evaluateAffectedScopes(f.companyId, f.agentId, null);
await flushBudgetEvaluationWork(db);
const [company] = await db.select().from(companies).where(eq(companies.id, f.companyId));
expect(company.status).toBe("active");
expect(company.pauseReason).toBeNull();
expect(await db.select().from(budgetIncidents).where(eq(budgetIncidents.companyId, f.companyId))).toHaveLength(0);
expect(await f.block()).toMatchObject({ reason: "New work must wait while a native run recovers its unfinished accounting." });
});
// Chaos waves: a run that had just succeeded was terminal for ~100 ms before
// its charge committed. The evaluator read that gap as a hard stop, paused the
// company and cancelled unrelated running work, which then never settled.
it("holds admission without a hard stop while a finished run's charge commits", async () => {
const f = await fixture();
await db.update(heartbeatRuns).set({ status: "succeeded", errorCode: null,
usageJson: sql`${heartbeatRuns.usageJson} || '{"accountingReceiptReady":true,"costUsd":0.1}'::jsonb` })
.where(eq(heartbeatRuns.id, f.run.id));
// Its coordinator already applied the result, so nothing counts it as recovering.
await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.run.id));
const runningId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runningId, companyId: f.companyId, agentId: f.otherAgentId,
invocationSource: "assignment", status: "running" });
await budgetService(db).evaluateAffectedScopes(f.companyId, f.agentId, null);
await flushBudgetEvaluationWork(db);
const [company] = await db.select().from(companies).where(eq(companies.id, f.companyId));
expect(company).toMatchObject({ status: "active", pauseReason: null });
expect(await db.select().from(budgetIncidents).where(eq(budgetIncidents.companyId, f.companyId))).toHaveLength(0);
const [policy] = await db.select().from(budgetPolicies).where(eq(budgetPolicies.id, f.policy.id));
expect(policy.enforcementVersion).toBe(f.policy.enforcementVersion);
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runningId)))[0].status).toBe("running");
expect(await f.block()).toMatchObject({ reason: "Company cannot start work while completed runs await accounting." });
});
it("settles a finalization-deadline failure once its local stop is verified", async () => {
const f = await fixture({ failureCode: "execution_finalization_deadline_exceeded" });
expect(await f.block()).not.toBeNull();
expect(await reconcileRunCosts(db)).toMatchObject({ accounted: 1 });
await flushBudgetEvaluationWork(db);
expect(await f.block()).toBeNull();
});
it.each([
["no verified stop event", { stopEvidence: false }],
["a finalization deadline without a verified stop", { failureCode: "execution_finalization_deadline_exceeded", stopEvidence: false }],
] as const)("keeps the debt pending with %s", async (_label, options) => {
const f = await fixture(options);
expect(await reconcileRunCosts(db)).toMatchObject({ accounted: 0 });
expect(await accountRunCost(db, f.run.id)).toBe(false);
expect((await f.readRun()).costAccountingPending).toBe(true);
expect(await f.charges()).toHaveLength(0);
});
// Upgrade path: an older release paused the company for pending accounting.
it("releases a budget-owned pause that only pending accounting kept", async () => {
const f = await fixture({ stopEvidence: false });
await db.update(companies).set({ status: "paused", pauseReason: "budget", pausedAt: new Date() })
.where(eq(companies.id, f.companyId));
await db.insert(budgetIncidents).values({ companyId: f.companyId, policyId: f.policy.id, scopeType: "company",
scopeId: f.companyId, metric: "billed_cents", windowKind: "calendar_month_utc",
windowStart: new Date(Date.UTC(2026, 10, 1)), windowEnd: new Date(Date.UTC(2026, 11, 1)),
thresholdType: "hard", amountLimit: 500, amountObserved: 0 });
await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.run.id));
await budgetService(db).evaluateAffectedScopes(f.companyId, f.agentId, null);
await flushBudgetEvaluationWork(db);
const [company] = await db.select().from(companies).where(eq(companies.id, f.companyId));
expect(company).toMatchObject({ status: "active", pauseReason: null });
expect((await db.select().from(budgetIncidents).where(eq(budgetIncidents.companyId, f.companyId)))[0].status).not.toBe("open");
expect(await f.block()).toMatchObject({ reason: "Company cannot start work while completed runs await accounting." });
const [policy] = await db.select().from(budgetPolicies).where(eq(budgetPolicies.id, f.policy.id));
expect((await budgetService(db).overview(f.companyId)).policies[0]?.status).not.toBe("hard_stop");
expect(policy.id).toBe(f.policy.id);
});
it("keeps the debt pending while native recovery can still produce a result", async () => {
const f = await fixture({ phase: "observed" });
expect(await reconcileRunCosts(db)).toMatchObject({ accounted: 0 });
expect((await f.readRun()).costAccountingPending).toBe(true);
expect(await f.charges()).toHaveLength(0);
});
it("reconciles a final receipt that arrives after the unavailable receipt settled", async () => {
const f = await fixture();
expect(await accountRunCost(db, f.run.id)).toBe(true);
await persistUsageReceipt(db, { schema: "paperclip/accounting-receipt/v1", id: randomUUID(),
companyId: f.companyId, runId: f.run.id, adapterType: "paperclip_runner", sourceId: f.sourceId, sequence: 2,
receivedAt: new Date().toISOString(), receipt: { complete: true, usageBasis: "per_run", provider: "anthropic",
biller: "anthropic", model: "claude-sonnet-5", billingType: "metered_api",
usage: { inputTokens: 1200, cachedInputTokens: 0, outputTokens: 80 } } });
const late = await f.readRun();
expect(late.costAccountingPending).toBe(true);
expect(late.usageJson).toMatchObject({ accountingLateReceiptPending: true });
});
it("does not reopen the hold for a later receipt the rate card could price but that carries no price", async () => {
const f = await fixture();
expect(await accountRunCost(db, f.run.id)).toBe(true);
await persistUsageReceipt(db, { schema: "paperclip/accounting-receipt/v1", id: randomUUID(),
companyId: f.companyId, runId: f.run.id, adapterType: "paperclip_runner", sourceId: f.sourceId, sequence: 2,
receivedAt: new Date().toISOString(),
producerEvent: { sourceEventId: randomUUID(), eventType: "turn.completed" },
receipt: { complete: true, usageBasis: "per_run", provider: "anthropic", biller: "anthropic",
model: "claude-sonnet-5", billingType: "metered_api",
usage: { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, cacheWriteTokens: 0 } } });
expect((await f.readRun()).costAccountingPending).toBe(false);
expect(await f.block()).toBeNull();
});
it("does not reopen the hold for a later complete receipt that adds no price or usage", async () => {
const f = await fixture();
expect(await accountRunCost(db, f.run.id)).toBe(true);
await persistUsageReceipt(db, { schema: "paperclip/accounting-receipt/v1", id: randomUUID(),
companyId: f.companyId, runId: f.run.id, adapterType: "paperclip_runner", sourceId: f.sourceId, sequence: 2,
receivedAt: new Date().toISOString(),
producerEvent: { sourceEventId: randomUUID(), eventType: "turn.completed" },
receipt: { complete: true, usageBasis: "per_run", provider: "anthropic", biller: "anthropic",
model: "claude-sonnet-5", billingType: "metered_api", costStatus: "unpriced",
usage: { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 } } });
expect((await f.readRun()).costAccountingPending).toBe(false);
expect(await f.block()).toBeNull();
});
// A producer receipt priced only from the rate card is normally not a money
// correction. For a charge settled without its receipt, it is the first price.
it("prices the unavailable charge when a complete rate-card receipt arrives later", async () => {
const f = await fixture({ unpricedUsagePolicy: "block" });
expect(await accountRunCost(db, f.run.id)).toBe(true);
await persistUsageReceipt(db, { schema: "paperclip/accounting-receipt/v1", id: randomUUID(),
companyId: f.companyId, runId: f.run.id, adapterType: "paperclip_runner", sourceId: f.sourceId, sequence: 2,
receivedAt: new Date().toISOString(),
producerEvent: { sourceEventId: randomUUID(), eventType: "turn.completed" },
receipt: { complete: true, usageBasis: "per_run", provider: "anthropic", biller: "anthropic",
model: "claude-sonnet-5", billingType: "metered_api", costUsd: 0.25, costStatus: "estimated",
pricingProvenance: { source: "rate_card", version: "anthropic-test" },
usage: { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 } } });
expect((await f.readRun()).usageJson).toMatchObject({ accountingLateReceiptPending: true });
await accountRunCost(db, f.run.id);
await flushBudgetEvaluationWork(db);
expect((await f.readRun()).costAccountingPending).toBe(false);
const charges = await f.charges();
expect(charges).toHaveLength(1);
expect(charges[0]).toMatchObject({ costStatus: "estimated" });
expect(Number(charges[0].costCents)).toBeCloseTo(25, 5);
expect(await f.block()).toBeNull();
});
});