Skip to content

The agent that grows with you

feat: authenticate live worker persistence and explicit restart adoption

Teknium9d7d7e2abdab
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.py
new file mode 100644
index 00000000000..a36e55b9da6
--- /dev/null
+++ b/agent/runtime_session_store.py
@@ -0,0 +1,198 @@
+"""Explicit worker persistence facade; never opens the canonical SQLite store.
+
+This first operation family is deliberately NOT a complete SessionDB substitute.
+No existing cron/child/compute consumer is switched until its inventory is covered.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+from pathlib import Path
+import tempfile
+import threading
+
+
+class WorkerPersistenceError(RuntimeError):
+ pass
+
+
+class WorkerRPC:
+ """Bounded authenticated calls to an existing owner; never starts a daemon.
+
+ websockets.sync owns a dedicated frame receiver, independent of the caller.
+ No owner-loop synchronous self-RPC or SQLite fallback is permitted.
+ """
+ def __init__(self, home):
+ self.home = Path(home).resolve()
+ self.lock = threading.Lock()
+
+ def __call__(self, method, **params):
+ from hermes_cli.gateway_client import _session_ticket
+ from hermes_cli.gateway_runtime_discovery import query_identify
+ from websockets.sync.client import connect
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ pass
+ else:
+ raise WorkerPersistenceError('synchronous_rpc_on_event_loop')
+ with self.lock:
+ descriptor = query_identify(self.home, timeout=5)
+ if descriptor.get('pid') == os.getpid():
+ raise WorkerPersistenceError('synchronous_self_rpc')
+ from hermes_cli.gateway_runtime import _endpoint
+ discovery = _endpoint(descriptor, self.home)
+ if discovery.state != 'ready' or discovery.endpoint is None:
+ raise WorkerPersistenceError('owner_unavailable')
+ endpoint = discovery.endpoint
+ ticket = _session_ticket(self.home, endpoint)
+ url = endpoint.api_origin.replace('https:', 'wss:').replace('http:', 'ws:') + '/api/ws'
+ with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket],
+ open_timeout=5, close_timeout=1, max_size=8 * 1024 * 1024) as ws:
+ ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}))
+ import time
+ deadline = time.monotonic() + 20
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError('worker_receipt_timeout')
+ response = json.loads(ws.recv(timeout=remaining))
+ if response.get('id') == 1:
+ break
+ if 'error' in response:
+ raise WorkerPersistenceError(response['error'].get('message', 'persistence_failed'))
+ return response['result']
+
+
+class RuntimeSessionStore:
+ """Synchronous durable results with a private byte-bounded retry journal.
+
+ A failed write remains pending, and failure is sticky until explicit retry or
+ adoption. Local queue acceptance is never returned as canonical commit.
+ Pending journals live outside age-pruned cache trees.
+ """
+ def __init__(self, rpc, scope, outbox_dir, *, max_bytes=4 * 1024 * 1024):
+ self.rpc = rpc
+ self.scope = dict(scope)
+ self.max_bytes = max_bytes
+ self.lock = threading.RLock()
+ self.failure = None
+ self.path = Path(outbox_dir) / 'pending.json'
+ self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ if self.path.parent.is_symlink() or self.path.is_symlink():
+ raise WorkerPersistenceError('unsafe_outbox')
+ os.chmod(self.path.parent, 0o700)
+ if self.path.exists():
+ self.journal = json.loads(self.path.read_text())
+ if self.journal['scope'] != self.scope:
+ raise WorkerPersistenceError('outbox_scope_mismatch')
+ else:
+ self.journal = {'scope': self.scope, 'next_sequence': 1, 'pending': []}
+ self._save(self.journal)
+
+ def _save(self, journal):
+ encoded = json.dumps(journal, ensure_ascii=True, allow_nan=False, separators=(',', ':')).encode()
+ if len(encoded) > self.max_bytes:
+ self.failure = 'outbox_full'
+ raise WorkerPersistenceError(self.failure)
+ fd, temporary = tempfile.mkstemp(prefix='.pending-', dir=self.path.parent)
+ try:
+ with os.fdopen(fd, 'wb') as stream:
+ stream.write(encoded)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, self.path)
+ if os.name != 'nt':
+ directory = os.open(self.path.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+ def _session(self, session_id):
+ if session_id != self.scope['session_id']:
+ raise WorkerPersistenceError('permission_denied')
+
+ def _apply(self, operation, payload):
+ with self.lock:
+ if self.failure:
+ raise WorkerPersistenceError(self.failure)
+ if self.journal['pending']:
+ raise WorkerPersistenceError('pending_receipt')
+ entry = {'sequence': self.journal['next_sequence'], 'operation': operation, 'payload': payload}
+ candidate = json.loads(json.dumps(self.journal))
+ candidate['pending'].append(entry)
+ candidate['next_sequence'] += 1
+ self._save(candidate)
+ self.journal = candidate
+ return self.retry_pending()[0]
+
+ def retry_pending(self):
+ with self.lock:
+ results = []
+ try:
+ while self.journal['pending']:
+ entry = self.journal['pending'][0]
+ result = self.rpc('worker.persist', **self.scope, **entry)
+ candidate = dict(self.journal, pending=self.journal['pending'][1:])
+ self._save(candidate)
+ self.journal = candidate
+ results.append(result)
+ except Exception as exc:
+ self.failure = str(exc)
+ raise
+ self.failure = None
+ return results
+
+ def adopt(self, epoch):
+ """Install only a separately verified worker.adopt result; never self-adopt."""
+ with self.lock:
+ candidate = dict(self.journal, scope=dict(self.scope, epoch=epoch))
+ self._save(candidate)
+ self.scope = candidate['scope']
+ self.journal = candidate
+ self.failure = None
+
+ def append_messages_batch(self, session_id, messages, compression_lock_holder=None,
+ turn_lease_holder=None, chunk_rows=None, turn_lease_ttl_seconds=300.0):
+ self._session(session_id)
+ if compression_lock_holder is not None or chunk_rows is not None or turn_lease_ttl_seconds != 300.0:
+ raise WorkerPersistenceError('unsupported_operation')
+ result = self._apply('transcript.append', {'messages': messages, 'turn_lease_holder': turn_lease_holder})
+ for message, annotation in zip(messages, result['annotations'], strict=True):
+ message.update(annotation)
+ return result['count']
+
+ def try_acquire_session_turn_lease(self, session_id, holder, *, ttl_seconds=300.0, patience_s=None):
+ self._session(session_id)
+ return self._apply('turn.acquire', {'holder': holder, 'ttl_seconds': ttl_seconds})['value']
+
+ def refresh_session_turn_lease(self, session_id, holder, *, ttl_seconds=300.0):
+ self._session(session_id)
+ return self._apply('turn.renew', {'holder': holder, 'ttl_seconds': ttl_seconds})['value']
+
+ def release_session_turn_lease(self, session_id, holder):
+ self._session(session_id)
+ self._apply('turn.release', {'holder': holder})
+
+ def queue_token_counts(self, session_id, **usage):
+ self._session(session_id)
+ self._apply('usage.main', usage)
+
+ def record_auxiliary_usage(self, session_id, task, **usage):
+ self._session(session_id)
+ self._apply('usage.auxiliary', dict(usage, task=task))
+
+ def flush_token_counts(self, timeout=5.0):
+ with self.lock:
+ if self.failure:
+ raise WorkerPersistenceError(self.failure)
+ if self.journal['pending']:
+ raise WorkerPersistenceError('pending_receipt')
+ return True
+
+ def close(self):
+ self.flush_token_counts()
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 6ae2d479825..f11f958bdd4 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -36,6 +36,8 @@ class AuthorityConnection:
'slash.exec': self.slash_exec, 'command.dispatch': self.command_dispatch,
'session.list': self.list_sessions, 'session.info': self.info,
'session.mutate': self.mutate,
+ 'worker.register': self.worker_register, 'worker.adopt': self.worker_adopt,
+ 'worker.persist': self.worker_persist,
'setup.status': self.setup_status, 'setup.runtime_check': self.setup_runtime_check,
'session.resume': self.resume, 'prompt.submit': self.submit,
'prompt.receipt': self.receipt, 'prompt.cancel': self.cancel,
@@ -53,6 +55,18 @@ class AuthorityConnection:
return {'jsonrpc': '2.0', 'id': rid, 'error': {
'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}
+ async def worker_register(self, ref, params):
+ from gateway.session_worker import worker_request
+ return await worker_request(self, ref, params, operation='register')
+
+ async def worker_adopt(self, ref, params):
+ from gateway.session_worker import worker_request
+ return await worker_request(self, ref, params, operation='adopt')
+
+ async def worker_persist(self, ref, params):
+ from gateway.session_worker import worker_request
+ return await worker_request(self, ref, params, operation='persist')
+
async def slash_exec(self, ref, params):
from gateway.session_commands import execute_command
return await execute_command(self, ref, params)
diff --git a/gateway/session_worker.py b/gateway/session_worker.py
new file mode 100644
index 00000000000..a6a0df048b8
--- /dev/null
+++ b/gateway/session_worker.py
@@ -0,0 +1,79 @@
+"""Execution-scoped worker operations on the ordinary authenticated authority.
+
+Only explicit local compute registrations are enabled. Cron/child claims need
+producer-specific validation before their consumers can use this transport.
+"""
+import asyncio
+import hmac
+import os
+
+from gateway.session_admission import admission_fingerprint
+from hermes_state_runtime import (
+ RuntimeStoreError, _secret_digest, adopt_worker_execution,
+ mutate_worker_execution, register_worker_execution,
+)
+
+_SCOPE = {'profile_id', 'session_id', 'execution_id', 'generation', 'pid', 'birth', 'secret'}
+
+
+def _claim(connection, ref, params):
+ import psutil
+ authority = connection.authority
+ if params.get('profile_id') != authority.profile_id or connection.actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if not connection.actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ pid, birth = params.get('pid'), params.get('birth')
+ secret = params.get('secret')
+ if (type(pid) is not int or pid <= 0 or pid == os.getpid()
+ or type(birth) not in (int, float) or not isinstance(secret, str) or not 16 <= len(secret) <= 256):
+ raise RuntimeStoreError('invalid_params')
+ try:
+ process = psutil.Process(pid)
+ if (process.create_time() != birth or not process.is_running()
+ or process.status() == psutil.STATUS_ZOMBIE
+ or process.username() != psutil.Process().username()):
+ raise RuntimeStoreError('permission_denied')
+ except psutil.Error as exc:
+ raise RuntimeStoreError('worker_not_live') from exc
+ # Reuse the durable adoption digest as the producer claim. Changing any
+ # assignment, principal, profile, PID birth or secret cannot adopt it.
+ return admission_fingerprint(canonical_target=ref.session_id, payload={
+ key: params[key] for key in _SCOPE} | {'principal': connection.actor.subject})
+
+
+def _verify(connection, ref, params, claim):
+ authority = connection.authority
+ with authority.db._read_ctx() as conn:
+ row = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?',
+ (params['execution_id'],)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ if row['session_id'] != ref.session_id:
+ raise RuntimeStoreError('permission_denied')
+ if type(params['generation']) is not int or row['generation'] != params['generation']:
+ raise RuntimeStoreError('stale_generation')
+ if not hmac.compare_digest(row['adoption_digest'], _secret_digest(claim)):
+ raise RuntimeStoreError('permission_denied')
+
+
+async def worker_request(connection, ref, params, *, operation):
+ extra = {'register': {'kind'}, 'adopt': set(), 'persist': {'epoch', 'sequence', 'operation', 'payload'}}[operation]
+ if set(params) != _SCOPE | extra:
+ raise RuntimeStoreError('invalid_params')
+ claim = _claim(connection, ref, params)
+ authority = connection.authority
+ authority._require_admission_open()
+ scope = {key: params[key] for key in ('execution_id', 'session_id', 'generation')}
+ if operation == 'register':
+ authority.authorize(connection.actor, ref, 'session:control')
+ if params['kind'] != 'compute':
+ raise RuntimeStoreError('unsupported_producer')
+ return await asyncio.to_thread(register_worker_execution, authority.db, epoch=authority.epoch,
+ **scope, kind='compute', adoption_secret=claim, require_idle=True)
+ _verify(connection, ref, params, claim)
+ if operation == 'adopt':
+ return await asyncio.to_thread(adopt_worker_execution, authority.db, epoch=authority.epoch,
+ **scope, adoption_secret=claim)
+ return await asyncio.to_thread(mutate_worker_execution, authority.db, epoch=params['epoch'],
+ **scope, sequence=params['sequence'], operation=params['operation'], payload=params['payload'])
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index ac06c8056fb..18997c033ba 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -359,7 +359,7 @@ def _secret_digest(secret):
def register_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,
- generation: int, kind: str, adoption_secret: str) -> dict:
+ generation: int, kind: str, adoption_secret: str, require_idle: bool = False) -> dict:
for value in (execution_id, session_id):
_text(value)
if kind not in ('cron', 'child', 'compute', 'kanban'):
@@ -375,6 +375,8 @@ def register_worker_execution(db, *, epoch: int, execution_id: str, session_id:
if (old['session_id'], old['generation'], old['kind'], old['owner_epoch'], old['adoption_digest']) != (session_id, generation, kind, epoch, digest):
raise RuntimeStoreError('admission_conflict')
return _worker_public(old)
+ if require_idle and conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status!='terminal'", (session_id,)).fetchone():
+ raise RuntimeStoreError('stale_generation')
if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status!='terminal'", (session_id,)).fetchone():
raise RuntimeStoreError('stale_generation')
if conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status='unknown'", (session_id,)).fetchone():
diff --git a/tests/gateway/fixtures/persistence_worker.py b/tests/gateway/fixtures/persistence_worker.py
new file mode 100644
index 00000000000..ec62b98a8da
--- /dev/null
+++ b/tests/gateway/fixtures/persistence_worker.py
@@ -0,0 +1,87 @@
+"""Owned inert tool witness. Commands arrive through a private test pipe."""
+import json
+import os
+from pathlib import Path
+import sys
+
+import psutil
+
+
+def writable_fds(home):
+ result = []
+ for path in Path('/proc/self/fd').iterdir():
+ try:
+ target = path.resolve()
+ flags = next(line.split(':')[1].strip() for line in
+ (Path('/proc/self/fdinfo') / path.name).read_text().splitlines()
+ if line.startswith('flags:'))
+ if target.name in ('state.db', 'state.db-wal', 'state.db-shm') and int(flags, 8) & 3:
+ result.append(str(target))
+ except FileNotFoundError:
+ continue
+ return result
+
+
+def reason(fn):
+ try:
+ fn()
+ except Exception as exc:
+ return str(exc)
+ raise AssertionError('expected refusal')
+
+
+for line in sys.stdin:
+ try:
+ command = json.loads(line)
+ if command['op'] == 'start':
+ from agent import runtime_session_store as module
+ home = Path(command['home'])
+ transport = module.WorkerRPC(home)
+ scope = {'profile_id': str(home), 'session_id': command['session_id'],
+ 'execution_id': 'owned-worker', 'generation': 0,
+ 'pid': os.getpid(), 'birth': psutil.Process().create_time(), 'secret': 'private-worker-secret'}
+ registration = transport('worker.register', **scope, kind='compute')
+ scope['epoch'] = registration['owner_epoch']
+ store = module.RuntimeSessionStore(transport, scope, home / 'worker-outboxes' / 'owned-worker', max_bytes=20000)
+ sid = scope['session_id']
+ store.try_acquire_session_turn_lease(sid, 'owned-worker-lease')
+ (home / 'tool-marker').write_text('once')
+ messages = [{'role': 'user', 'content': 'start'},
+ {'role': 'assistant', 'content': None, 'tool_calls': [{'id': 'call', 'type': 'function',
+ 'function': {'name': 'inert', 'arguments': '{}'}}]},
+ {'role': 'tool', 'content': 'tool-marker', 'tool_call_id': 'call', 'tool_name': 'inert'}]
+ original = store.rpc
+ lost = []
+ def lose_ack(method, **params):
+ result = original(method, **params)
+ lost.append(params)
+ raise TimeoutError('lost_ack')
+ store.rpc = lose_ack
+ assert reason(lambda: store.append_messages_batch(sid, messages, turn_lease_holder='owned-worker-lease')) == 'lost_ack'
+ store.rpc = original
+ recovered = store.retry_pending()
+ assert recovered[0]['count'] == 3
+ saved = lost[0]
+ assert original('worker.persist', **saved) == recovered[0]
+ store.queue_token_counts(sid, input_tokens=11, model='inert-model', api_call_count=1)
+ assert store.flush_token_counts()
+ output = {'registered': True, 'rows': 3, 'lost_ack_replayed': True,
+ 'epoch': scope['epoch'], 'pid': os.getpid(),
+ 'conflict': reason(lambda: original('worker.persist', **(saved | {'payload': {'messages': []}}))),
+ 'wrong_session': reason(lambda: original('worker.persist', **(saved | {'session_id': 'foreign'}))),
+ 'wrong_profile': reason(lambda: original('worker.persist', **(saved | {'profile_id': '/foreign'}))),
+ 'wrong_generation': reason(lambda: original('worker.persist', **(saved | {'generation': 99}))),
+ 'outbox_full': reason(lambda: store.append_messages_batch(sid, [{'role': 'user', 'content': 'x' * 30000}])),
+ 'writable_canonical_fds': writable_fds(home)}
+ else:
+ stale = reason(lambda: transport('worker.persist', **saved))
+ adopted = transport('worker.adopt', **{k: v for k, v in scope.items() if k != 'epoch'})
+ store.adopt(adopted['owner_epoch'])
+ store.refresh_session_turn_lease(sid, 'owned-worker-lease')
+ output = {'stale': stale, 'epoch': adopted['owner_epoch'], 'pid': os.getpid(),
+ 'writable_canonical_fds': writable_fds(home)}
+ sys.stdout.write(json.dumps(output) + '\n'); sys.stdout.flush()
+ except Exception as exc:
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ sys.stdout.write(json.dumps({'fatal': repr(exc)}) + '\n'); sys.stdout.flush()
diff --git a/tests/gateway/test_worker_persistence.py b/tests/gateway/test_worker_persistence.py
new file mode 100644
index 00000000000..1df44a397d0
--- /dev/null
+++ b/tests/gateway/test_worker_persistence.py
@@ -0,0 +1,76 @@
+"""Separate worker, ordinary daemon, production private control and authenticated WS."""
+import asyncio
+import json
+import os
+from pathlib import Path
+import sqlite3
+import subprocess
+import sys
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket
+
+
+def test_worker_survives_owner_restart_without_repeating_tool(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'inert', 'base_url': 'http://127.0.0.1:9/v1'},
+ 'auxiliary': {'title_generation': {'enabled': False}}}))
+ 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='http://127.0.0.1:9/v1')
+ async def create(desc):
+ async with websocket(home, desc) as ws:
+ response = await rpc(ws, 'session.create', request_id='worker-session', source='cli')
+ assert 'result' in response, response
+ return response['result']['session_id']
+ with (tmp_path / 'worker.log').open('w+') as log:
+ worker = subprocess.Popen([sys.executable, str(root / 'tests/gateway/fixtures/persistence_worker.py')],
+ cwd=root, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, text=True)
+ def command(op, **params):
+ worker.stdin.write(json.dumps({'op': op, **params}) + '\n')
+ worker.stdin.flush()
+ import select
+ assert select.select([worker.stdout], [], [], 30)[0], 'worker response timeout'
+ raw = worker.stdout.readline()
+ log.flush(); log.seek(0)
+ assert raw, log.read()
+ result = json.loads(raw)
+ assert 'fatal' not in result, result
+ return result
+ try:
+ with daemon(root, home, env, barrier=False) as (owner, desc):
+ sid = asyncio.run(create(desc))
+ first = command('start', home=str(home), session_id=sid)
+ assert first['registered'], first
+ assert first['rows'] == 3 and first['lost_ack_replayed']
+ assert first['wrong_session'] == 'permission_denied'
+ assert first['wrong_profile'] == 'profile_mismatch'
+ assert first['wrong_generation'] == 'stale_generation'
+ assert first['conflict'] == 'admission_conflict'
+ assert first['outbox_full'] == 'outbox_full'
+ assert first['writable_canonical_fds'] == []
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ assert db.execute('SELECT COUNT(*) FROM messages WHERE session_id=?', (sid,)).fetchone()[0] == 3
+ assert db.execute('SELECT input_tokens FROM sessions WHERE id=?', (sid,)).fetchone()[0] == 11
+ owner.kill(); owner.wait(timeout=10)
+ with daemon(root, home, env, barrier=False):
+ second = command('adopt')
+ assert second['stale'] == 'stale_epoch'
+ assert second['epoch'] > first['epoch']
+ assert second['writable_canonical_fds'] == []
+ assert second['pid'] == first['pid'] == worker.pid
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ assert db.execute("SELECT COUNT(*) FROM messages WHERE content='tool-marker'").fetchone()[0] == 1
+ assert db.execute('SELECT input_tokens FROM sessions WHERE id=?', (sid,)).fetchone()[0] == 11
+ assert (home / 'tool-marker').read_text() == 'once'
+ print(json.dumps({'first': first, 'second': second}))
+ finally:
+ if worker.poll() is None:
+ worker.kill()
+ worker.wait(timeout=10)
+ worker.stdin.close(); worker.stdout.close()