Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(cost): track document processing costs

Steven Enamakel29f6f2fc1570
diff --git a/crates/openhuman-core/src/platform/cost/storage_schema.rs b/crates/openhuman-core/src/platform/cost/storage_schema.rs
new file mode 100644
index 0000000000..136d1de0ea
--- /dev/null
+++ b/crates/openhuman-core/src/platform/cost/storage_schema.rs
@@ -0,0 +1,85 @@
+//! The `cost` owner's storage schema: the usage ledger and the step that
+//! brings the v1 collection forward.
+//!
+//! | v1 | v2 | change |
+//! |---|---|---|
+//! | `cost_records` (`usage.timestamp` RFC 3339 beside `ts_ms`) | `cost.records` | `usage.timestamp` dropped; `ts_ms` is the instant |
+
+use serde_json::Value;
+use tinystoragedrivers::schema::{Schema, ScopeClass, SourceRecord, Step, TargetRecord};
+use tinystoragedrivers::{CollectionSpec, IndexSpec, Result};
+
+use super::types::CostRecord;
+use crate::storage::schema_support::{key_of, owner, rfc3339_ms};
+
+pub(super) const RECORDS: &str = "cost.records";
+pub(super) const LEGACY_RECORDS: &str = "cost_records";
+const SCHEMA: u32 = 2;
+
+/// What the cost ledger keeps and the step from the v1 collection.
+#[must_use]
+pub fn storage_schema() -> Schema {
+ Schema::new(owner("cost"))
+ .collection_with(SCHEMA, spec(), ScopeClass::Tenant)
+ .step(Step::new("records_v2", RECORDS, 1, SCHEMA, records_v2).source(LEGACY_RECORDS))
+}
+
+pub(super) fn spec() -> CollectionSpec {
+ CollectionSpec::new(RECORDS).index(IndexSpec::new("by_time", ["ts_ms"]))
+}
+
+/// A record as its stored body: its fields with the usage timestamp carried
+/// once, as `ts_ms`.
+///
+/// # Errors
+///
+/// When the record does not serialize.
+pub(super) fn to_body(record: &CostRecord) -> anyhow::Result<Value> {
+ let mut doc = serde_json::to_value(record)?;
+ if let Some(usage) = doc.get_mut("usage").and_then(Value::as_object_mut) {
+ usage.remove("timestamp");
+ }
+ doc["ts_ms"] = record.usage.timestamp.timestamp_millis().into();
+ Ok(doc)
+}
+
+/// The record a stored body holds.
+///
+/// # Errors
+///
+/// When the body is not a record.
+pub(super) fn from_body(mut doc: Value) -> anyhow::Result<CostRecord> {
+ let ts_ms = doc.get("ts_ms").and_then(Value::as_i64).unwrap_or_default();
+ let at = chrono::DateTime::from_timestamp_millis(ts_ms).unwrap_or_default();
+ if let Some(usage) = doc.get_mut("usage").and_then(Value::as_object_mut) {
+ usage.insert("timestamp".into(), serde_json::json!(at));
+ }
+ Ok(serde_json::from_value(doc)?)
+}
+
+fn records_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {
+ batch
+ .into_iter()
+ .map(|record| {
+ let mut body = record.body;
+ let stamped = body
+ .pointer("/usage/timestamp")
+ .and_then(Value::as_str)
+ .and_then(rfc3339_ms);
+ let ts_ms = body
+ .get("ts_ms")
+ .and_then(Value::as_i64)
+ .or(stamped)
+ .unwrap_or(record.meta.created_ms);
+ if let Some(usage) = body.get_mut("usage").and_then(Value::as_object_mut) {
+ usage.remove("timestamp");
+ }
+ body["ts_ms"] = ts_ms.into();
+ Ok(TargetRecord::new(RECORDS, key_of(&record.id)?, body).created_ms(ts_ms))
+ })
+ .collect()
+}
+
+#[cfg(test)]
+#[path = "storage_schema_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/platform/cost/storage_schema_tests.rs b/crates/openhuman-core/src/platform/cost/storage_schema_tests.rs
new file mode 100644
index 0000000000..74a0559a91
--- /dev/null
+++ b/crates/openhuman-core/src/platform/cost/storage_schema_tests.rs
@@ -0,0 +1,63 @@
+use super::*;
+use serde_json::json;
+use tinystoragedrivers::Meta;
+
+fn source(id: &str, body: Value) -> SourceRecord {
+ SourceRecord {
+ id: id.to_string(),
+ body,
+ meta: Meta::unknown(),
+ }
+}
+
+#[test]
+fn the_usage_timestamp_is_carried_once_as_milliseconds() {
+ let out = records_v2(vec![source(
+ "r1",
+ json!({
+ "id": "r1", "session_id": "s",
+ "usage": { "model": "m", "timestamp": "1970-01-01T00:00:02Z", "cost_usd": 0.5 },
+ "ts_ms": 2000,
+ }),
+ )])
+ .unwrap();
+ assert_eq!(out[0].collection, RECORDS);
+ assert_eq!(out[0].id, "r1");
+ assert_eq!(
+ out[0].body,
+ json!({
+ "id": "r1", "session_id": "s",
+ "usage": { "model": "m", "cost_usd": 0.5 },
+ "ts_ms": 2000,
+ })
+ );
+}
+
+#[test]
+fn a_row_without_ts_ms_takes_it_from_the_timestamp() {
+ let out = records_v2(vec![source(
+ "r2",
+ json!({ "id": "r2", "session_id": "s", "usage": { "timestamp": "1970-01-01T00:00:03Z" } }),
+ )])
+ .unwrap();
+ assert_eq!(out[0].body["ts_ms"], 3000);
+}
+
+#[test]
+fn a_record_round_trips_through_its_body() {
+ let usage = super::super::types::TokenUsage::new("m", 10, 5, 1.0, 2.0);
+ let record = CostRecord::new("s", usage);
+ let body = to_body(&record).unwrap();
+ assert!(body["usage"].get("timestamp").is_none());
+ let back = from_body(body).unwrap();
+ assert_eq!(back.id, record.id);
+ assert_eq!(
+ back.usage.timestamp.timestamp_millis(),
+ record.usage.timestamp.timestamp_millis()
+ );
+}
+
+#[test]
+fn the_schema_composes_under_its_owner() {
+ tinystoragedrivers::schema::Registry::compose([storage_schema()]).unwrap();
+}
diff --git a/crates/openhuman-core/src/platform/cost/tracker_documents.rs b/crates/openhuman-core/src/platform/cost/tracker_documents.rs
index 6226e88e5b..7f3434220a 100644
--- a/crates/openhuman-core/src/platform/cost/tracker_documents.rs
+++ b/crates/openhuman-core/src/platform/cost/tracker_documents.rs
@@ -10,25 +10,25 @@
//!
//! | Collection | Document id | Holds |
//! | --- | --- | --- |
-//! | `cost_records` | record id | one [`CostRecord`], plus `ts_ms` (epoch ms) for ordering |
+//! | `cost.records` | `Key::of([record id])` | one [`CostRecord`], its usage timestamp carried once as `ts_ms` (epoch ms, [`super::storage_schema`]) |
//!
//! The JSONL ledger is append-only, so a record is written once
//! (`Precondition::Absent`) and never edited. Readers get the records oldest
//! first, the order the file kept them in.
use anyhow::{Context, Result};
-use serde_json::Value;
-use tinystoragedrivers::{CollectionSpec, IndexSpec, Precondition, Query, Sort};
+use tinystoragedrivers::{CollectionSpec, Precondition, Query, Sort};
+use super::storage_schema::{from_body, spec, to_body, RECORDS};
use super::types::CostRecord;
use crate::storage::documents::Repo;
+use crate::storage::schema_support::key_of;
use crate::storage::DocumentStoreExt;
-const RECORDS: &str = "cost_records";
const DOMAIN: &str = "cost::tracker";
fn collections() -> Vec<CollectionSpec> {
- vec![CollectionSpec::new(RECORDS).index(IndexSpec::new("by_time", ["ts_ms"]))]
+ vec![spec()]
}
/// The document store for this call: the installed backend, else the
@@ -72,9 +72,8 @@ impl CostDocs {
/// Appends one record.
pub(super) fn add(&self, record: &CostRecord) -> Result<()> {
- let mut doc = serde_json::to_value(record).context("serialize cost record")?;
- doc["ts_ms"] = Value::from(record.usage.timestamp.timestamp_millis());
- let id = record.id.clone();
+ let doc = to_body(record).context("serialize cost record")?;
+ let id = key_of(&record.id)?;
log::trace!("[cost::tracker] document add id={id}");
self.0.run(|docs| async move {
docs.put(RECORDS, &id, doc, Precondition::Absent)
@@ -138,9 +137,8 @@ impl CostDocs {
/// Writes `record` unless its id is already stored; `false` when it was.
fn add_if_absent(&self, record: &CostRecord) -> Result<bool> {
- let mut doc = serde_json::to_value(record).context("serialize cost record")?;
- doc["ts_ms"] = Value::from(record.usage.timestamp.timestamp_millis());
- let id = record.id.clone();
+ let doc = to_body(record).context("serialize cost record")?;
+ let id = key_of(&record.id)?;
self.0.run(|docs| async move {
match docs.put(RECORDS, &id, doc, Precondition::Absent).await {
Ok(_) => Ok(true),
@@ -162,7 +160,7 @@ impl CostDocs {
})?;
Ok(stored
.into_iter()
- .filter_map(|item| match serde_json::from_value(item.doc) {
+ .filter_map(|item| match from_body(item.doc) {
Ok(record) => Some(record),
Err(error) => {
log::warn!(