Skip to content

The agent that grows with you

fix: freeze retry journals and retain exclusive worker outbox ownership

Tekniuma8c163afbcf5
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.py
index 2acf9993cf1..8f79c306ad9 100644
--- a/agent/runtime_session_store.py
+++ b/agent/runtime_session_store.py
@@ -84,15 +84,32 @@ class RuntimeSessionStore:
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(encoding="utf-8"))
- 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)
+ from gateway.status import _try_acquire_file_lock
+ lock_path = self.path.parent / 'owner.lock'
+ if lock_path.is_symlink():
+ raise WorkerPersistenceError('unsafe_outbox')
+ self._outbox_owner = lock_path.open('a+', encoding='utf-8')
+ os.chmod(lock_path, 0o600)
+ if not _try_acquire_file_lock(self._outbox_owner):
+ self._outbox_owner.close()
+ raise WorkerPersistenceError('outbox_in_use')
+ try:
+ if self.path.exists():
+ if self.path.stat().st_size > max_bytes:
+ raise WorkerPersistenceError('outbox_full')
+ self.journal = json.loads(self.path.read_text(encoding="utf-8"))
+ 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)
+ except Exception:
+ self._outbox_owner.close()
+ raise
def _save(self, journal):
+ if self._outbox_owner.closed:
+ raise WorkerPersistenceError('outbox_closed')
encoded = json.dumps(journal, ensure_ascii=True, allow_nan=False, separators=(',', ':')).encode()
if len(encoded) > self.max_bytes:
self.failure = 'outbox_full'
@@ -125,7 +142,7 @@ class RuntimeSessionStore:
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['pending'].append(json.loads(json.dumps(entry, allow_nan=False)))
candidate['next_sequence'] += 1
self._save(candidate)
self.journal = candidate
@@ -196,4 +213,8 @@ class RuntimeSessionStore:
return True
def close(self):
- self.flush_token_counts()
+ with self.lock:
+ try:
+ self.flush_token_counts()
+ finally:
+ self._outbox_owner.close()
diff --git a/tests/agent/test_runtime_session_store.py b/tests/agent/test_runtime_session_store.py
new file mode 100644
index 00000000000..408d0ee28a2
--- /dev/null
+++ b/tests/agent/test_runtime_session_store.py
@@ -0,0 +1,54 @@
+import json
+
+import pytest
+
+from agent.runtime_session_store import RuntimeSessionStore, WorkerPersistenceError
+
+
+def test_outbox_freezes_failed_payload_and_reopens_exclusively(tmp_path):
+ scope = {'session_id': 's', 'execution_id': 'w', 'epoch': 1}
+ rows = [{'role': 'user', 'content': 'frozen'}]
+ def unavailable(method, **params):
+ rows[0]['content'] = 'caller changed'
+ raise TimeoutError('offline')
+ store = RuntimeSessionStore(unavailable, scope, tmp_path / 'private')
+ try:
+ with pytest.raises(TimeoutError):
+ store.append_messages_batch('s', rows)
+ disk = json.loads(store.path.read_text())
+ assert disk['pending'][0]['payload']['messages'][0]['content'] == 'frozen'
+ assert store.journal['pending'] == disk['pending']
+ with pytest.raises(WorkerPersistenceError, match='outbox_in_use'):
+ RuntimeSessionStore(unavailable, scope, tmp_path / 'private')
+ with pytest.raises(WorkerPersistenceError, match='offline'):
+ store.queue_token_counts('s', input_tokens=1)
+ finally:
+ with pytest.raises(WorkerPersistenceError, match='offline'):
+ store.close()
+ seen = []
+ def commit(method, **params):
+ seen.append(params)
+ return {'count': 1, 'annotations': [{'_row_id': 42}]}
+ restored = RuntimeSessionStore(commit, scope, tmp_path / 'private')
+ try:
+ assert restored.retry_pending()[0]['count'] == 1
+ assert seen[0]['payload']['messages'][0]['content'] == 'frozen'
+ assert json.loads(restored.path.read_text())['pending'] == []
+ assert restored.path.stat().st_mode & 0o077 == 0
+ finally:
+ restored.close()
+
+
+def test_outbox_capacity_failure_does_not_advance_or_discard(tmp_path):
+ def unavailable(*args, **kwargs):
+ raise TimeoutError('offline')
+ store = RuntimeSessionStore(unavailable, {'session_id': 's'}, tmp_path / 'private', max_bytes=500)
+ try:
+ before = store.path.read_bytes()
+ with pytest.raises(WorkerPersistenceError, match='outbox_full'):
+ store.append_messages_batch('s', [{'role': 'user', 'content': 'x' * 1000}])
+ assert store.path.read_bytes() == before
+ assert store.failure == 'outbox_full'
+ finally:
+ with pytest.raises(WorkerPersistenceError, match='outbox_full'):
+ store.close()