Skip to content

The agent that grows with you

feat: receipt worker main and auxiliary usage in canonical transactions

Teknium9d896c499b03
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 2166cd3c4f4..ac06c8056fb 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -501,11 +501,38 @@ def _worker_turn(db, conn, session_id, payload, operation):
return {'value': value}
+def _worker_usage(db, conn, session_id, payload, *, auxiliary=False):
+ from hermes_state_usage import _MODEL_USAGE_FIELDS, _TOKEN_COUNTERS
+ allowed = (_MODEL_USAGE_FIELDS - {'billing_mode', 'actual_cost_usd', 'cost_status', 'cost_source'} | {'task'}) if auxiliary else (_MODEL_USAGE_FIELDS | {'pricing_version', 'absolute'})
+ if set(payload) - allowed:
+ raise RuntimeStoreError('invalid_params')
+ for key, value in payload.items():
+ if key in (*_TOKEN_COUNTERS, 'api_call_count'):
+ valid = type(value) is int and 0 <= value <= 2**53
+ elif key in ('estimated_cost_usd', 'actual_cost_usd'):
+ valid = value is None or (type(value) in (int, float) and 0 <= value <= 1e12)
+ elif key == 'absolute':
+ valid = type(value) is bool
+ else:
+ valid = value is None or (isinstance(value, str) and len(value) <= 4096)
+ if not valid:
+ raise RuntimeStoreError('invalid_params')
+ if auxiliary:
+ if not payload.get('task'):
+ raise RuntimeStoreError('invalid_params')
+ db._record_model_usage(conn, session_id, **({'api_call_count': 1} | payload))
+ else:
+ db._update_token_counts_in_transaction(conn, session_id, **payload)
+ return {'value': None}
+
+
def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,
sequence, operation, payload):
"""One closed durable mutation and receipt; never call a self-committing API here."""
handlers = {
'transcript.append': _worker_append,
+ 'usage.main': _worker_usage,
+ 'usage.auxiliary': lambda db, conn, sid, p: _worker_usage(db, conn, sid, p, auxiliary=True),
**{name: (lambda db, conn, sid, p, op=name: _worker_turn(db, conn, sid, p, op))
for name in ('turn.acquire', 'turn.renew', 'turn.release')},
}
diff --git a/hermes_state_usage.py b/hermes_state_usage.py
index f272b760702..3f7549cbfca 100644
--- a/hermes_state_usage.py
+++ b/hermes_state_usage.py
@@ -279,13 +279,21 @@ class SessionUsageMixin:
pricing_version: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None,
billing_mode: Optional[str]=None, api_call_count: int=0, absolute: bool=False,
) -> None:
- """Update token counters and backfill model if unset. *absolute*=False increments
- (per-API-call deltas, CLI path); *absolute*=True sets directly (gateway path,
- where the cached agent holds cumulative totals)."""
- usage = {k: v for k, v in locals().items() if k in _MODEL_USAGE_FIELDS}
- # Ensure the row exists: under concurrent load create_session() may have failed on
- # locking, and the UPDATE would silently affect 0 rows.
+ """Update totals and route attribution, ensuring the legacy missing-row backfill."""
+ values = dict(locals())
+ values.pop('self')
+ values.pop('session_id')
self._insert_session_row(session_id, "unknown", model=model)
+ self._execute_write(lambda conn: self._update_token_counts_in_transaction(conn, session_id, **values))
+
+ def _update_token_counts_in_transaction(
+ self, conn, session_id: str, input_tokens: int=0, output_tokens: int=0, model: str=None, cache_read_tokens: int=0,
+ cache_write_tokens: int=0, reasoning_tokens: int=0, estimated_cost_usd: Optional[float]=None,
+ actual_cost_usd: Optional[float]=None, cost_status: Optional[str]=None, cost_source: Optional[str]=None,
+ pricing_version: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None,
+ billing_mode: Optional[str]=None, api_call_count: int=0, absolute: bool=False,
+ ) -> None:
+ usage = {k: v for k, v in locals().items() if k in _MODEL_USAGE_FIELDS}
sql = _TOKEN_UPDATE_ABSOLUTE_SQL if absolute else _TOKEN_UPDATE_DELTA_SQL
has_usage = bool(input_tokens or output_tokens or cache_read_tokens or cache_write_tokens or reasoning_tokens
or api_call_count or estimated_cost_usd)
@@ -308,28 +316,26 @@ class SessionUsageMixin:
# of how many times the user switches. See #51607.
record_model_usage = (not absolute) and has_usage
- def _do(conn):
- row = conn.execute(
- "SELECT model, billing_provider, api_call_count FROM sessions WHERE id = ?", (session_id,),
- ).fetchone()
- existing = dict(row) if row is not None else {}
- # create_session records the requested route before any API call. If that fails
- # and fallback succeeds, the first accounted usage is the authoritative route;
- # after that keep the row as is (one row cannot represent mixed usage).
- first_accounted_route = (
- int(existing.get("api_call_count") or 0) == 0 and has_accounted_usage and bool(model)
- and bool(billing_provider)
- and (existing.get("model") != model or existing.get("billing_provider") != billing_provider)
- )
- if first_accounted_route:
- conn.execute("""UPDATE sessions
- SET model = ?, billing_provider = ?,
- billing_base_url = ?, billing_mode = ?
- WHERE id = ?""", (model, billing_provider, billing_base_url, billing_mode, session_id))
- conn.execute(sql, params)
- if record_model_usage:
- self._record_model_usage(conn, session_id, **usage)
- self._execute_write(_do)
+ row = conn.execute(
+ "SELECT model, billing_provider, api_call_count FROM sessions WHERE id = ?", (session_id,),
+ ).fetchone()
+ existing = dict(row) if row is not None else {}
+ # create_session records the requested route before any API call. If that fails
+ # and fallback succeeds, the first accounted usage is the authoritative route;
+ # after that keep the row as is (one row cannot represent mixed usage).
+ first_accounted_route = (
+ int(existing.get("api_call_count") or 0) == 0 and has_accounted_usage and bool(model)
+ and bool(billing_provider)
+ and (existing.get("model") != model or existing.get("billing_provider") != billing_provider)
+ )
+ if first_accounted_route:
+ conn.execute("""UPDATE sessions
+ SET model = ?, billing_provider = ?,
+ billing_base_url = ?, billing_mode = ?
+ WHERE id = ?""", (model, billing_provider, billing_base_url, billing_mode, session_id))
+ conn.execute(sql, params)
+ if record_model_usage:
+ self._record_model_usage(conn, session_id, **usage)
def _record_model_usage(
self, conn, session_id: str, *, model: Optional[str]=None, billing_provider: Optional[str]=None,
diff --git a/tests/state/test_runtime_worker_usage.py b/tests/state/test_runtime_worker_usage.py
new file mode 100644
index 00000000000..ee30b0b1a07
--- /dev/null
+++ b/tests/state/test_runtime_worker_usage.py
@@ -0,0 +1,37 @@
+import sqlite3
+import pytest
+from hermes_state import SessionDB
+import hermes_state_runtime as rt
+
+
+def test_usage_receipt_includes_route_rows_and_rolls_back_on_receipt_failure(tmp_path):
+ db = SessionDB(tmp_path / 'state.db')
+ try:
+ db.create_session('s', source='cli')
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ scope = dict(epoch=epoch, execution_id='w', session_id='s', generation=0)
+ rt.register_worker_execution(db, **scope, kind='compute', adoption_secret='private')
+ payload = {'input_tokens': 13, 'output_tokens': 7, 'api_call_count': 1,
+ 'model': 'model-a', 'billing_provider': 'provider', 'estimated_cost_usd': 0.25}
+ args = dict(**scope, sequence=1, operation='usage.main', payload=payload)
+ receipt = rt.mutate_worker_execution(db, **args)
+ assert rt.mutate_worker_execution(db, **args) == receipt
+ assert db.get_session('s')['input_tokens'] == 13
+ with db._read_ctx() as conn:
+ assert conn.execute('SELECT input_tokens FROM session_model_usage').fetchone()[0] == 13
+ db._execute_write(lambda c: c.execute("CREATE TRIGGER deny_receipt BEFORE INSERT ON worker_receipts BEGIN SELECT RAISE(ABORT, 'deny receipt'); END"))
+ with pytest.raises(sqlite3.IntegrityError, match='deny receipt'):
+ rt.mutate_worker_execution(db, **(args | {'sequence': 2}))
+ assert db.get_session('s')['input_tokens'] == 13
+ db._execute_write(lambda c: c.execute('DROP TRIGGER deny_receipt'))
+ aux = dict(**scope, sequence=2, operation='usage.auxiliary',
+ payload={'task': 'compression', 'model': 'aux', 'input_tokens': 3})
+ rt.mutate_worker_execution(db, **aux)
+ rt.mutate_worker_execution(db, **aux)
+ assert db.get_session('s')['input_tokens'] == 13
+ with db._read_ctx() as conn:
+ assert conn.execute("SELECT input_tokens FROM session_model_usage WHERE task='compression'").fetchone()[0] == 3
+ with pytest.raises(rt.RuntimeStoreError, match='invalid_params'):
+ rt.mutate_worker_execution(db, **(args | {'sequence': 3, 'payload': {'input_tokens': -1}}))
+ finally:
+ db.close()