The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(storage): publish worker outbox, hosted blobs and media dirs via utils
Teknium3996bf69ccc5
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.pyindex db913e9043b..c53e07a53e1 100644--- a/agent/runtime_session_store.py+++ b/agent/runtime_session_store.py@@ -9,7 +9,6 @@ import asyncioimport jsonimport osfrom pathlib import Path-import tempfileimport threading@@ -157,21 +156,9 @@ class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecyclif 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)+ from utils import atomic_write_bytes+ # Owner-only journal (the dir is 0700 too); the rename and its directory entry are durable.+ atomic_write_bytes(self.path, encoded, tmp_prefix='.pending-', mode=0o600, fsync_dir=True)def _session(self, session_id):if session_id != self.scope['session_id']:diff --git a/gateway/hosted_room_attachments.py b/gateway/hosted_room_attachments.pyindex c6922d37182..52000dc58f8 100644--- a/gateway/hosted_room_attachments.py+++ b/gateway/hosted_room_attachments.py@@ -447,29 +447,9 @@ class HostedRoomAttachmentStore:return self.blob_root / blob_iddef _write_blob(self, target: Path, data: bytes) -> None:- temp = self.blob_root / f".tmp-{secrets.token_hex(16)}"- descriptor = None- try:- descriptor = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(descriptor, "wb") as handle:- descriptor = None- handle.write(data)- handle.flush()- os.fsync(handle.fileno())- os.replace(temp, target)- os.chmod(target, 0o600)- try:- directory = os.open(self.blob_root, os.O_RDONLY)- try:- os.fsync(directory)- finally:- os.close(directory)- except OSError:- pass- finally:- if descriptor is not None:- os.close(descriptor)- temp.unlink(missing_ok=True)+ from utils import atomic_write_bytes+ # ``.tmp-`` staging names are what the orphan sweep reclaims after a crash.+ atomic_write_bytes(target, data, tmp_prefix=".tmp-", mode=0o600, fsync_dir=True)def _open_blob(self, *, blob_id: str, size: int) -> int:"""Open the regular blob file and fence its size against the durable row."""diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 87e0457bdba..7ffec680c22 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -14,6 +14,7 @@ import statimport tempfilefrom hermes_state_runtime import RuntimeStoreError+from utils import fsync_directorydef _media_root():@@ -115,16 +116,6 @@ def restore_attachments(payload):return {'media_urls': restore_native_media(data['media']), 'media_types': list(data['media_types'])}-def _sync_directory(path):- # Windows cannot open directories through os.open; file fsync still precedes ACK.- if os.name != 'nt':- fd = os.open(path, os.O_RDONLY)- try:- os.fsync(fd)- finally:- os.close(fd)--def _open_regular(path):if not path.is_absolute() or path.is_symlink():raise ValueError('native media must be a local regular file')@@ -160,7 +151,7 @@ def capture_native_media(paths):else:os.replace(temporary, target)for directory in (target.parent, root, root.parent, root.parent.parent, root.parent.parent.parent):- _sync_directory(directory)+ fsync_directory(directory)finally:for temporary in staged:temporary.unlink(missing_ok=True)diff --git a/tests/agent/test_runtime_session_store.py b/tests/agent/test_runtime_session_store.pyindex 0e3ddb67d48..63869948c52 100644--- a/tests/agent/test_runtime_session_store.py+++ b/tests/agent/test_runtime_session_store.py@@ -1,4 +1,5 @@import json+import osimport pytest@@ -91,6 +92,28 @@ def test_outbox_filesystem_failure_is_sticky(tmp_path, monkeypatch):store._outbox_owner.close()+def test_outbox_journal_survives_a_cross_device_rename(tmp_path, monkeypatch):+ """The journal publishes through utils.atomic_replace: a bind-mounted outbox whose rename+ fails EXDEV falls back to copy+fsync instead of failing every worker write, and the+ journal stays owner-only."""+ import errno+ import stat+ real_replace = os.replace+ def exdev_replace(src, dst):+ if str(dst).endswith('pending.json'):+ raise OSError(errno.EXDEV, 'cross-device link')+ return real_replace(src, dst)+ monkeypatch.setattr(os, 'replace', exdev_replace)+ store = RuntimeSessionStore(lambda *a, **k: {}, {'session_id': 's'}, tmp_path / 'private')+ try:+ journal = store.path+ assert json.loads(journal.read_text())['scope'] == {'session_id': 's'}+ assert stat.S_IMODE(journal.stat().st_mode) == 0o600+ assert [p.name for p in journal.parent.iterdir() if p.name.startswith('.pending-')] == []+ finally:+ store._outbox_owner.close()++def test_worker_store_persists_and_restores_the_tools_prefix_pin(tmp_path):"""persist_agent_tool_names writes the pin through the worker facade and a rebuilt workeragent reads it back from the same row (F26). Without the facade method the pin stays NULL