Cost Ledger & Metering
Relevant source files
The following files were used as context for generating this wiki page:
The Cost Ledger & Metering system tracks and audits outbound provider calls within the Vantage platform. It provides an append-only log of every metered action, facilitating budget management, workspace credit tracking, and public cost transparency.
The system consists of three primary layers: the Meter (which wraps provider calls), the Ledger (which calculates and persists individual cost events), and the Aggregation Layer (which rolls up events into daily summaries).
Sources: lib/costs/ledger.ts, lib/costs/meter.ts, README.md
Data Architecture
The system relies on a set of relational tables to store pricing configurations, individual call events, and aggregated totals.
Core Tables
| Table | Purpose | Key Columns |
|---|---|---|
cost_event | Stores every individual outbound call as an immutable audit row. | id, ts, workspace_id, provider, action, units, cost_usd, ok |
cost_daily | Holds daily rollups of costs per source, provider, and action. | day, source_key, provider, action, calls, cost_usd, failed |
provider_price | Manages active prices for specific provider actions. | provider, action, unit_cost_usd, effective_from |
budget_day | Tracks global daily spending against a defined cap. | day, spent_usd, cap_usd |
Sources: lib/db/schema.ts:509-566, drizzle/0000_m1_core.sql
Entity Relationships
The following diagram illustrates how cost events relate to workspaces and daily aggregations.
This diagram shows the relationship between workspaces, sources, pricing data, and the resulting cost logs.
Sources: lib/db/schema.ts:509-566
Cost Computation Logic
The system performs precise currency calculations to prevent floating-point drift and ensure that stored units multiplied by unit costs exactly match the total cost.
Precision and Rounding
Costs are quantized to 6 decimal places (numeric(12,6)), using a scale factor of 1,000,000.
roundUsd(value): Multiplies by1,000,000, rounds the result usingtoPrecision(15)to strip float noise, and divides back.computeCost(input):- Quantizes units to 4 decimal places (
numeric(14,4)). - Multiplies units by the 6-decimal rounded unit cost.
- Sets total to zero for failed calls unless
chargedOnFailureis true.
- Quantizes units to 4 decimal places (
Sources: lib/costs/ledger.ts:25-50, test/cost-ledger.test.ts:26-55
// Example of precision rounding to avoid float drift
// Sources: [lib/costs/ledger.ts:25-28]
export function roundUsd(value: number): number {
return Math.round(Number((value * 1_000_000).toPrecision(15))) / 1_000_000;
}
Metering Workflow
The withCost function serves as the primary entry point for metered provider calls. It ensures that every call is recorded even if the provider function throws an error.
Call Lifecycle
- The Meter receives a provider function and metadata (source key, provider, action).
- It executes the provider function.
- If the function succeeds:
- It determines billable units via a callback or defaults to 1.
- It checks if the result indicates a logical failure via
isFailure.
- If the function throws:
- It catches the error and prepares a record with
ok: false.
- It catches the error and prepares a record with
- The Ledger retrieves the current price from
provider_priceand inserts acost_eventrow. - The original result is returned, or the error is rethrown.
Sources: lib/costs/meter.ts:23-51, test/cost-meter.test.ts:35-85
This diagram illustrates the sequence from provider execution to ledger persistence.
Sources: lib/costs/meter.ts:23-51
Aggregation and Rollups
Individual events are aggregated into the cost_daily table to facilitate reporting and dashboarding.
Rollup Mechanism
The rollupDay function performs an idempotent upsert. It recomputes totals for a specific UTC day by scanning the cost_event table. Rerunning a rollup overwrites existing totals for that day, preventing double-counting.
- Calls: Count of all events.
- Cost: Sum of
cost_usd. - Failed: Count of events where
okis false.
Sources: test/cost-meter.test.ts:88-121
Scheduled Tasks
The system supports rolling up recent data (yesterday and today) via rollupRecent. This ensures that daily totals remain accurate as events are logged throughout the day.
Sources: test/cost-meter.test.ts:117-121
Summary
The Cost Ledger & Metering module provides a robust framework for financial accountability within the application. By combining precise rounding logic, a fail-safe metering wrapper, and idempotent daily rollups, it maintains a reliable record of operational costs across multiple service providers.
Sources: lib/costs/ledger.ts, lib/costs/meter.ts, lib/db/schema.ts