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 Enamakel5d5cef7b548f
diff --git a/crates/openhuman-core/src/platform/cost/mod.rs b/crates/openhuman-core/src/platform/cost/mod.rs
index 90d70a50fd..c51f4cbf58 100644
--- a/crates/openhuman-core/src/platform/cost/mod.rs
+++ b/crates/openhuman-core/src/platform/cost/mod.rs
@@ -8,6 +8,7 @@ mod schemas;
pub mod scope;
pub mod tools;
pub mod tracker;
+mod tracker_documents;
pub mod types;
pub use global::{
diff --git a/crates/openhuman-core/src/platform/cost/tracker.rs b/crates/openhuman-core/src/platform/cost/tracker.rs
index 672a54c84d..3008191d7c 100644
--- a/crates/openhuman-core/src/platform/cost/tracker.rs
+++ b/crates/openhuman-core/src/platform/cost/tracker.rs
@@ -455,7 +455,11 @@ struct CostStorage {
impl CostStorage {
/// Create or open cost storage.
fn new(path: &Path) -> Result<Self> {
- if let Some(parent) = path.parent() {
+ // With a storage backend the ledger lives in documents under the
+ // acting agent's scope, which is only known per call: no directory to
+ // make, and no aggregate to prime here.
+ let documents = crate::storage::installed().is_some();
+ if let Some(parent) = path.parent().filter(|_| !documents) {
fs::create_dir_all(parent)
.with_context(|| format!("Failed to create directory {}", parent.display()))?;
}
@@ -472,11 +476,13 @@ impl CostStorage {
cached_month: now.month(),
};
- storage.rebuild_aggregates(
- storage.cached_day,
- storage.cached_year,
- storage.cached_month,
- )?;
+ if !documents {
+ storage.rebuild_aggregates(
+ storage.cached_day,
+ storage.cached_year,
+ storage.cached_month,
+ )?;
+ }
Ok(storage)
}
@@ -485,6 +491,15 @@ impl CostStorage {
where
F: FnMut(CostRecord),
{
+ if let Some(docs) = super::tracker_documents::current()? {
+ for record in docs.all()? {
+ if !is_legacy_host_duplicate(&record) {
+ on_record(record);
+ }
+ }
+ return Ok(());
+ }
+
if !self.path.exists() {
return Ok(());
}
@@ -576,6 +591,13 @@ impl CostStorage {
/// Add a new record.
fn add_record(&mut self, record: CostRecord) -> Result<()> {
+ // The period aggregates are one cache for the whole process, so they
+ // are not kept for a document ledger, whose scope changes per call;
+ // `get_aggregated_costs` recomputes them from the scope's records.
+ if let Some(docs) = super::tracker_documents::current()? {
+ return docs.add(&record);
+ }
+
if let Some(parent) = self.path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("Failed to create directory {}", parent.display()))?;
@@ -617,6 +639,11 @@ impl CostStorage {
/// [`Self::get_aggregated_managed_costs`] for anything that gates a
/// request.
fn get_aggregated_costs(&mut self) -> Result<(f64, f64)> {
+ if super::tracker_documents::current()?.is_some() {
+ let now = Utc::now();
+ self.rebuild_aggregates(now.date_naive(), now.year(), now.month())?;
+ return Ok((self.daily_cost_usd, self.monthly_cost_usd));
+ }
self.ensure_period_cache_current()?;
Ok((self.daily_cost_usd, self.monthly_cost_usd))
}
diff --git a/crates/openhuman-core/src/platform/cost/tracker_documents.rs b/crates/openhuman-core/src/platform/cost/tracker_documents.rs
new file mode 100644
index 0000000000..8d420802a1
--- /dev/null
+++ b/crates/openhuman-core/src/platform/cost/tracker_documents.rs
@@ -0,0 +1,89 @@
+//! The cost ledger on the `tinystoragedrivers` document port.
+//!
+//! Used instead of `state/costs.jsonl` when the host configured a storage
+//! backend ([`crate::storage`]); `CostStorage` in `tracker.rs` picks it per
+//! call, so records live under the acting agent's storage scope (`local` on a
+//! single-user host). Without a backend the JSONL file at today's path is
+//! used unchanged.
+//!
+//! # Layout
+//!
+//! | Collection | Document id | Holds |
+//! | --- | --- | --- |
+//! | `cost_records` | record id | one [`CostRecord`], plus `ts_ms` (epoch ms) for ordering |
+//!
+//! 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 super::types::CostRecord;
+use crate::storage::documents::Repo;
+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"]))]
+}
+
+/// The document store for this call, when the host configured one.
+pub(super) fn current() -> Result<Option<CostDocs>> {
+ Ok(Repo::current(DOMAIN, collections)?.map(CostDocs))
+}
+
+/// The cost ledger over one scoped document handle.
+pub(super) struct CostDocs(Repo);
+
+impl CostDocs {
+ #[cfg(test)]
+ pub(super) fn over(scoped: &crate::storage::ScopedStorage) -> Self {
+ Self(Repo::over(scoped, DOMAIN, collections))
+ }
+
+ /// 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();
+ log::trace!("[cost::tracker] document add id={id}");
+ self.0.run(|docs| async move {
+ docs.put(RECORDS, &id, doc, Precondition::Absent)
+ .await
+ .map(|_| ())
+ })
+ }
+
+ /// Every record, oldest first. Documents that no longer parse are skipped
+ /// with a warning, as malformed ledger lines are.
+ pub(super) fn all(&self) -> Result<Vec<CostRecord>> {
+ let stored = self.0.run(|docs| async move {
+ docs.query_all(
+ RECORDS,
+ &Query::all().sort(Sort::asc("ts_ms")).sort(Sort::asc("_id")),
+ )
+ .await
+ })?;
+ Ok(stored
+ .into_iter()
+ .filter_map(|item| match serde_json::from_value(item.doc) {
+ Ok(record) => Some(record),
+ Err(error) => {
+ log::warn!(
+ "[cost::tracker] skipping malformed cost document id={} error={error}",
+ item.id
+ );
+ None
+ }
+ })
+ .collect())
+ }
+}
+
+#[cfg(test)]
+#[path = "tracker_documents_tests.rs"]
+mod tests;