The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): cap attachments per admission and release retained bytes on settlement/cancel
teknium1181f98f5b33a
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 92f270e5297..22f8e9077e7 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -265,6 +265,8 @@ class SessionAuthority:async def cancel_queued(self, actor, ref, admission_id):await self.receipt(actor, ref, admission_id)row = cancel_session_input(self.db, epoch=self.epoch, admission_id=admission_id)+ from gateway.session_ingress_media import release_admission_media+ release_admission_media(self.db, admission_id)self._publish_pending(ref)return self._receipt(row)@@ -402,6 +404,8 @@ class SessionAuthority:response=response, outcome=outcome,result=self.pending_results.pop(admission_id, None))live.controls.snapshot(ref.session_id, None)+ from gateway.session_ingress_media import release_admission_media+ release_admission_media(self.db, admission_id)self._publish_pending(ref)live.event_stream.publish(ref.session_id, {'text': response, 'content': response, 'admission_id': admission_id,diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 5b8133546d3..7ef706bd16c 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -1,10 +1,12 @@"""Immutable local-media references for owner-only native admission.The existing managed document cache supplies profile routing, delivery eligibility-and upload limits. Its flat age-based cleanup skips this retained subdirectory.-There is deliberately no GC until it can account for queued AND unknown rows.+and upload limits. Its flat age-based cleanup skips this retained subdirectory:+retained bytes are released per admission by ``release_admission_media`` once the+row is terminal and no live (queued/started/unknown) row still references them."""import hashlib+import jsonimport osfrom pathlib import Pathimport stat@@ -76,6 +78,9 @@ def capture_native_media(paths):from gateway.platforms.base import get_inbound_media_max_bytes, validate_inbound_media_sizereferences = []limit = max(0, get_inbound_media_max_bytes())+ # ``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 = 0for value in paths:path = Path(value)try:@@ -95,7 +100,7 @@ def capture_native_media(paths):while chunk := source.read(1024 * 1024):size += len(chunk)try:- validate_inbound_media_size(size, max_bytes=limit)+ validate_inbound_media_size(total + size, max_bytes=limit)except ValueError as exc:raise RuntimeStoreError('invalid_params') from excdigest.update(chunk)@@ -116,11 +121,51 @@ def capture_native_media(paths):for directory in (target.parent, root, root.parent, root.parent.parent, root.parent.parent.parent):_sync_directory(directory)references.append(reference)+ total += sizefinally:temporary.unlink(missing_ok=True)return references+def admission_media_references(payload):+ """Every retained ``native-inputs`` reference a committed payload owns."""+ return list(payload.get('attachments_v1', {}).get('media', ())) + list(+ payload.get('native_text_v1', {}).get('media', ()))+++def release_admission_media(db, admission_id):+ """Delete retained bytes of a terminal admission unless a live row still shares them.++ Terminal rows are exact-retry evidence by digest only; their bytes are not+ replayed. Rows that are not terminal (queued, started, unknown) may still+ execute, so any digest they reference stays on disk.+ """+ from hermes_state_runtime import get_session_admission+ row = get_session_admission(db, admission_id=admission_id)+ if row is None or row['status'] != 'terminal':+ return 0+ mine = admission_media_references(row['payload'])+ if not mine:+ return 0+ 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+ for reference in admission_media_references(json.loads(saved[0]))}+ released = 0+ for reference in mine:+ path = Path(reference['path'])+ if reference['sha256'] in held or path.parent.parent != root or path.parent.name != reference['sha256']:+ continue+ try:+ path.unlink()+ released += 1+ path.parent.rmdir()+ except OSError:+ continue+ return released++def restore_native_media(references):if not references:return []diff --git a/tests/gateway/test_native_media_budget.py b/tests/gateway/test_native_media_budget.pynew file mode 100644index 00000000000..d26bbe20bcb--- /dev/null+++ b/tests/gateway/test_native_media_budget.py@@ -0,0 +1,83 @@+"""Public attachments are bounded per admission and their retained bytes are released."""+from types import SimpleNamespace++import pytest++from gateway.session_authority import LiveSession, SessionAuthority+from gateway.session_contract import Principal, SessionRef, Submission+from hermes_state import SessionDB+from hermes_state_runtime import RuntimeStoreError, begin_runtime_epoch, list_session_admissions++PNG = b'\x89PNG\r\n\x1a\n' + b'\x00' * 8+++def _authority(tmp_path, monkeypatch):+ 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')+ authority = SessionAuthority(SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False)),+ profile_id='owned', instance_id='current', db=db, epoch=epoch)+ authority.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='human'), 'route')+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ return db, authority+++def _staged(tmp_path, name, size):+ from gateway.platforms.base import get_image_cache_dir+ path = get_image_cache_dir() / name+ path.write_bytes(PNG + b'\x00' * max(0, size - len(PNG)))+ return {'path': str(path), 'mime': 'image/png'}+++def _submit(authority, request_id, attachments):+ actor = Principal('human', 'owned', frozenset({'session:submit', 'session:control'}), 'cli')+ return authority.submit(actor, Submission(request_id=request_id, ref=SessionRef('owned', 's'),+ payload={'text': 'hi', 'attachments': attachments}, intent='queue'))+++async def test_attachment_cap_is_per_admission_not_per_file(tmp_path, monkeypatch):+ from gateway.platforms import base+ monkeypatch.setattr(base, 'get_inbound_media_max_bytes', lambda: 3 * 1024)+ db, authority = _authority(tmp_path, monkeypatch)+ with db:+ files = [_staged(tmp_path, f'part{i}.png', 2 * 1024) for i in range(2)]+ # Each file is under the cap; together they are not.+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ await _submit(authority, 'too-big', files)+ assert list_session_admissions(db, session_id='s', pending_only=False) == []+ receipt = await _submit(authority, 'fits', files[:1])+ assert receipt.status == 'queued'+++async def test_retained_bytes_are_released_after_cancel_and_settlement(tmp_path, monkeypatch):+ from gateway.session_ingress_media import _media_root, admission_media_references+ db, authority = _authority(tmp_path, monkeypatch)+ actor = Principal('human', 'owned', frozenset({'session:submit', 'session:control'}), 'cli')+ ref = SessionRef('owned', 's')+ with db:+ shared = _staged(tmp_path, 'shared.png', 64)+ first = await _submit(authority, 'first', [shared])+ second = await _submit(authority, 'second', [shared])+ row = next(r for r in list_session_admissions(db, session_id='s') if r['admission_id'] == first.admission_id)+ retained = admission_media_references(row['payload'])[0]['path']+ from pathlib import Path+ assert Path(retained).parent.parent == _media_root() and Path(retained).exists()+ # Same digest, two live rows: cancelling one must keep the bytes the other still needs.+ await authority.cancel_queued(actor, ref, first.admission_id)+ assert Path(retained).exists()+ # Settling the last live referent (through the real drain loop) releases them.+ from gateway import session_finite+ async def execute(authority, ref, row):+ assert Path(retained).exists(), 'bytes must survive until the turn has settled'+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)+ await authority._drain(ref)+ settled = next(r for r in list_session_admissions(db, session_id='s', pending_only=False)+ if r['admission_id'] == second.admission_id)+ assert settled['status'] == 'terminal' and settled['outcome'] == 'completed'+ assert not Path(retained).exists()+ assert not Path(retained).parent.exists()+ assert list(_media_root().iterdir()) == []