refactor(cost): single writer for cost_entries, finishRun reads SUM

Cost was written through three independent paths: worker-runner shipped
`finalUsage.costUsd` in run-finished -> finishRun wrote `runs.cost_usd`,
`tasks.cost_usd += costUsd`, `agents.spent_monthly_usd += costUsd`, and
inserted a per-run aggregate row in cost_entries. CostWriter
additionally inserted per-message rows in cost_entries from main. Any
CostWriter failure created silent drift between `SUM(cost_entries)`
(read by budget enforcement) and `runs.cost_usd` (read by the UI).

Make CostWriter the single writer, finishRun the single reader.

- Add `db.recordCostEntry(...)` as the first-class insert path for
  per-message cost rows. CostWriter calls it; tests call it directly.
- Remove the aggregate INSERT from finishRun. finishRun now reads
  `SELECT COALESCE(SUM(amount_usd), 0) FROM cost_entries WHERE run_id=?
  AND unattributed=0` and writes that as the authoritative run total to
  runs.cost_usd, tasks.cost_usd, and agents.spent_monthly_usd.
- Drop `costUsd` from `finishRun` input, the worker `run-finished`
  ChildMessage shape, the automation `RunFinishedEvent` type, and every
  caller + test fixture. Cost is owned by the per-message path.
- worker-runner stops extracting `usage.cost.total` — token counts stay
  for session accumulation, cost comes from pi-ai via CostWriter.
- run-finished-helpers now gates budget incident checks on
  `event.status === "succeeded"` instead of a cost field that no longer
  exists on the event.
- automation-run-completion fires `budget_threshold` on every succeeded
  run (post-run spent_monthly_usd already reflects the SUM path).
- Update budget tests to write a `recordCostEntry` before `finishRun`
  to simulate the per-message cost path; drop `costUsd` from cross-
  subsystem, edge-case-budget, database, and related fixtures.

One writer, one reader, one source of truth. No drift.
This commit is contained in:
ZacharyZhang-NY committed 2026-04-17 15:04:22 -04:00
1 parent 77f81a7c5a
commit 14dc9a4897
26 files changed
+102 -93

No files matched your search

+15 -26
View File
@@ -18,18 +18,18 @@ interface ObserveInput {
}
/**
* Writes a `cost_entries` row for an assistant `message_end` and updates the
* cumulative `runs.cost_usd` for the active run.
* Writes a `cost_entries` row for each pi `message_end`. finishRun reads
* SUM(cost_entries.amount_usd) for the run-level aggregate, so this is
* the single source of truth for cost attribution.
*/
export class CostWriter {
constructor(private readonly deps: CostWriterDeps) {}
observeAssistantMessage(input: ObserveInput): void {
// Fail closed on cost calculation — budget policies read `cost_entries`
// to enforce spending gates; an "unattributed" row would silently let
// an agent run unbounded. If pricing cannot be resolved, refuse to
// persist the row and let the caller see the error. The failure is
// visible (throws) instead of invisible (null amount, unattributed=1).
// to enforce spending gates; silently emitting an unattributed row
// would let an agent run unbounded. If pricing cannot be resolved,
// throw so the caller logs and the missing cost is visible.
const definition = getConnectorDefinition(input.connectorId);
if (!definition.provider) {
throw new Error(`[cost-writer] connector ${input.connectorId} has no provider mapping`);
@@ -45,25 +45,14 @@ export class CostWriter {
);
}
this.deps.db.queryAll(
"insert into cost_entries (id, company_id, run_id, task_id, agent_id, connector_id, amount_usd, unattributed, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
cryptoRandomId(),
input.companyId,
input.runId,
input.taskId,
input.agentId,
input.connectorId,
cost.total,
0,
new Date().toISOString(),
);
this.deps.db.recordCostEntry({
runId: input.runId,
companyId: input.companyId,
agentId: input.agentId,
taskId: input.taskId,
connectorId: input.connectorId,
amountUsd: cost.total,
unattributed: false,
});
}
}
function cryptoRandomId(): string {
// Avoid pulling node:crypto at module top-level so this file can be
// imported from non-Node contexts during type checks.
return globalThis.crypto?.randomUUID
? globalThis.crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}