The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(worker-outbox): reconcile a retained outbox under the verified successor's adoption
Teknium14dd2b98fe1b
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex e8d1e5f0d6c..2eaec31292e 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -286,7 +286,7 @@ def execute(frame, channel):adopted = rpc('worker.adopt', **{k: v for k, v in scope.items() if k != 'epoch'})if adopted['owner_epoch'] != scope['epoch']:raise RuntimeError('stale_epoch')- store = RuntimeSessionStore(rpc, scope, outbox_dir(frame['home'], scope['execution_id']))+ store = RuntimeSessionStore(rpc, scope, outbox_dir(frame['home'], scope['execution_id']), adopted)from gateway.session_kanban import bind_worker_contextbind_worker_context(frame)# Background processes a previous admission of this session started outlive that workerdiff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.pyindex 94e1ee49c88..b4053951858 100644--- a/agent/runtime_session_store.py+++ b/agent/runtime_session_store.py@@ -110,7 +110,7 @@ class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecycladoption. 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):+ def __init__(self, rpc, scope, outbox_dir, adopted=None, *, max_bytes=4 * 1024 * 1024):self.rpc = rpcself.scope = dict(scope)self.max_bytes = max_bytes@@ -135,13 +135,19 @@ class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecyclif self.path.stat().st_size > max_bytes:raise WorkerPersistenceError('outbox_full')self.journal = json.loads(self.path.read_text(encoding="utf-8-sig"))- if self.journal['scope'] != self.scope:- raise WorkerPersistenceError('outbox_scope_mismatch')+ reconciled = self.journal['scope'] != self.scope+ if reconciled:+ self._reconcile_adopted(adopted)else:+ reconciled = Falseself.journal = {'scope': self.scope, 'next_sequence': 1, 'pending': []}self._save(self.journal)if self.journal['pending']:self.retry_pending()+ if reconciled and self.scope != dict(scope):+ # Replay must land the journal exactly on the adopted assignment (a pending+ # publication moves it to the child); anything else is not this successor's outbox.+ raise WorkerPersistenceError('outbox_scope_mismatch')if is_worker_process():from tools.async_delegation_worker import bind_worker_delegation_storebind_worker_delegation_store(self)@@ -149,6 +155,35 @@ class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecyclself._outbox_owner.close()raise+ def _reconcile_adopted(self, adopted):+ """Carry a retained outbox across verified owner replacement.++ ``adopted`` is the separately authenticated ``worker.adopt`` result for the requested+ scope; never self-adopt. Only the owner epoch (forward) and the physical target may+ differ from the journal (a same-epoch restart can still find the target rotated).+ Pending entries replay under the journal's own target with the adopted epoch, so an+ exact lost-ACK retry resolves its original receipt instead of creating a second one;+ the constructor then requires the replayed scope to equal the adopted one.+ """+ old, new = self.journal['scope'], self.scope+ fixed = set(new) - {'epoch', 'session_id'}+ if (not isinstance(adopted, dict) or set(old) != set(new)+ or any(old[key] != new[key] for key in fixed)+ or adopted.get('execution_id') != new.get('execution_id')+ or adopted.get('generation') != new.get('generation')+ or adopted.get('session_id') != new.get('session_id')+ or adopted.get('owner_epoch') != new.get('epoch') or adopted.get('status') != 'running'+ or type(old.get('epoch')) is not int or type(new.get('epoch')) is not int+ or old['epoch'] > new['epoch']+ # Only a pending publication can still move the target; replay must prove it.+ or (old['session_id'] != new['session_id'] and not any(+ entry['operation'] == 'compression.publish' for entry in self.journal['pending']))):+ raise WorkerPersistenceError('outbox_scope_mismatch')+ candidate = dict(self.journal, scope=dict(old, epoch=new['epoch']))+ self._save(candidate)+ self.scope = candidate['scope']+ self.journal = candidate+def _save(self, journal):if self._outbox_owner.closed:raise WorkerPersistenceError('outbox_closed')diff --git a/tests/agent/test_worker_outbox_adoption.py b/tests/agent/test_worker_outbox_adoption.pynew file mode 100644index 00000000000..fe8b93a0fa1--- /dev/null+++ b/tests/agent/test_worker_outbox_adoption.py@@ -0,0 +1,97 @@+"""A retained worker outbox follows verified owner adoption (epoch replacement, physical-target+rotation) without a second receipt, and is still refused for anything but the verified successor."""+import pytest++from agent.runtime_session_store import RuntimeSessionStore, WorkerPersistenceError+from hermes_state import SessionDB+from hermes_state_runtime import (adopt_worker_execution, begin_runtime_epoch,+ mutate_worker_execution, register_worker_execution)+++def _owner(db):+ return lambda method, **params: mutate_worker_execution(db, **params)+++def _lose_ack(db, store):+ def lost(method, **params):+ mutate_worker_execution(db, **params) # commits for real; only the reply is lost+ raise TimeoutError('lost_ack')+ store.rpc = lost+++def _receipts(db):+ return db._read_one('SELECT COUNT(*) FROM worker_receipts')[0]+++def test_lost_ack_receipt_reconciles_under_the_adopted_epoch_once(tmp_path):+ path, outbox = tmp_path / 'state.db', tmp_path / 'outbox'+ db = SessionDB(path)+ db.create_session('s', 'cli')+ first = begin_runtime_epoch(db, instance_id='first')+ scope = dict(epoch=first, execution_id='worker', session_id='s', generation=0)+ register_worker_execution(db, **scope, kind='compute', adoption_secret='private')+ store = RuntimeSessionStore(_owner(db), scope, outbox)+ _lose_ack(db, store)+ with pytest.raises(TimeoutError):+ store.queue_token_counts('s', input_tokens=10)+ store._outbox_owner.close() # the worker exited with its durable pending journal+ db.close()+ db = SessionDB(path) # owner replaced+ try:+ second = begin_runtime_epoch(db, instance_id='second')+ successor = dict(scope, epoch=second)+ # Not the verified successor: no adoption proof, or proof for another epoch/execution.+ adopted = adopt_worker_execution(db, epoch=second, execution_id='worker', session_id='s',+ generation=0, adoption_secret='private')+ for proof in (None, dict(adopted, owner_epoch=first), dict(adopted, execution_id='other')):+ with pytest.raises(WorkerPersistenceError, match='outbox_scope_mismatch'):+ RuntimeSessionStore(_owner(db), successor, outbox, adopted=proof)+ with pytest.raises(WorkerPersistenceError, match='outbox_scope_mismatch'):+ RuntimeSessionStore(_owner(db), dict(successor, generation=1), outbox, adopted=adopted)+ assert _receipts(db) == 1+ reopened = RuntimeSessionStore(_owner(db), successor, outbox, adopted=adopted)+ try:+ assert reopened.journal['pending'] == [] and reopened.scope == successor+ reopened.queue_token_counts('s', input_tokens=5)+ assert _receipts(db) == 2 # sequence 1 resolved as its original receipt, then 2+ assert db.get_session('s')['input_tokens'] == 15+ finally:+ reopened.close()+ finally:+ db.close()+++def test_pending_publication_follows_adoption_onto_the_rotated_target(tmp_path):+ path, outbox = tmp_path / 'state.db', tmp_path / 'outbox'+ db = SessionDB(path)+ db.create_session('root', 'cli', system_prompt='PREFIX')+ first = begin_runtime_epoch(db, instance_id='first')+ scope = dict(epoch=first, execution_id='worker', session_id='root', generation=0)+ register_worker_execution(db, **scope, kind='compute', adoption_secret='private')+ store = RuntimeSessionStore(_owner(db), scope, outbox)+ assert store.try_acquire_compression_lock('root', 'holder')+ _lose_ack(db, store)+ with pytest.raises(TimeoutError):+ store.publish_compression_child(parent_session_id='root', child_session_id='child', source='cli',+ messages=[{'role': 'assistant', 'content': 'SUMMARY'}], system_prompt='PREFIX',+ compression_lock_holder='holder')+ store._outbox_owner.close()+ db.close()+ db = SessionDB(path)+ try:+ second = begin_runtime_epoch(db, instance_id='second')+ adopted = adopt_worker_execution(db, epoch=second, execution_id='worker', session_id='child',+ generation=0, adoption_secret='private')+ receipts = _receipts(db)+ reopened = RuntimeSessionStore(_owner(db), dict(scope, epoch=second, session_id='child'),+ outbox, adopted=adopted)+ try:+ assert reopened.journal['pending'] == []+ assert reopened.scope == dict(scope, epoch=second, session_id='child')+ assert _receipts(db) == receipts+ assert db._read_one('SELECT COUNT(*) FROM sessions WHERE id=?', ('child',))[0] == 1+ reopened.append_messages_batch('child', [{'role': 'user', 'content': 'next'}])+ finally:+ reopened.close()+ finally:+ db.close()