The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retained native media always has an admission owner (X7, reported by @Xipong)
teknium166a868abe40a
diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 7ef706bd16c..3e6d5d9b54c 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -6,6 +6,7 @@ retained bytes are released per admission by ``release_admission_media`` once throw is terminal and no live (queued/started/unknown) row still references them."""import hashlib+from contextlib import suppressimport jsonimport osfrom pathlib import Path@@ -81,50 +82,66 @@ def capture_native_media(paths):# ``gateway.max_inbound_media_bytes`` bounds the whole admission, not each file: with# per-file caps alone ten attachments could commit ~1.25 GiB of retained bytes per turn.total = 0- for value in paths:- path = Path(value)+ # Files THIS batch published. No admission exists until every file is accepted, so a+ # rejected batch rolls its own publications back; a target that already existed belongs+ # to an earlier admission and is never touched.+ published = []+ try:+ for value in paths:+ _capture_file(Path(value), limit, total, references, published)+ total = sum(reference['size'] for reference in references)+ except BaseException:+ for target in published:+ target.unlink(missing_ok=True)+ with suppress(OSError):+ target.parent.rmdir()+ raise+ return references+++def _capture_file(path, limit, total, references, published):+ from gateway.platforms.base import validate_inbound_media_size+ try:+ source = _open_regular(path)+ except (OSError, ValueError) as exc:+ raise RuntimeStoreError('invalid_params') from exc+ with source:+ root = _media_root()+ if root.resolve() != root:+ raise RuntimeStoreError('invalid_params')+ root.mkdir(mode=0o700, parents=True, exist_ok=True)+ fd, name = tempfile.mkstemp(prefix='.capture-', dir=root)+ temporary = Path(name)try:- source = _open_regular(path)- except (OSError, ValueError) as exc:- raise RuntimeStoreError('invalid_params') from exc- with source:- root = _media_root()- if root.resolve() != root:+ digest, size = hashlib.sha256(), 0+ with os.fdopen(fd, 'wb') as output:+ while chunk := source.read(1024 * 1024):+ size += len(chunk)+ try:+ validate_inbound_media_size(total + size, max_bytes=limit)+ except ValueError as exc:+ raise RuntimeStoreError('invalid_params') from exc+ digest.update(chunk)+ output.write(chunk)+ output.flush()+ os.fsync(output.fileno())+ target = root / digest.hexdigest() / path.name+ if target.parent.resolve() != target.parent:raise RuntimeStoreError('invalid_params')- root.mkdir(mode=0o700, parents=True, exist_ok=True)- fd, name = tempfile.mkstemp(prefix='.capture-', dir=root)- temporary = Path(name)- try:- digest, size = hashlib.sha256(), 0- with os.fdopen(fd, 'wb') as output:- while chunk := source.read(1024 * 1024):- size += len(chunk)- try:- validate_inbound_media_size(total + size, max_bytes=limit)- except ValueError as exc:- raise RuntimeStoreError('invalid_params') from exc- digest.update(chunk)- output.write(chunk)- output.flush()- os.fsync(output.fileno())- target = root / digest.hexdigest() / path.name- if target.parent.resolve() != target.parent:- raise RuntimeStoreError('invalid_params')- target.parent.mkdir(mode=0o700, exist_ok=True)- reference = {'path': str(target), 'sha256': digest.hexdigest(), 'size': size}- if target.exists():- # An earlier admission can reference this file. Never repair it by- # overwriting accepted bytes, even when a retry has the same digest.- restore_native_media([reference])- else:- os.replace(temporary, target)- for directory in (target.parent, root, root.parent, root.parent.parent, root.parent.parent.parent):- _sync_directory(directory)- references.append(reference)- total += size- finally:- temporary.unlink(missing_ok=True)- return references+ target.parent.mkdir(mode=0o700, exist_ok=True)+ reference = {'path': str(target), 'sha256': digest.hexdigest(), 'size': size}+ if target.exists():+ # An earlier admission can reference this file. Never repair it by+ # overwriting accepted bytes, even when a retry has the same digest.+ restore_native_media([reference])+ else:+ os.replace(temporary, target)+ published.append(target)+ for directory in (target.parent, root, root.parent, root.parent.parent, root.parent.parent.parent):+ _sync_directory(directory)+ references.append(reference)+ finally:+ temporary.unlink(missing_ok=True)def admission_media_references(payload):@@ -138,7 +155,10 @@ def release_admission_media(db, admission_id):Terminal rows are exact-retry evidence by digest only; their bytes are notreplayed. Rows that are not terminal (queued, started, unknown) may still- execute, so any digest they reference stays on disk.+ execute, so any path they reference stays on disk. Storage is per+ ``<digest>/<basename>`` and a row replays exactly the path it references, so holding+ is per path too: equal bytes admitted under another basename are a separate file+ whose own row decides its release."""from hermes_state_runtime import get_session_admissionrow = get_session_admission(db, admission_id=admission_id)@@ -150,12 +170,12 @@ def release_admission_media(db, admission_id):root = _media_root()with db._read_ctx() as conn:live = conn.execute("SELECT payload_json FROM session_admissions WHERE status!='terminal'").fetchall()- held = {reference['sha256'] for saved in live+ held = {reference['path'] for saved in livefor reference in admission_media_references(json.loads(saved[0]))}released = 0for reference in mine:path = Path(reference['path'])- if reference['sha256'] in held or path.parent.parent != root or path.parent.name != reference['sha256']:+ if reference['path'] in held or path.parent.parent != root or path.parent.name != reference['sha256']:continuetry:path.unlink()diff --git a/tests/gateway/test_native_media_ownership.py b/tests/gateway/test_native_media_ownership.pynew file mode 100644index 00000000000..db2d4706306--- /dev/null+++ b/tests/gateway/test_native_media_ownership.py@@ -0,0 +1,60 @@+"""Retained native bytes always have an owner: no orphan from a rejected batch, no leftover+when equal bytes were admitted under different basenames."""+from pathlib import Path++import pytest++from gateway.session_ingress_media import _media_root, capture_native_media, release_admission_media+from hermes_state import SessionDB+from hermes_state_runtime import admit_session_input, begin_runtime_epoch, cancel_session_input++PNG = b'\x89PNG\r\n\x1a\n' + b'\x00' * 8+++def _staged(name, size):+ from gateway.platforms.base import get_image_cache_dir+ path = get_image_cache_dir() / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(PNG + b'\x00' * max(0, size - len(PNG)))+ return path+++def test_rejected_batch_publishes_nothing(tmp_path, monkeypatch):+ """(a) File B trips the aggregate budget after A was published: A must not stay retained+ with no admission to release it — while a file an EARLIER capture published (and so an+ earlier admission may own) is not rolled back with the rejected batch."""+ from gateway.platforms import base+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(base, 'get_inbound_media_max_bytes', lambda: 3 * 1024)+ from hermes_state_runtime import RuntimeStoreError+ owned = Path(capture_native_media([_staged('owned.png', 512)])[0]['path'])+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ capture_native_media([_staged('owned.png', 512), _staged('a.png', 2 * 1024), _staged('b.png', 2 * 1024)])+ assert owned.exists()+ assert [p.name for p in _media_root().iterdir()] == [owned.parent.name]+++def test_equal_bytes_under_different_basenames_are_fully_released(tmp_path, monkeypatch):+ """(b) Two admissions retain the same digest as ``<digest>/a.png`` and ``<digest>/b.png``.+ Cancelling A while B is live keeps A's bytes (shared digest); after B is terminal too,+ nothing under the digest directory may remain."""+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ db = SessionDB(db_path=tmp_path / 'state.db')+ db.create_session('s', source='test')+ epoch = begin_runtime_epoch(db, instance_id='current')+ rows = []+ for name in ('a.png', 'b.png'):+ media = capture_native_media([_staged(name, 64)])+ payload = {'text': name, 'attachments_v1': {'media': media, 'media_types': ['image/png']}}+ rows.append(admit_session_input(db, epoch=epoch, principal_id='p', session_id='s',+ request_id=name, payload=payload))+ first, second = rows+ digest_dir = _media_root() / first['payload']['attachments_v1']['media'][0]['sha256']+ assert sorted(p.name for p in digest_dir.iterdir()) == ['a.png', 'b.png']+ cancel_session_input(db, epoch=epoch, admission_id=first['admission_id'])+ release_admission_media(db, first['admission_id'])+ assert (digest_dir / 'b.png').exists(), 'bytes a live admission still needs must survive'+ cancel_session_input(db, epoch=epoch, admission_id=second['admission_id'])+ release_admission_media(db, second['admission_id'])+ assert not digest_dir.exists(), list(digest_dir.iterdir())+ assert list(_media_root().iterdir()) == []