Skip to content

The agent that grows with you

feat: publish real prepared compression in the mutation receipt transaction

Tekniumb654027693d6
diff --git a/gateway/session_mutation_compress.py b/gateway/session_mutation_compress.py
new file mode 100644
index 00000000000..23bc7a03cbd
--- /dev/null
+++ b/gateway/session_mutation_compress.py
@@ -0,0 +1,35 @@
+"""Summary preparation has no canonical store; publication owns the only write."""
+import asyncio
+import json
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+async def prepare_compress(authority, live, payload, prepared):
+ from gateway.session_policy import restore_policy, policy_scope
+ from agent.context_compressor import ContextCompressor
+ snapshot = prepared['snapshot']
+ policy = restore_policy(snapshot['receipt']['policy'])
+ config = policy.config(authority)
+ options = config.get('compression') or {}
+ if options.get('checkpoint_required'):
+ raise RuntimeStoreError('compression_checkpoint_required')
+ model, runtime = authority.runner._resolve_session_agent_runtime(source=live.source, session_key=live.route)
+ if runtime.get('api_mode') == 'codex_app_server':
+ raise RuntimeStoreError('runtime_coordination_required')
+ history = authority.db.get_messages_as_conversation(snapshot['target'])
+ messages = [m for m in history if m.get('role') in {'user', 'assistant', 'tool'}]
+ def summarize():
+ with policy_scope(policy, authority=authority):
+ compressor = ContextCompressor(model, base_url=runtime.get('base_url') or '',
+ api_key=runtime.get('api_key') or '', provider=runtime.get('provider') or '',
+ api_mode=runtime.get('api_mode') or '', quiet_mode=True, abort_on_summary_failure=True,
+ protect_first_n=options.get('protect_first_n', 3), protect_last_n=options.get('protect_last_n', 20),
+ custom_providers=config.get('custom_providers'))
+ compressed = compressor.compress(json.loads(json.dumps(messages)), force=True,
+ focus_topic=payload.get('focus'))
+ if not any(m.get('_compressed_summary') for m in compressed):
+ raise RuntimeStoreError('nothing_to_compress')
+ return compressed
+ compressed = await asyncio.to_thread(summarize)
+ return dict(prepared, messages=compressed)
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index 2fc6ac9547b..9d4111a940b 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -7,7 +7,6 @@ branch/compress/model still require their own prepared runtime publication.
from hermes_state_runtime import RuntimeStoreError, mutate_runtime_session
_METADATA = frozenset({'rename', 'archive', 'sidebar'})
-_RUNTIME_ACTIONS = frozenset({'compress'})
_FIELDS = frozenset({'session_id', 'request_id', 'expected_revision', 'operation', 'payload'})
@@ -69,9 +68,6 @@ async def mutate_session(authority, actor, ref, params):
if operation in {'rewind', 'reset'} and not callable(getattr(authority.runner, '_evict_cached_agent', None)):
raise RuntimeStoreError('runtime_coordination_required')
- if operation in _RUNTIME_ACTIONS:
- live_guard([ref.session_id])
- raise RuntimeStoreError('runtime_coordination_required')
def authorize_write(conn):
from hermes_state_mutation_binding import authorize_history, import_history_control
if operation == 'import':
@@ -81,7 +77,7 @@ async def mutate_session(authority, actor, ref, params):
raise RuntimeStoreError('permission_denied')
prepared = None
- if operation == 'model':
+ if operation in {'model', 'compress'}:
prepared = mutate_runtime_session(authority.db, epoch=authority.epoch,
principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],
expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),
@@ -89,7 +85,9 @@ async def mutate_session(authority, actor, ref, params):
if 'snapshot' not in prepared:
return prepared
from gateway.session_mutation_model import prepare_model
- prepared = await prepare_model(authority, live, params['payload'], prepared)
+ from gateway.session_mutation_compress import prepare_compress
+ prepare = {'model': prepare_model, 'compress': prepare_compress}[operation]
+ prepared = await prepare(authority, live, params['payload'], prepared)
applied = False
result = mutate_runtime_session(authority.db, epoch=authority.epoch,
principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],
@@ -102,7 +100,7 @@ async def mutate_session(authority, actor, ref, params):
if operation == 'branch':
from gateway.session_local_recovery import restore_local_session
restore_local_session(authority, result['branched_session_id'])
- if operation == 'reset' and applied:
+ if operation in {'reset', 'compress'} and applied:
from gateway.session_local_recovery import restore_local_session
restore_local_session(authority, ref.session_id)
authority.runner._evict_cached_agent(authority.sessions[ref.session_id].route)
diff --git a/hermes_state_mutation_compress.py b/hermes_state_mutation_compress.py
new file mode 100644
index 00000000000..4f2b97b6242
--- /dev/null
+++ b/hermes_state_mutation_compress.py
@@ -0,0 +1,20 @@
+"""Commit a prepared summary, physical successor, generation and receipt atomically."""
+import uuid
+from hermes_state_mutation_prepared import validate_prepared
+
+
+def compress_in_transaction(db, conn, session_id, payload, prepared):
+ snapshot = validate_prepared(db, conn, session_id, prepared)
+ policy = snapshot['receipt']['policy']
+ target = snapshot['target']
+ child = uuid.uuid4().hex
+ from hermes_state_worker_compression import publish_on_connection
+ # No worker/turn/compactor can be active: validate_prepared checks those
+ # obligations on this exact connection. No separate legacy transaction runs.
+ publish_on_connection(db, conn, parent_session_id=target, child_session_id=child,
+ source=policy['source'], model=policy['model'], messages=prepared['messages'],
+ model_config={'_compressed_from': target}, cwd=policy['cwd'], require_compression_lease=False)
+ conn.execute('UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', (session_id,))
+ generation = conn.execute('SELECT runtime_generation FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
+ return set(), {'target_session_id': child, 'previous_target_session_id': target,
+ 'execution_generation': generation, 'message_count': len(prepared['messages'])}
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
index f3f8f3f799a..89ab2974c57 100644
--- a/hermes_state_mutations.py
+++ b/hermes_state_mutations.py
@@ -13,6 +13,8 @@ def validate_action(operation, payload):
return
if operation == 'branch' and (not payload or (set(payload) == {'title'} and isinstance(payload['title'], str))):
return
+ if operation == 'compress' and (not payload or (set(payload) == {'focus'} and isinstance(payload['focus'], str))):
+ return
if operation in {'delete', 'reset'} and not payload:
return
if operation == 'import' and set(payload) == {'sessions'} and isinstance(payload['sessions'], list):
@@ -32,6 +34,9 @@ def validate_action(operation, payload):
def apply_action(db, conn, session_id, operation, payload, *, prepared=None):
+ if operation == 'compress':
+ from hermes_state_mutation_compress import compress_in_transaction
+ return compress_in_transaction(db, conn, session_id, payload, prepared)
if operation == 'model':
from hermes_state_mutation_prepared import model_in_transaction
return model_in_transaction(db, conn, session_id, payload, prepared)
diff --git a/tests/gateway/test_session_mutation_compress.py b/tests/gateway/test_session_mutation_compress.py
new file mode 100644
index 00000000000..e9b6bcf7e8c
--- /dev/null
+++ b/tests/gateway/test_session_mutation_compress.py
@@ -0,0 +1,109 @@
+"""Real summary preparation commits only against the unchanged local transcript."""
+import asyncio
+from http.server import ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import sqlite3
+import threading
+
+import pytest
+from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket
+from tests.gateway.test_session_mutation_model import CatalogModel
+
+
+class SummaryModel(CatalogModel):
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ if body.get('messages'):
+ self.server.requests.append(body)
+ summary = body.get('model') == 'summary'
+ text = 'SUMMARY_RETAINED_FACTS' if summary else 'ORDINARY_REPLY ' + ('historical detail ' * 700)
+ payload = json.dumps({'id': 'fixture', 'choices': [{'index': 0,
+ 'message': {'role': 'assistant', 'content': text}, 'finish_reason': 'stop'}],
+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 10, 'total_tokens': 20}}).encode()
+ kind = 'application/json'
+ if body.get('stream'):
+ payload = ('data: ' + json.dumps({'id': 'fixture', 'choices': [{'index': 0,
+ 'delta': {'role': 'assistant', 'content': text}, 'finish_reason': 'stop'}]}) + '\n\ndata: [DONE]\n\n').encode()
+ kind = 'text/event-stream'
+ self.send_response(200)
+ self.send_header('Content-Type', kind)
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+
+def test_compress_runs_summary_and_next_inference_on_atomic_successor(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), SummaryModel)
+ peer.requests = []
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ cfg = {'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'original', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False},
+ 'compression': {'provider': 'custom', 'model': 'summary', 'base_url': url}},
+ 'platform_toolsets': {'cli': []}, 'compression': {'protect_first_n': 1, 'protect_last_n': 2}}
+ (home / 'config.yaml').write_text(json.dumps(cfg))
+ (home / 'models_dev_cache.json').write_text(json.dumps({'custom': {'id': 'custom', 'models': {
+ name: {'id': name, 'name': name, 'limit': {'context': 1000000, 'output': 4000}}
+ for name in ('original', 'summary')}}}))
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')
+
+ async def run(desc):
+ async with websocket(home, desc) as ws:
+ async def call(method, **params):
+ response = await rpc(ws, method, **params)
+ assert 'result' in response, response
+ return response['result']
+ sid = (await call('session.create', source='cli', request_id='owner', toolsets=[]))['session_id']
+ async def turn(text):
+ await call('prompt.submit', session_id=sid, input_id=text, text=text)
+ async with asyncio.timeout(30):
+ while True:
+ with sqlite3.connect(home / 'state.db') as db:
+ row = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (text,)).fetchone()
+ if row and row[0] == 'terminal':
+ return await call('session.resume', session_id=sid)
+ await asyncio.sleep(.03)
+ for i in range(12):
+ before = await turn('HISTORY_' + str(i))
+ params = dict(session_id=sid, request_id='compress', operation='compress', payload={},
+ expected_revision=before['revision'], expected_generation=before['execution_generation'])
+ result = await call('session.mutate', **params)
+ assert any(r['model'] == 'summary' for r in peer.requests)
+ assert result['target_session_id'] != sid
+ compressed = await call('session.resume', session_id=sid)
+ assert 'SUMMARY_RETAINED_FACTS' in json.dumps(compressed['messages'])
+ await turn('AFTER_COMPRESSION')
+ assert 'SUMMARY_RETAINED_FACTS' in json.dumps(peer.requests[-1]['messages'])
+ count = len(peer.requests)
+ assert await call('session.mutate', **params) == result
+ assert len(peer.requests) == count
+ with sqlite3.connect(home / 'state.db') as db:
+ assert db.execute('SELECT end_reason FROM sessions WHERE id=?', (sid,)).fetchone()[0] == 'compression'
+ assert db.execute('SELECT count(*) FROM messages WHERE session_id=?', (sid,)).fetchone()[0] > 0
+ receipt = json.loads(db.execute('SELECT value FROM state_meta WHERE key=?',
+ ('gateway.local_policy.v1:' + sid,)).fetchone()[0])
+ assert receipt['entry']['session_id'] == result['target_session_id']
+ return params, result
+ try:
+ with daemon(root, home, env, barrier=False) as (_, desc):
+ params, result = asyncio.run(run(desc))
+ async def retry(desc):
+ async with websocket(home, desc) as ws:
+ assert (await rpc(ws, 'session.mutate', **params)).get('result') == result
+ with daemon(root, home, env, barrier=False) as (_, desc):
+ asyncio.run(retry(desc))
+ finally:
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)