use std::path::Path;
use std::str::FromStr;
use chrono::{DateTime, Utc};
use costroid_focus::{
FocusAccessPath, FocusRecord, LedgerLane, TokenType, UnpricedUsage, FOCUS_VERSION,
};
use rusqlite::{Connection, OptionalExtension};
use rust_decimal::Decimal;
use thiserror::Error;
pub const SCHEMA_VERSION: i64 = 7;
pub const USAGE_ROWS_TABLE: &str = "usage_rows";
pub const STORE_META_TABLE: &str = "store_meta";
pub const USAGE_ROWS_COLUMNS: &[&str] = &[
"charge_period_start",
"x_lane",
"x_tool",
"x_model",
"x_token_type",
"x_access_path",
"x_pricing_status",
"x_estimated", "x_project", "billed_cost",
"effective_cost",
"list_cost",
"contracted_cost",
"pricing_currency_effective_cost",
"x_consumed_tokens",
"billing_currency",
"consumed_quantity",
"pricing_quantity",
"list_unit_price",
"contracted_unit_price",
"pricing_currency_list_unit_price",
"pricing_currency_contracted_unit_price",
"service_name",
"service_provider_name",
"host_provider_name",
"invoice_issuer_name",
"sku_id",
"sku_price_id",
"sku_meter",
"pricing_category",
"pricing_unit",
"x_focus_input_version",
"x_sidechain", "x_attribution_confidence", "x_collector_version", "x_pricing_snapshot_id",
"x_inference_profile_id",
"x_measured_wh",
"x_avg_power_watts",
"x_hardware_profile",
"x_amortized_hw_cost",
"x_runtime_kind",
"x_benchmark_id",
"x_measurement_mode",
];
pub const FORBIDDEN_SUBSTRINGS: &[&str] = &[
"description",
"resource",
"tags",
"content",
"prompt",
"completion",
"message",
"text", "sku_price_details",
];
pub fn usage_rows_ddl() -> String {
format!(
"CREATE TABLE IF NOT EXISTS {USAGE_ROWS_TABLE} (\n \
id INTEGER PRIMARY KEY,\n \
charge_period_start TEXT NOT NULL,\n \
x_lane TEXT NOT NULL,\n \
x_tool TEXT NOT NULL,\n \
x_model TEXT NOT NULL,\n \
x_token_type TEXT NOT NULL,\n \
x_access_path TEXT NOT NULL,\n \
x_pricing_status TEXT NOT NULL,\n \
x_estimated INTEGER NOT NULL,\n \
x_project TEXT,\n \
billed_cost TEXT NOT NULL,\n \
effective_cost TEXT NOT NULL,\n \
list_cost TEXT NOT NULL,\n \
contracted_cost TEXT NOT NULL,\n \
pricing_currency_effective_cost TEXT NOT NULL,\n \
x_consumed_tokens TEXT NOT NULL,\n \
billing_currency TEXT NOT NULL,\n \
consumed_quantity TEXT,\n \
pricing_quantity TEXT,\n \
list_unit_price TEXT,\n \
contracted_unit_price TEXT,\n \
pricing_currency_list_unit_price TEXT,\n \
pricing_currency_contracted_unit_price TEXT,\n \
service_name TEXT NOT NULL,\n \
service_provider_name TEXT NOT NULL,\n \
host_provider_name TEXT NOT NULL,\n \
invoice_issuer_name TEXT NOT NULL,\n \
sku_id TEXT,\n \
sku_price_id TEXT,\n \
sku_meter TEXT,\n \
pricing_category TEXT,\n \
pricing_unit TEXT,\n \
x_focus_input_version TEXT,\n \
x_sidechain INTEGER NOT NULL,\n \
x_attribution_confidence TEXT NOT NULL,\n \
x_collector_version TEXT NOT NULL,\n \
x_pricing_snapshot_id TEXT,\n \
x_inference_profile_id TEXT,\n \
x_measured_wh TEXT,\n \
x_avg_power_watts TEXT,\n \
x_hardware_profile TEXT,\n \
x_amortized_hw_cost TEXT,\n \
x_runtime_kind TEXT,\n \
x_benchmark_id TEXT,\n \
x_measurement_mode TEXT\n\
)"
)
}
fn store_meta_ddl() -> String {
format!(
"CREATE TABLE IF NOT EXISTS {STORE_META_TABLE} (\n \
key TEXT PRIMARY KEY,\n \
value TEXT NOT NULL\n\
)"
)
}
#[derive(Debug, Error)]
pub enum StoreError {
#[error("sqlite error: {0}")]
Sqlite(#[from] rusqlite::Error),
#[error("unsupported store schema version: found {found}, expected {expected}")]
SchemaVersion { found: i64, expected: i64 },
#[error("failed to reconstruct a FocusRecord from a stored row: {0}")]
Reconstruct(String),
#[error("failed to build a FocusRecord on replay: {0}")]
Focus(#[from] costroid_focus::FocusError),
}
pub struct Store {
conn: Connection,
}
impl Store {
pub fn open_in_memory() -> Result<Self, StoreError> {
let conn = Connection::open_in_memory()?;
Self::from_connection(conn)
}
pub fn open(path: &Path) -> Result<Self, StoreError> {
let conn = Connection::open(path)?;
Self::from_connection(conn)
}
fn from_connection(conn: Connection) -> Result<Self, StoreError> {
conn.execute_batch(&format!("{};\n{};", store_meta_ddl(), usage_rows_ddl()))?;
let existing: Option<String> = conn
.query_row(
&format!("SELECT value FROM {STORE_META_TABLE} WHERE key = 'schema_version'"),
[],
|row| row.get(0),
)
.optional()?;
match existing {
Some(value) => {
let found: i64 = value.parse().unwrap_or(-1);
if found != SCHEMA_VERSION {
return Err(StoreError::SchemaVersion {
found,
expected: SCHEMA_VERSION,
});
}
}
None => {
conn.execute(
&format!(
"INSERT INTO {STORE_META_TABLE} (key, value) VALUES \
('schema_version', ?1), ('focus_version', ?2)"
),
rusqlite::params![SCHEMA_VERSION.to_string(), FOCUS_VERSION],
)?;
}
}
Ok(Self { conn })
}
pub fn ingest(&self, rows: &[FocusRecord]) -> Result<usize, StoreError> {
let tx = self.conn.unchecked_transaction()?;
{
let mut stmt = tx.prepare(&format!(
"INSERT INTO {USAGE_ROWS_TABLE} (\
charge_period_start, x_lane, x_tool, x_model, x_token_type, \
x_access_path, x_pricing_status, x_estimated, x_project, \
billed_cost, effective_cost, list_cost, contracted_cost, \
pricing_currency_effective_cost, x_consumed_tokens, billing_currency, \
consumed_quantity, pricing_quantity, list_unit_price, \
contracted_unit_price, pricing_currency_list_unit_price, \
pricing_currency_contracted_unit_price, service_name, \
service_provider_name, host_provider_name, invoice_issuer_name, \
sku_id, sku_price_id, sku_meter, pricing_category, pricing_unit, \
x_focus_input_version, x_sidechain, x_attribution_confidence, \
x_collector_version, x_pricing_snapshot_id, x_inference_profile_id, \
x_measured_wh, x_avg_power_watts, x_hardware_profile, \
x_amortized_hw_cost, x_runtime_kind, x_benchmark_id, x_measurement_mode\
) VALUES (\
?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, \
?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, \
?29, ?30, ?31, ?32, ?33, ?34, ?35, ?36, ?37, ?38, ?39, ?40, ?41, \
?42, ?43, ?44\
)"
))?;
for row in rows {
stmt.execute(rusqlite::params![
row.charge_period_start.to_rfc3339(),
row.x_lane,
row.x_tool,
row.x_model,
row.x_token_type,
row.x_access_path,
row.x_pricing_status,
i64::from(row.x_estimated),
row.x_project,
row.billed_cost.to_string(),
row.effective_cost.to_string(),
row.list_cost.to_string(),
row.contracted_cost.to_string(),
row.pricing_currency_effective_cost.to_string(),
row.x_consumed_tokens.to_string(),
row.billing_currency,
decimal_opt_to_string(&row.consumed_quantity),
decimal_opt_to_string(&row.pricing_quantity),
decimal_opt_to_string(&row.list_unit_price),
decimal_opt_to_string(&row.contracted_unit_price),
decimal_opt_to_string(&row.pricing_currency_list_unit_price),
decimal_opt_to_string(&row.pricing_currency_contracted_unit_price),
row.service_name,
row.service_provider_name,
row.host_provider_name,
row.invoice_issuer_name,
row.sku_id,
row.sku_price_id,
row.sku_meter,
row.pricing_category,
row.pricing_unit,
row.x_focus_input_version,
i64::from(row.x_sidechain),
row.x_attribution_confidence,
row.x_collector_version,
row.x_pricing_snapshot_id,
row.x_inference_profile_id,
decimal_opt_to_string(&row.x_measured_wh),
decimal_opt_to_string(&row.x_avg_power_watts),
row.x_hardware_profile,
decimal_opt_to_string(&row.x_amortized_hw_cost),
row.x_runtime_kind,
row.x_benchmark_id,
row.x_measurement_mode,
])?;
}
}
tx.commit()?;
Ok(rows.len())
}
pub fn row_count(&self) -> Result<usize, StoreError> {
let count: i64 = self.conn.query_row(
&format!("SELECT COUNT(*) FROM {USAGE_ROWS_TABLE}"),
[],
|row| row.get(0),
)?;
Ok(count.max(0) as usize)
}
pub fn all_focus_rows(&self) -> Result<Vec<FocusRecord>, StoreError> {
let mut stmt = self.conn.prepare(&format!(
"SELECT charge_period_start, x_lane, x_tool, x_model, x_token_type, \
x_access_path, x_pricing_status, x_estimated, x_project, billed_cost, \
effective_cost, list_cost, contracted_cost, \
pricing_currency_effective_cost, x_consumed_tokens, billing_currency, \
consumed_quantity, pricing_quantity, list_unit_price, \
contracted_unit_price, pricing_currency_list_unit_price, \
pricing_currency_contracted_unit_price, service_name, \
service_provider_name, host_provider_name, invoice_issuer_name, sku_id, \
sku_price_id, sku_meter, pricing_category, pricing_unit, \
x_focus_input_version, x_sidechain, x_attribution_confidence, \
x_collector_version, x_pricing_snapshot_id, x_inference_profile_id, \
x_measured_wh, x_avg_power_watts, x_hardware_profile, \
x_amortized_hw_cost, x_runtime_kind, x_benchmark_id, x_measurement_mode \
FROM {USAGE_ROWS_TABLE} ORDER BY id"
))?;
let mut records = Vec::new();
let mut query = stmt.query([])?;
while let Some(row) = query.next()? {
records.push(Self::reconstruct_row(row)?);
}
Ok(records)
}
fn reconstruct_row(row: &rusqlite::Row<'_>) -> Result<FocusRecord, StoreError> {
let charge_period_start: String = row.get(0)?;
let x_lane: String = row.get(1)?;
let x_tool: String = row.get(2)?;
let x_model: String = row.get(3)?;
let x_token_type: String = row.get(4)?;
let x_access_path: String = row.get(5)?;
let x_pricing_status: String = row.get(6)?;
let x_estimated: i64 = row.get(7)?;
let x_project: Option<String> = row.get(8)?;
let billed_cost: String = row.get(9)?;
let effective_cost: String = row.get(10)?;
let list_cost: String = row.get(11)?;
let contracted_cost: String = row.get(12)?;
let pricing_currency_effective_cost: String = row.get(13)?;
let x_consumed_tokens: String = row.get(14)?;
let billing_currency: String = row.get(15)?;
let consumed_quantity: Option<String> = row.get(16)?;
let pricing_quantity: Option<String> = row.get(17)?;
let list_unit_price: Option<String> = row.get(18)?;
let contracted_unit_price: Option<String> = row.get(19)?;
let pricing_currency_list_unit_price: Option<String> = row.get(20)?;
let pricing_currency_contracted_unit_price: Option<String> = row.get(21)?;
let service_name: String = row.get(22)?;
let service_provider_name: String = row.get(23)?;
let host_provider_name: String = row.get(24)?;
let invoice_issuer_name: String = row.get(25)?;
let sku_id: Option<String> = row.get(26)?;
let sku_price_id: Option<String> = row.get(27)?;
let sku_meter: Option<String> = row.get(28)?;
let pricing_category: Option<String> = row.get(29)?;
let pricing_unit: Option<String> = row.get(30)?;
let x_focus_input_version: Option<String> = row.get(31)?;
let x_sidechain: i64 = row.get(32)?;
let x_attribution_confidence: String = row.get(33)?;
let x_collector_version: String = row.get(34)?;
let x_pricing_snapshot_id: Option<String> = row.get(35)?;
let x_inference_profile_id: Option<String> = row.get(36)?;
let x_measured_wh: Option<String> = row.get(37)?;
let x_avg_power_watts: Option<String> = row.get(38)?;
let x_hardware_profile: Option<String> = row.get(39)?;
let x_amortized_hw_cost: Option<String> = row.get(40)?;
let x_runtime_kind: Option<String> = row.get(41)?;
let x_benchmark_id: Option<String> = row.get(42)?;
let x_measurement_mode: Option<String> = row.get(43)?;
let lane = LedgerLane::from_focus_str(&x_lane)
.ok_or_else(|| StoreError::Reconstruct(format!("unknown x_lane `{x_lane}`")))?;
let token_type = TokenType::from_focus_str(&x_token_type).ok_or_else(|| {
StoreError::Reconstruct(format!("unknown x_token_type `{x_token_type}`"))
})?;
let access_path = FocusAccessPath::from_focus_str(&x_access_path).ok_or_else(|| {
StoreError::Reconstruct(format!("unknown x_access_path `{x_access_path}`"))
})?;
let timestamp = DateTime::parse_from_rfc3339(&charge_period_start)
.map_err(|err| {
StoreError::Reconstruct(format!(
"unparseable charge_period_start `{charge_period_start}`: {err}"
))
})?
.with_timezone(&Utc);
let billed = parse_decimal("billed_cost", &billed_cost)?;
let effective = parse_decimal("effective_cost", &effective_cost)?;
let list = parse_decimal("list_cost", &list_cost)?;
let contracted = parse_decimal("contracted_cost", &contracted_cost)?;
let pricing_currency_effective = parse_decimal(
"pricing_currency_effective_cost",
&pricing_currency_effective_cost,
)?;
let consumed_qty = parse_decimal_opt("consumed_quantity", &consumed_quantity)?;
let pricing_qty = parse_decimal_opt("pricing_quantity", &pricing_quantity)?;
let list_unit = parse_decimal_opt("list_unit_price", &list_unit_price)?;
let contracted_unit = parse_decimal_opt("contracted_unit_price", &contracted_unit_price)?;
let pricing_currency_list_unit = parse_decimal_opt(
"pricing_currency_list_unit_price",
&pricing_currency_list_unit_price,
)?;
let pricing_currency_contracted_unit = parse_decimal_opt(
"pricing_currency_contracted_unit_price",
&pricing_currency_contracted_unit_price,
)?;
let consumed = parse_decimal("x_consumed_tokens", &x_consumed_tokens)?;
let token_count = decimal_to_u64("x_consumed_tokens", &consumed)?;
let input = UnpricedUsage {
lane,
timestamp,
tool: x_tool,
model: x_model,
token_type,
token_count,
project: x_project,
access_path,
service_name,
service_provider_name,
host_provider_name,
invoice_issuer_name,
billing_currency,
};
let mut record = FocusRecord::unpriced_usage(input)?;
record.billed_cost = billed;
record.effective_cost = effective;
record.list_cost = list;
record.contracted_cost = contracted;
record.pricing_currency_effective_cost = pricing_currency_effective;
record.consumed_quantity = consumed_qty;
record.pricing_quantity = pricing_qty;
record.list_unit_price = list_unit;
record.contracted_unit_price = contracted_unit;
record.pricing_currency_list_unit_price = pricing_currency_list_unit;
record.pricing_currency_contracted_unit_price = pricing_currency_contracted_unit;
record.x_estimated = x_estimated != 0;
record.x_pricing_status = x_pricing_status;
record.x_consumed_tokens = consumed;
record.sku_id = sku_id;
record.sku_price_id = sku_price_id;
record.sku_meter = sku_meter;
record.pricing_category = pricing_category;
record.pricing_unit = pricing_unit;
record.x_focus_input_version = x_focus_input_version;
record.x_sidechain = x_sidechain != 0;
record.x_attribution_confidence = x_attribution_confidence;
record.x_collector_version = x_collector_version;
record.x_pricing_snapshot_id = x_pricing_snapshot_id;
record.x_inference_profile_id = x_inference_profile_id;
record.x_measured_wh = parse_decimal_opt("x_measured_wh", &x_measured_wh)?;
record.x_avg_power_watts = parse_decimal_opt("x_avg_power_watts", &x_avg_power_watts)?;
record.x_amortized_hw_cost =
parse_decimal_opt("x_amortized_hw_cost", &x_amortized_hw_cost)?;
record.x_hardware_profile = x_hardware_profile;
record.x_runtime_kind = x_runtime_kind;
record.x_benchmark_id = x_benchmark_id;
record.x_measurement_mode = x_measurement_mode;
Ok(record)
}
pub fn stored_lanes(&self) -> Result<Vec<String>, StoreError> {
let mut stmt = self.conn.prepare(&format!(
"SELECT x_lane FROM {USAGE_ROWS_TABLE} ORDER BY id"
))?;
let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
let mut lanes = Vec::new();
for lane in rows {
lanes.push(lane?);
}
Ok(lanes)
}
pub fn stored_billed_costs(&self) -> Result<Vec<String>, StoreError> {
let mut stmt = self.conn.prepare(&format!(
"SELECT billed_cost FROM {USAGE_ROWS_TABLE} ORDER BY id"
))?;
let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
let mut costs = Vec::new();
for cost in rows {
costs.push(cost?);
}
Ok(costs)
}
}
fn parse_decimal(column: &str, value: &str) -> Result<Decimal, StoreError> {
Decimal::from_str(value)
.map_err(|err| StoreError::Reconstruct(format!("unparseable {column} `{value}`: {err}")))
}
fn parse_decimal_opt(column: &str, value: &Option<String>) -> Result<Option<Decimal>, StoreError> {
match value {
Some(text) => Ok(Some(parse_decimal(column, text)?)),
None => Ok(None),
}
}
fn decimal_opt_to_string(value: &Option<Decimal>) -> Option<String> {
value.as_ref().map(Decimal::to_string)
}
fn decimal_to_u64(column: &str, value: &Decimal) -> Result<u64, StoreError> {
use rust_decimal::prelude::ToPrimitive;
if value.fract() != Decimal::ZERO {
return Err(StoreError::Reconstruct(format!(
"{column} `{value}` is not a whole token count"
)));
}
value.to_u64().ok_or_else(|| {
StoreError::Reconstruct(format!(
"{column} `{value}` is out of range for a token count"
))
})
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{LocalResult, TimeZone};
use costroid_focus::DEFAULT_BILLING_CURRENCY;
fn record(lane: LedgerLane, billed_cents: i64) -> FocusRecord {
let timestamp = match Utc.with_ymd_and_hms(2026, 1, 15, 12, 34, 56) {
LocalResult::Single(value) => value,
LocalResult::Ambiguous(_, _) | LocalResult::None => {
panic!("test timestamp should be valid")
}
};
let input = UnpricedUsage {
lane,
timestamp,
tool: "codex".to_string(),
model: "example-model".to_string(),
token_type: TokenType::Input,
token_count: 1_500,
project: Some("/work/project".to_string()),
access_path: FocusAccessPath::Subscription,
service_name: "Codex".to_string(),
service_provider_name: "OpenAI".to_string(),
host_provider_name: "OpenAI".to_string(),
invoice_issuer_name: "OpenAI".to_string(),
billing_currency: DEFAULT_BILLING_CURRENCY.to_string(),
};
let Ok(mut rec) = FocusRecord::unpriced_usage(input) else {
panic!("record should build");
};
let billed = Decimal::new(billed_cents, 2);
rec.billed_cost = billed;
rec.effective_cost = billed;
rec
}
#[test]
fn r4_schema_forbids_free_text_columns_and_is_allowlist_bounded() {
let ddl = usage_rows_ddl()
.to_lowercase()
.replace("text", "")
.replace("integer", "");
for forbidden in FORBIDDEN_SUBSTRINGS {
if *forbidden == "text" {
continue;
}
assert!(
!ddl.contains(forbidden),
"R4 violation: usage_rows DDL contains forbidden substring `{forbidden}`:\n{ddl}"
);
}
let Ok(store) = Store::open_in_memory() else {
panic!("in-memory store should open");
};
let Ok(mut stmt) = store
.conn
.prepare(&format!("PRAGMA table_info({USAGE_ROWS_TABLE})"))
else {
panic!("table_info pragma should prepare");
};
let Ok(rows) = stmt.query_map([], |row| row.get::<_, String>(1)) else {
panic!("table_info should query");
};
let mut columns = Vec::new();
for col in rows {
let Ok(col) = col else {
panic!("column name should read");
};
columns.push(col);
}
let allow: std::collections::BTreeSet<&str> = USAGE_ROWS_COLUMNS.iter().copied().collect();
for col in &columns {
if col == "id" {
continue;
}
let lower = col.to_lowercase();
for forbidden in FORBIDDEN_SUBSTRINGS {
assert!(
!lower.contains(forbidden),
"R4 violation: column `{col}` contains forbidden substring `{forbidden}`"
);
}
assert!(
allow.contains(col.as_str()),
"fail-closed: column `{col}` is in the DDL but NOT in USAGE_ROWS_COLUMNS — \
review it (does it carry content?) before allowlisting it"
);
}
let real: std::collections::BTreeSet<&str> = columns.iter().map(String::as_str).collect();
for allowed in USAGE_ROWS_COLUMNS {
assert!(
real.contains(allowed),
"allowlist column `{allowed}` is not present in the live usage_rows schema"
);
}
}
#[test]
fn store_persist_or_drop_decision_is_field_exhaustive_over_focus_record() {
let FocusRecord {
billed_cost: _,
effective_cost: _,
list_cost: _,
contracted_cost: _,
pricing_currency_effective_cost: _,
billing_currency: _,
charge_period_start: _,
consumed_quantity: _,
pricing_quantity: _,
list_unit_price: _,
contracted_unit_price: _,
pricing_currency_list_unit_price: _,
pricing_currency_contracted_unit_price: _,
service_name: _,
service_provider_name: _,
host_provider_name: _,
invoice_issuer_name: _,
sku_id: _,
sku_price_id: _,
sku_meter: _,
pricing_category: _,
pricing_unit: _,
x_lane: _,
x_model: _,
x_token_type: _,
x_access_path: _,
x_estimated: _,
x_tool: _,
x_project: _,
x_pricing_status: _,
x_consumed_tokens: _,
x_focus_input_version: _,
x_sidechain: _,
x_attribution_confidence: _,
x_collector_version: _,
x_pricing_snapshot_id: _,
x_inference_profile_id: _,
x_measured_wh: _,
x_avg_power_watts: _,
x_hardware_profile: _,
x_amortized_hw_cost: _,
x_runtime_kind: _,
x_benchmark_id: _,
x_measurement_mode: _,
billing_account_id: _, billing_account_name: _, billing_account_type: _, billing_period_start: _, billing_period_end: _, charge_period_end: _, charge_category: _, charge_class: _, charge_description: _, charge_frequency: _, service_category: _, service_subcategory: _, provider_name: _, publisher_name: _, invoice_id: _, sku_price_details: _, pricing_currency: _, consumed_unit: _, commitment_discount_category: _, commitment_discount_id: _, commitment_discount_name: _, commitment_discount_quantity: _, commitment_discount_status: _, commitment_discount_type: _, commitment_discount_unit: _, capacity_reservation_id: _, capacity_reservation_status: _, region_id: _, region_name: _, availability_zone: _, resource_id: _, resource_name: _, resource_type: _, sub_account_id: _, sub_account_name: _, sub_account_type: _, tags: _, contract_applied: _, allocated_method_id: _, allocated_method_details: _, allocated_resource_id: _, allocated_resource_name: _, allocated_tags: _, } = record(LedgerLane::DeveloperTool, 0);
}
#[test]
fn ingest_round_trips_whitelisted_metadata() {
let Ok(store) = Store::open_in_memory() else {
panic!("in-memory store should open");
};
let rows = [
record(LedgerLane::DeveloperTool, 1_234), record(LedgerLane::CloudApi, 50), record(LedgerLane::LocalInference, 0), ];
let Ok(count) = store.ingest(&rows) else {
panic!("ingest should succeed");
};
assert_eq!(count, 3);
let Ok(total) = store.row_count() else {
panic!("row_count should succeed");
};
assert_eq!(total, 3);
let Ok(lanes) = store.stored_lanes() else {
panic!("stored_lanes should succeed");
};
assert_eq!(
lanes,
vec![
"developer_tool".to_string(),
"cloud_api".to_string(),
"local_inference".to_string(),
]
);
let Ok(costs) = store.stored_billed_costs() else {
panic!("stored_billed_costs should succeed");
};
assert_eq!(
costs,
vec!["12.34".to_string(), "0.50".to_string(), "0.00".to_string()]
);
}
#[test]
fn ingest_appends_across_calls() {
let Ok(store) = Store::open_in_memory() else {
panic!("in-memory store should open");
};
let Ok(_) = store.ingest(&[record(LedgerLane::DeveloperTool, 100)]) else {
panic!("first ingest should succeed");
};
let Ok(_) = store.ingest(&[
record(LedgerLane::CloudApi, 200),
record(LedgerLane::CloudApi, 300),
]) else {
panic!("second ingest should succeed");
};
let Ok(total) = store.row_count() else {
panic!("row_count should succeed");
};
assert_eq!(total, 3);
}
fn priced_cloud_record() -> FocusRecord {
let timestamp = match Utc.with_ymd_and_hms(2026, 2, 3, 9, 0, 0) {
LocalResult::Single(value) => value,
LocalResult::Ambiguous(_, _) | LocalResult::None => {
panic!("test timestamp should be valid")
}
};
let input = UnpricedUsage {
lane: LedgerLane::CloudApi,
timestamp,
tool: "anthropic-api".to_string(),
model: "claude-opus".to_string(),
token_type: TokenType::Output,
token_count: 4_096,
project: None,
access_path: FocusAccessPath::Api,
service_name: "Anthropic API".to_string(),
service_provider_name: "Anthropic".to_string(),
host_provider_name: "Anthropic".to_string(),
invoice_issuer_name: "Anthropic".to_string(),
billing_currency: DEFAULT_BILLING_CURRENCY.to_string(),
};
let Ok(mut rec) = FocusRecord::unpriced_usage(input) else {
panic!("priced cloud record should build");
};
let cost = Decimal::new(12_345, 4); rec.billed_cost = cost;
rec.effective_cost = cost;
rec.list_cost = cost;
rec.contracted_cost = cost;
rec.pricing_currency_effective_cost = cost;
let quantity = Decimal::from(4_096);
let per_token = Decimal::new(15, 8); rec.consumed_quantity = Some(quantity);
rec.pricing_quantity = Some(quantity);
rec.list_unit_price = Some(per_token);
rec.contracted_unit_price = Some(per_token);
rec.pricing_currency_list_unit_price = Some(per_token);
rec.pricing_currency_contracted_unit_price = Some(per_token);
rec.sku_price_id = Some("claude-opus:output:standard".to_string());
rec.pricing_category = Some("Standard".to_string());
rec.pricing_unit = Some("tokens".to_string());
rec.x_estimated = false;
rec.x_pricing_status = "priced".to_string();
rec.x_focus_input_version = Some("1.2".to_string());
rec.x_collector_version = "0.5.0-test".to_string();
rec
}
#[test]
fn all_focus_rows_round_trips_records_faithfully_including_priced_cloud() {
let Ok(store) = Store::open_in_memory() else {
panic!("in-memory store should open");
};
let mut sidechain_dev = record(LedgerLane::DeveloperTool, 1_234); sidechain_dev.x_sidechain = true;
sidechain_dev.x_attribution_confidence = "uncertain".to_string();
sidechain_dev.x_pricing_snapshot_id = Some("litellm@2026-06-18#36c8994e".to_string());
let mut local = record(LedgerLane::LocalInference, 0);
local.x_measured_wh = Some(Decimal::new(44, 4)); local.x_avg_power_watts = Some(Decimal::new(1600, 1)); local.x_hardware_profile = Some("strix-halo-128gb@2026-06-20".to_string());
local.x_amortized_hw_cost = Some(Decimal::new(21, 4)); local.x_runtime_kind = Some("ollama".to_string());
local.x_benchmark_id = Some("gemma4-coding-v1".to_string());
local.x_measurement_mode = Some("measured_wallmeter".to_string());
let originals = vec![
sidechain_dev, priced_cloud_record(), local, ];
let Ok(count) = store.ingest(&originals) else {
panic!("ingest should succeed");
};
assert_eq!(count, 3);
let Ok(reconstructed) = store.all_focus_rows() else {
panic!("all_focus_rows should succeed");
};
assert_eq!(reconstructed, originals);
assert_eq!(
reconstructed[0].x_pricing_snapshot_id,
Some("litellm@2026-06-18#36c8994e".to_string())
);
assert!(reconstructed[1].x_pricing_snapshot_id.is_none());
let cloud = &reconstructed[1];
assert_eq!(cloud.x_lane, "cloud_api");
assert_eq!(cloud.x_pricing_status, "priced");
assert!(!cloud.x_estimated);
assert_eq!(cloud.billed_cost, Decimal::new(12_345, 4));
assert_eq!(cloud.effective_cost, Decimal::new(12_345, 4));
assert_eq!(cloud.x_access_path, "api");
assert_eq!(cloud.x_token_type, "output");
assert_eq!(cloud.x_consumed_tokens, Decimal::from(4_096));
assert_eq!(cloud.list_cost, Decimal::new(12_345, 4));
assert_eq!(cloud.contracted_cost, Decimal::new(12_345, 4));
assert_eq!(
cloud.pricing_currency_effective_cost,
Decimal::new(12_345, 4)
);
let quantity = Decimal::from(4_096);
let per_token = Decimal::new(15, 8);
assert_eq!(cloud.consumed_quantity, Some(quantity));
assert_eq!(cloud.pricing_quantity, Some(quantity));
assert_eq!(cloud.list_unit_price, Some(per_token));
assert_eq!(cloud.contracted_unit_price, Some(per_token));
assert_eq!(cloud.pricing_currency_list_unit_price, Some(per_token));
assert_eq!(
cloud.pricing_currency_contracted_unit_price,
Some(per_token)
);
assert_eq!(
cloud.sku_price_id,
Some("claude-opus:output:standard".to_string())
);
assert_eq!(cloud.pricing_category, Some("Standard".to_string()));
assert_eq!(cloud.pricing_unit, Some("tokens".to_string()));
assert_eq!(
cloud.x_focus_input_version,
Some("1.2".to_string()),
"import provenance round-trips (not lost on replay)"
);
assert_eq!(
cloud.x_collector_version, "0.5.0-test",
"the STORED collector version is restored, not the current const"
);
let dev = &reconstructed[0];
assert_eq!(dev.pricing_quantity, None);
assert_eq!(dev.sku_price_id, None);
assert_eq!(dev.pricing_unit, None);
assert_eq!(dev.list_cost, Decimal::ZERO);
assert_eq!(
dev.x_focus_input_version, None,
"a directly-collected (non-imported) row stays None"
);
assert!(dev.x_sidechain, "the sidechain flag round-trips");
assert_eq!(
dev.x_attribution_confidence, "uncertain",
"uncertain attribution round-trips (not reverted to the confident default)"
);
assert_eq!(dev.x_measured_wh, None);
assert_eq!(dev.x_measurement_mode, None);
assert_eq!(cloud.x_avg_power_watts, None);
let local = &reconstructed[2];
assert_eq!(local.x_lane, "local_inference");
assert_eq!(local.x_measured_wh, Some(Decimal::new(44, 4)));
assert_eq!(local.x_avg_power_watts, Some(Decimal::new(1600, 1)));
assert_eq!(
local.x_hardware_profile,
Some("strix-halo-128gb@2026-06-20".to_string())
);
assert_eq!(local.x_amortized_hw_cost, Some(Decimal::new(21, 4)));
assert_eq!(local.x_runtime_kind, Some("ollama".to_string()));
assert_eq!(local.x_benchmark_id, Some("gemma4-coding-v1".to_string()));
assert_eq!(
local.x_measurement_mode,
Some("measured_wallmeter".to_string())
);
}
#[test]
fn all_focus_rows_fails_closed_on_a_malformed_stored_enum() {
let Ok(store) = Store::open_in_memory() else {
panic!("in-memory store should open");
};
let Ok(_) = store.ingest(&[record(LedgerLane::DeveloperTool, 100)]) else {
panic!("ingest should succeed");
};
let Ok(_) = store.conn.execute(
&format!("UPDATE {USAGE_ROWS_TABLE} SET x_lane = 'not_a_lane'"),
[],
) else {
panic!("update should succeed");
};
match store.all_focus_rows() {
Err(StoreError::Reconstruct(msg)) => {
assert!(
msg.contains("x_lane"),
"error should name the bad column: {msg}"
);
}
other => panic!("expected a Reconstruct error, got {other:?}"),
}
}
}