Skip to content

The agent that grows with you

fix(gateway): carry billing and turn-end usage across a managed worker turn

yoniebansfcaddb248d4c
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index 73e12870381..f9843d74c36 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -35,23 +35,42 @@ RESULT_FIELDS = ('final_response', 'failed', 'interrupted', 'completed', 'partia
'api_calls', 'model', 'provider', 'prompt_tokens', 'completion_tokens', 'total_tokens',
'cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens',
'estimated_cost_usd', 'cost_status', 'cost_source', 'service_tier', 'failure_reason',
- 'session_id', 'requested_model', 'served_model', '_turn_input_tokens', '_turn_output_tokens')
+ 'session_id', 'requested_model', 'served_model', '_turn_input_tokens', '_turn_output_tokens',
+ 'billing_block')
+# ``billing_block`` (``agent/billing_links.BillingBlock`` plus ``unverified``) is the one structured field.
+BILLING_FIELDS = ('provider', 'provider_label', 'model', 'billing_url', 'is_nous', 'message', 'unverified')
+
+
+def _scalar(value):
+ return value is None or type(value) in (bool, int, float) or (isinstance(value, str) and len(value) <= 4096)
+
+
+def _billing_block(value):
+ return isinstance(value, dict) and not set(value) - set(BILLING_FIELDS) and all(map(_scalar, value.values()))
def result_frame(result):
"""Worker side: the receipt fields of ``run_conversation``'s result, scalars only, text bounded."""
- return {k: (v[:4096] if isinstance(v, str) and k != 'final_response' else v) for k, v in result.items()
- if k in RESULT_FIELDS and (v is None or type(v) in (bool, int, float, str))}
+ frame = {k: (v[:4096] if isinstance(v, str) and k != 'final_response' else v) for k, v in result.items()
+ if k in RESULT_FIELDS and k != 'billing_block' and (v is None or type(v) in (bool, int, float, str))}
+ block = result.get('billing_block')
+ if isinstance(block, dict):
+ frame['billing_block'] = {k: v[:4096] if isinstance(v, str) else v for k, v in block.items()
+ if k in BILLING_FIELDS and (v is None or type(v) in (bool, int, float, str))}
+ return frame
def accept_result(result):
"""Owner side of the worker's result frame: ``(result, usage)`` in the in-process turn's shape
(gateway projection: prompt/completion tokens as input/output), or ValueError."""
if (not isinstance(result, dict) or set(result) - set(RESULT_FIELDS) or not isinstance(result.get('final_response'), str)
- or any(not (value is None or type(value) in (bool, int, float) or (isinstance(value, str) and len(value) <= 4096))
- for key, value in result.items() if key != 'final_response')):
+ or result.get('billing_block') is not None and not _billing_block(result['billing_block'])
+ or any(not _scalar(value) for key, value in result.items() if key not in ('final_response', 'billing_block'))):
raise ValueError('invalid_worker_result')
accepted = dict(result)
+ if accepted.get('billing_block') is None:
+ # Every failure other than a billing wall carries no block.
+ accepted.pop('billing_block', None)
turn_in, turn_out = accepted.pop('_turn_input_tokens', None), accepted.pop('_turn_output_tokens', None)
if any(value is not None and (type(value) is not int or value < 0) for value in (turn_in, turn_out)):
raise ValueError('invalid_worker_result')
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 587071d9eb2..4ff71708965 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -450,6 +450,59 @@ def _interrupted_before_bootstrap(authority, row):
return ''
+def _settled_session_usage(authority, session_id, accepted, execution_id=None):
+ """A managed turn's ``message.complete.usage``: the worker exits with its turn, so the session-cumulative counters come from the rows its usage writes committed. A worker that compresses mid-turn ends on a child of this reservation's session; the owner's execution row records that tip (compression moves it in the same transaction), so the path from the tip back to the reservation plus the reservation's own compression ancestors is summed, and stale siblings or the conversation a branch came from never count."""
+ import sqlite3
+ db = authority.db
+ try:
+ tip = _execution_tip(db, execution_id)
+ path = _continuation_path(db, session_id, tip) if tip and tip != session_id else None
+ ids = list(dict.fromkeys([*_compression_ancestors(db, session_id), *(path or [session_id])]))
+ rows = [db.get_session(sid) or {} for sid in ids]
+ except sqlite3.Error: # usage is display-only; settlement never waits on it
+ return {}
+ counts = {key: sum(int(row.get(key) or 0) for row in rows) for key in (
+ 'input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens')}
+ prompt = counts['input_tokens'] + counts['cache_read_tokens'] + counts['cache_write_tokens']
+ return {'session_usage': {**counts, 'prompt_tokens': prompt, 'completion_tokens': counts['output_tokens'],
+ 'total_tokens': prompt + counts['output_tokens'],
+ 'api_calls': sum(int(row.get('api_call_count') or 0) for row in rows),
+ 'model': str(accepted.get('model') or rows[-1].get('model') or '')}}
+
+
+def _execution_tip(db, execution_id):
+ """The session this worker execution last wrote to, as the owner's ledger records it."""
+ if not execution_id:
+ return None
+ with db._read_ctx() as conn:
+ row = conn.execute('SELECT session_id FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()
+ return row[0] if row else None
+
+
+def _continuation_path(db, start, tip):
+ """Ids from *start* to *tip* when *tip* reaches *start* through compression continuations only, else None."""
+ path, current = [tip], tip
+ while current != start and len(path) <= 200:
+ row = db.get_session(current)
+ if not row or not db._is_compression_child_row(row):
+ return None
+ current = row['parent_session_id']
+ path.append(current)
+ return path[::-1] if current == start else None
+
+
+def _compression_ancestors(db, session_id):
+ """Root-first ids of the sessions *session_id* continues by compression, excluding itself."""
+ ancestors, current = [], db.get_session(session_id)
+ while current and db._is_compression_child_row(current) and len(ancestors) < 200:
+ parent = current['parent_session_id']
+ if parent in ancestors or parent == session_id:
+ break
+ ancestors.append(parent)
+ current = db.get_session(parent)
+ return ancestors[::-1]
+
+
async def execute_managed(authority, ref, row, policy):
from gateway.run_turn_progress import publish_worker_tool_event
# This route never passes the inbound prepare step, so the worker would read ``@`` tokens as typed.
@@ -531,7 +584,9 @@ async def execute_managed(authority, ref, row, policy):
with suppress(subprocess.TimeoutExpired):
await asyncio.to_thread(process.wait, 10)
# Like in-process execution, settlement belongs to the drain's stream lock.
- authority.pending_results[row['admission_id']] = {'result': accepted, 'usage': usage}
+ authority.pending_results[row['admission_id']] = {
+ 'result': {**accepted, 'local_viewer': True}, 'usage': usage,
+ **await asyncio.to_thread(_settled_session_usage, authority, scope['session_id'], accepted, scope['execution_id'])}
return accepted['final_response']
raise RuntimeStoreError('invalid_worker_frame')
except (Exception, asyncio.CancelledError) as exc:
diff --git a/tests/gateway/test_managed_worker_finished_exit.py b/tests/gateway/test_managed_worker_finished_exit.py
index 6750722a68d..0a3c5824a61 100644
--- a/tests/gateway/test_managed_worker_finished_exit.py
+++ b/tests/gateway/test_managed_worker_finished_exit.py
@@ -20,7 +20,9 @@ send({'type': 'hello', 'pid': me.pid, 'birth': me.create_time(), 'ancestors': [p
for line in sys.stdin.buffer:
frame = json.loads(line)
if 'version' in frame:
- send({'type': 'result', 'result': {'final_response': 'FINISHED_ANSWER'}})
+ send({'type': 'result', 'result': {'final_response': 'FINISHED_ANSWER', 'model': 'm', 'failure_reason': 'billing',
+ 'billing_block': {'provider': 'custom', 'provider_label': 'Custom', 'model': 'm', 'billing_url': None,
+ 'is_nous': False, 'message': 'Add credits'}}})
elif frame == {'type': 'finish'}:
send({'type': 'finished'})
break
@@ -31,8 +33,8 @@ time.sleep(60) # interpreter teardown that outlives the owner's exit wait
@pytest.mark.platforms("linux")
[email protected]('exit_shape', ['nonzero', 'lingering'])
-def test_finished_worker_keeps_its_result_on_slow_or_nonzero_exit(tmp_path, monkeypatch, exit_shape):
[email protected](('exit_shape', 'rotate'), [('nonzero', False), ('lingering', False), ('nonzero', True)])
+def test_finished_worker_keeps_its_result_on_slow_or_nonzero_exit(tmp_path, monkeypatch, exit_shape, rotate):
from gateway import session_managed_worker as managed
from gateway.session_authority import LiveSession, SessionAuthority
from gateway.session_contract import Submission
@@ -43,6 +45,8 @@ def test_finished_worker_keeps_its_result_on_slow_or_nonzero_exit(tmp_path, monk
monkeypatch.setenv('HERMES_HOME', str(tmp_path))
db = SessionDB(db_path=tmp_path / 'state.db')
db.create_session('s', source='test')
+ # The worker's per-call usage writes, already committed by the time it reports 'finished'.
+ db.update_token_counts('s', input_tokens=200, output_tokens=50, cache_read_tokens=800, api_call_count=3, model='m')
runner = SimpleNamespace(_draining=False, _cached_agent_for=lambda route: None,
_adapter_for_source=lambda source: None)
authority = SessionAuthority(runner, profile_id='owned', instance_id='i', db=db,
@@ -58,6 +62,20 @@ def test_finished_worker_keeps_its_result_on_slow_or_nonzero_exit(tmp_path, monk
super().__init__([sys.executable, '-c', CHILD, exit_shape], **kw)
spawned.append(self)
monkeypatch.setattr(managed.subprocess, 'Popen', Child)
+ if rotate:
+ reserve = managed.reserve_admission_worker
+
+ def reserve_then_compress(authority, **kwargs):
+ # A worker compression mid-turn: the transcript continues in a child session and the owner's
+ # execution row follows it in the same transaction (hermes_state_worker_compression.py).
+ scope = reserve(authority, **kwargs)
+ db.end_session('s', 'compression')
+ db.create_session('s-c1', source='test', parent_session_id='s')
+ db._execute_write(lambda conn: conn.execute('UPDATE worker_executions SET session_id=? WHERE execution_id=?',
+ ('s-c1', scope['execution_id'])))
+ db.update_token_counts('s-c1', input_tokens=100, output_tokens=10, api_call_count=1, model='m')
+ return scope
+ monkeypatch.setattr(managed, 'reserve_admission_worker', reserve_then_compress)
policy = build_policy({'cwd': str(tmp_path), 'model': 'm'}, {}, profile_terminal=False)
async def scenario():
@@ -70,6 +88,17 @@ def test_finished_worker_keeps_its_result_on_slow_or_nonzero_exit(tmp_path, monk
row, response = asyncio.run(scenario())
status = db._read_one('SELECT status FROM session_admissions WHERE admission_id=?', (row['admission_id'],))[0]
assert response == 'FINISHED_ANSWER'
- assert authority.pending_results[row['admission_id']]['result']['final_response'] == 'FINISHED_ANSWER'
+ captured = authority.pending_results[row['admission_id']]
+ assert captured['result']['final_response'] == 'FINISHED_ANSWER'
assert status == 'started', 'the finished turn was marked unknown instead of reaching settlement'
assert spawned[0].poll() is not None, "close() did not reap the worker"
+ # A local viewer's message.complete gets the billing banner and turn-end usage, as in process.
+ from gateway.session_settlement_recovery import completion_payload
+ complete = completion_payload(row, {'outcome': 'completed'}, response, captured)
+ assert complete['billing']['message'] == 'Add credits' and complete['failure_reason'] == 'billing'
+ if rotate:
+ assert complete['usage'] == {'model': 'm', 'input': 300, 'output': 60, 'reasoning': 0, 'prompt': 1100,
+ 'completion': 60, 'total': 1160, 'calls': 4, 'cache_hit_pct': 73}
+ else:
+ assert complete['usage'] == {'model': 'm', 'input': 200, 'output': 50, 'reasoning': 0, 'prompt': 1000,
+ 'completion': 50, 'total': 1050, 'calls': 3, 'cache_hit_pct': 80}
diff --git a/tests/gateway/test_managed_worker_result_usage.py b/tests/gateway/test_managed_worker_result_usage.py
index 8f2c172216f..4ed751eb52b 100644
--- a/tests/gateway/test_managed_worker_result_usage.py
+++ b/tests/gateway/test_managed_worker_result_usage.py
@@ -31,9 +31,116 @@ def test_worker_result_frame_carries_the_usage_ledger():
assert result['estimated_cost_usd'] == 0.0125 and result['turn_exit_reason'].startswith('text_response')
assert len(result['error']) == 4096 and 'messages' not in result and 'base_url' not in result
# Unknown or non-scalar fields are refused at the owner boundary.
- for bad in ({'final_response': 'x', 'messages': []}, {'final_response': 'x', 'model': ['m']}, {'failed': True}):
+ for bad in ({'final_response': 'x', 'messages': []}, {'final_response': 'x', 'model': ['m']}, {'failed': True},
+ {'final_response': 'x', 'billing_block': {'provider': 'p', 'extra': 1}},
+ {'final_response': 'x', 'billing_block': {'message': {'nested': 'no'}}},
+ {'final_response': 'x', 'billing_block': 'not a dict'}):
try:
accept_result(bad)
except ValueError:
continue
raise AssertionError(bad)
+
+
+def test_failed_non_billing_turn_with_no_billing_block_is_accepted():
+ """Turns that fail for any reason other than a billing wall return ``billing_block: None``; the owner accepts that frame instead of reading it as a lost worker."""
+ raw = {**_run_conversation_result(), 'failed': True, 'completed': False, 'failure_reason': 'rate_limit', 'billing_block': None}
+ wire = read_frame(io.BytesIO(encode_frame({'type': 'result', 'result': result_frame(raw)})))
+ result, _usage = accept_result(wire['result'])
+ assert result['failure_reason'] == 'rate_limit' and 'billing_block' not in result
+ accepted, _ = accept_result({'final_response': 'x', 'billing_block': None})
+ assert 'billing_block' not in accepted
+
+
+def test_worker_result_frame_carries_the_billing_block():
+ """A billing-blocked managed turn hands the owner the same structured block the in-process turn returns, so a local viewer's message.complete can carry ``billing``."""
+ block = {'provider': 'custom', 'provider_label': 'Custom', 'model': 'm', 'billing_url': None,
+ 'is_nous': False, 'message': 'Add credits', 'unverified': True, 'internal': object()}
+ raw = {**_run_conversation_result(), 'failed': True, 'failure_reason': 'billing', 'billing_block': block}
+ wire = read_frame(io.BytesIO(encode_frame({'type': 'result', 'result': result_frame(raw)})))
+ result, _usage = accept_result(wire['result'])
+ assert result['billing_block'] == {k: v for k, v in block.items() if k != 'internal'}
+ assert result['failure_reason'] == 'billing'
+
+
+def _usage_db(tmp_path):
+ from hermes_state import SessionDB
+ return SessionDB(db_path=tmp_path / 'state.db')
+
+
+def _settle(db, reservation, tip):
+ """Settle as the owner does: the tip is whatever the owner's execution row names (compression moves it there)."""
+ from types import SimpleNamespace
+ from gateway.session_managed_worker import _settled_session_usage
+ db._execute_write(lambda conn: conn.execute(
+ "INSERT INTO worker_executions(execution_id,session_id,kind,owner_epoch,generation,status,adoption_digest) "
+ "VALUES('exec',?,'compute',1,1,'running','d')", (tip,)))
+ try:
+ return _settled_session_usage(SimpleNamespace(db=db), reservation, {'model': 'm'}, 'exec')['session_usage']
+ finally:
+ db._execute_write(lambda conn: conn.execute("DELETE FROM worker_executions WHERE execution_id='exec'"))
+
+
+def test_settled_usage_sums_the_compression_lineage_a_worker_rotated_through(tmp_path):
+ """A managed worker that compresses mid-turn moves its writes to the child session while the owner's reservation still names the parent; the settled turn-end usage covers the whole lineage."""
+ db = _usage_db(tmp_path)
+ with db:
+ db.create_session('root', source='cli')
+ db.update_token_counts('root', input_tokens=200, output_tokens=50, api_call_count=2, model='m')
+ db.end_session('root', 'compression')
+ db.create_session('tip', source='cli', parent_session_id='root')
+ db.update_token_counts('tip', input_tokens=300, output_tokens=70, cache_read_tokens=100, api_call_count=1, model='m')
+ settled = _settle(db, 'root', 'tip')
+ assert (settled['input_tokens'], settled['output_tokens'], settled['cache_read_tokens'], settled['api_calls']) == (500, 120, 100, 3)
+ assert settled['prompt_tokens'] == 600 and settled['total_tokens'] == 720
+
+
+def test_settled_usage_follows_a_branch_through_its_own_compression(tmp_path):
+ """A branched session that compresses mid-turn sums itself and its continuation, never the conversation it was branched from."""
+ db = _usage_db(tmp_path)
+ with db:
+ db.create_session('origin', source='cli')
+ db.update_token_counts('origin', input_tokens=9000, output_tokens=900, api_call_count=9, model='m')
+ db.create_session('branch', source='cli', parent_session_id='origin', model_config={'_branched_from': 'origin'})
+ db.update_token_counts('branch', input_tokens=200, output_tokens=50, api_call_count=2, model='m')
+ db.end_session('branch', 'compression')
+ db.create_session('tip', source='cli', parent_session_id='branch', model_config={'_branched_from': 'origin'})
+ db.update_token_counts('tip', input_tokens=300, output_tokens=70, api_call_count=1, model='m')
+ settled = _settle(db, 'branch', 'tip')
+ assert (settled['input_tokens'], settled['output_tokens'], settled['api_calls']) == (500, 120, 3)
+
+
+def test_settled_usage_ignores_a_stale_sibling_of_the_continuation(tmp_path):
+ """A closed sibling under a compressed parent (an orphaned websocket session) is not part of the turn's lineage; only the path to the tip the execution ended on counts."""
+ db = _usage_db(tmp_path)
+ with db:
+ db.create_session('root', source='cli')
+ db.update_token_counts('root', input_tokens=10, api_call_count=1, model='m')
+ db.end_session('root', 'compression')
+ db.create_session('stale', source='cli', parent_session_id='root')
+ db.update_token_counts('stale', input_tokens=1000, api_call_count=5, model='m')
+ db.end_session('stale', 'ws_orphan_reap')
+ db.create_session('live', source='cli', parent_session_id='root')
+ db.update_token_counts('live', input_tokens=20, api_call_count=1, model='m')
+ from_root = _settle(db, 'root', 'live')
+ from_live = _settle(db, 'live', 'live')
+ assert (from_root['input_tokens'], from_root['api_calls']) == (30, 2)
+ assert (from_live['input_tokens'], from_live['api_calls']) == (30, 2)
+
+
+def test_settled_usage_ignores_the_worker_reported_session_id(tmp_path):
+ """The result frame's ``session_id`` is worker output: settlement reads the tip from the owner's execution row, so a frame naming a sibling or a foreign session changes nothing."""
+ from types import SimpleNamespace
+ from gateway.session_managed_worker import _settled_session_usage
+ db = _usage_db(tmp_path)
+ with db:
+ db.create_session('mine', source='cli')
+ db.update_token_counts('mine', input_tokens=10, api_call_count=1, model='m')
+ db.end_session('mine', 'compression')
+ db.create_session('sibling', source='cli', parent_session_id='mine')
+ db.update_token_counts('sibling', input_tokens=5000, api_call_count=50, model='m')
+ db.create_session('foreign', source='cli')
+ db.update_token_counts('foreign', input_tokens=7000, api_call_count=70, model='m')
+ for claimed in ('sibling', 'foreign'):
+ settled = _settled_session_usage(SimpleNamespace(db=db), 'mine', {'model': 'm', 'session_id': claimed})['session_usage']
+ assert (settled['input_tokens'], settled['api_calls']) == (10, 1)