From 7a7ff34bb4e2793cff14f2affc161e0b672eb11b Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Thu, 8 Oct 2026 08:39:09 -0700 Subject: [PATCH] fix(state): store per-turn results without session-wide copies Every settled turn stored its result under gateway.admission.result.v1.. The base already trims cumulative `messages` to the current-turn suffix in settle_session_input. Two problems remained: - `tools`, the session's full tool-schema list (about 45 KB with the default toolsets, more with MCP), was still copied into every row. 100 turns of about 1.6 KB each stored 13.2 MB on b4971df21a1 and 4.6 MB on the base. With this change they store 0.22 MB, a flat 2.2 KB per row. - finish_result redacted the whole cumulative result before compaction discarded most of it, so the recursive redaction walk grew with session length on every turn. Compact first, then redact only what is stored. No stored-result reader uses `tools`: session_bot, session_hosted_rpc, session_api_turn and the API run projection, session_cron (cron_result), session_a2a (final_response) and prompt.receipt include_result (the -q/-z ledger keys in _LEDGER_PASSTHROUGH_KEYS). Retirement's _TRANSCRIPT_FIELDS also drops `tools` from rows written before this change. Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5456384314 --- gateway/session_results.py | 3 ++ hermes_state_mutation_retirement.py | 2 +- hermes_state_terminal.py | 3 ++ tests/gateway/test_settled_result_size.py | 37 +++++++++++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 tests/gateway/test_settled_result_size.py diff --git a/gateway/session_results.py b/gateway/session_results.py index e133da71e1..f99bca12a8 100644 --- a/gateway/session_results.py +++ b/gateway/session_results.py @@ -74,6 +74,9 @@ def finish_result(db, *, epoch, row, response, outcome, result=None): if outcome in ('failed', 'interrupted'): value['failed' if outcome == 'failed' else 'interrupted'] = True value['completed'] = False + # Compact before redacting, so the walk covers this turn's output, not every earlier turn. + from hermes_state_terminal import compact_result + result = compact_result(result, user_message=row['payload'].get('text')) settled = settle_session_input(db, epoch=epoch, admission_id=row['admission_id'], generation=row['generation'], outcome=outcome, result=_redacted(result)) return settled, response diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.py index 6f4f25d480..113e549a7e 100644 --- a/hermes_state_mutation_retirement.py +++ b/hermes_state_mutation_retirement.py @@ -20,7 +20,7 @@ def has_mutation_receipt(db, principal_id, session_id, request_id): return conn.execute('SELECT 1 FROM state_meta WHERE key=?', (key,)).fetchone() is not None -_TRANSCRIPT_FIELDS = frozenset({'messages', 'last_reasoning'}) +_TRANSCRIPT_FIELDS = frozenset({'messages', 'last_reasoning', 'tools'}) def _compact_result(conn, admission_id): diff --git a/hermes_state_terminal.py b/hermes_state_terminal.py index c5b83caf1d..69fef49ecd 100644 --- a/hermes_state_terminal.py +++ b/hermes_state_terminal.py @@ -22,6 +22,9 @@ def compact_result(result, *, user_message=None): if not isinstance(value, dict): return result value = dict(value) + # The tool schema list rides every turn result for in-process transcript logging; it is the + # same session-wide copy each turn (tens of KB, more with MCP) and no stored-result reader uses it. + value.pop('tools', None) messages = value.get('messages') if isinstance(messages, list): # Agent results include all previous turns. APIs only project this turn's diff --git a/tests/gateway/test_settled_result_size.py b/tests/gateway/test_settled_result_size.py new file mode 100644 index 0000000000..1f42c0ec3b --- /dev/null +++ b/tests/gateway/test_settled_result_size.py @@ -0,0 +1,37 @@ +"""A settled turn result stores this turn's output and accounting, never per-session copies.""" +from gateway.session_results import admission_result, finish_result +from hermes_state_runtime import admit_session_input, claim_session_input + + +def test_stored_result_is_bounded_and_redaction_skips_earlier_turns(owner, monkeypatch): + import agent.redact + seen = [] + redact = agent.redact.redact_sensitive_text + monkeypatch.setattr(agent.redact, 'redact_sensitive_text', lambda text, **kw: seen.append(text) or redact(text, **kw)) + owner.db.create_session('s', source='api_server') + tools = [{'type': 'function', 'function': {'name': f'tool{i}', 'description': 'd' * 500}} for i in range(40)] + history = [{'role': 'user', 'content': 'history-sentinel ' + 'h' * 2000}] * 50 + sizes = [] + for index in range(2): + admit_session_input(owner.db, epoch=owner.epoch, principal_id='api', session_id='s', + request_id=str(index), payload={'text': f'ask {index}'}) + row = claim_session_input(owner.db, epoch=owner.epoch, session_id='s') + history = history + [{'role': 'user', 'content': f'ask {index}'}, {'role': 'assistant', 'content': 'done'}] + finish_result(owner.db, epoch=owner.epoch, row=row, response='done', outcome='completed', + result={'result': {'final_response': 'done', 'messages': list(history), 'tools': tools, + 'completed': True, 'model': 'm', 'turn_exit_reason': 'text_response', + 'estimated_cost_usd': .25}, + 'usage': {'input_tokens': 3}}) + saved = admission_result(owner.db, row['admission_id']) + # Every stored-result reader keeps its fields: final text, -z ledger keys, usage. + assert saved['usage'] == {'input_tokens': 3} + assert {k: saved['result'][k] for k in ('final_response', 'completed', 'model', 'turn_exit_reason', + 'estimated_cost_usd')} == {'final_response': 'done', 'completed': True, 'model': 'm', + 'turn_exit_reason': 'text_response', 'estimated_cost_usd': .25} + assert saved['result']['messages'] == [{'role': 'assistant', 'content': 'done'}] + assert 'tools' not in saved['result'] + with owner.db._read_ctx() as conn: + sizes.append(conn.execute('SELECT length(value) FROM state_meta WHERE key=?', + ('gateway.admission.result.v1.' + row['admission_id'],)).fetchone()[0]) + assert sizes[0] == sizes[1] < 1024, sizes + assert not any('history-sentinel' in text or 'd' * 500 in text for text in seen), 'redacted discarded copies'