The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retain API image holders during native media cleanup
David Dudok de Wit8b32f2b237d2
diff --git a/gateway/session_hosted_attachments.py b/gateway/session_hosted_attachments.pyindex 7cacf43c00d..698592ddb1b 100644--- a/gateway/session_hosted_attachments.py+++ b/gateway/session_hosted_attachments.py@@ -72,8 +72,11 @@ def submission_payload(rpc, prompt, attachments=None):if not attachments:return {'text': prompt}from gateway.hosted_room_driver import validate_bound_task_manifest- from gateway.session_ingress_media import capture_native_media, restore_native_media+ from gateway.session_ingress_media import capture_native_media, restore_native_media, validate_media_batch_sizemanifest = validate_bound_task_manifest(attachments)+ # Each bound file is captured on its own, so the admission-wide cap is enforced here,+ # before any member is materialized.+ validate_media_batch_size(item['size'] for item in manifest)store = HostedRoomAttachmentStore(rpc.authority.db.db_path)references = []transferred = getattr(rpc, 'hosted_attachment_data', None)diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 3e6d5d9b54c..7a184fe5787 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -2,8 +2,8 @@The existing managed document cache supplies profile routing, delivery eligibilityand 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.+native bytes are released by ``release_admission_media`` once their row is+terminal and no live native input or retained API image context still holds them."""import hashlibfrom contextlib import suppress@@ -144,18 +144,47 @@ def _capture_file(path, limit, total, references, published):temporary.unlink(missing_ok=True)+def validate_media_batch_size(sizes):+ """Preflight validated manifest sizes before materializing any batch member."""+ from gateway.platforms.base import get_inbound_media_max_bytes, validate_inbound_media_size+ try:+ validate_inbound_media_size(sum(sizes), max_bytes=max(0, get_inbound_media_max_bytes()))+ except ValueError as exc:+ raise RuntimeStoreError('invalid_params') from exc++def admission_media_references(payload):- """Every retained ``native-inputs`` reference a committed payload owns."""+ """Native references eligible as deletion candidates after terminal settlement."""return list(payload.get('attachments_v1', {}).get('media', ())) + list(payload.get('native_text_v1', {}).get('media', ()))+def _held_media_paths(conn):+ # Project only references, not potentially large inline-image/history payloads.+ rows = conn.execute("""SELECT status, json_extract(payload_json,+ '$.attachments_v1.media', '$.native_text_v1.media', '$.api_turn_v1.media')+ FROM session_admissions WHERE status!='terminal'+ OR json_type(payload_json, '$.api_turn_v1.media') IS NOT NULL""").fetchall()+ held = set()+ for status, encoded in rows:+ attachments, native, api = json.loads(encoded)+ # API images remain canonical history context after the turn completes.+ references = list(api or ())+ if status != 'terminal':+ references.extend(attachments or ())+ references.extend(native or ())+ held.update(reference['path'] for reference in references)+ return held++def release_admission_media(db, admission_id):- """Delete retained bytes of a terminal admission unless a live row still shares them.+ """Delete eligible terminal native bytes unless another retained input holds them.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 path they reference stays on disk. Storage is per+ execute, so any path they reference stays on disk; API image references stay+ on disk in every status because they remain history context after settlement,+ and are holders only, never deletion candidates. Storage is per``<digest>/<basename>`` and a row replays exactly the path it references, so holdingis per path too: equal bytes admitted under another basename are a separate filewhose own row decides its release.@@ -169,9 +198,7 @@ def release_admission_media(db, admission_id):return 0root = _media_root()with db._read_ctx() as conn:- live = conn.execute("SELECT payload_json FROM session_admissions WHERE status!='terminal'").fetchall()- held = {reference['path'] for saved in live- for reference in admission_media_references(json.loads(saved[0]))}+ held = _held_media_paths(conn)released = 0for reference in mine:path = Path(reference['path'])diff --git a/tests/gateway/test_api_media_retention.py b/tests/gateway/test_api_media_retention.pynew file mode 100644index 00000000000..a52d92ade30--- /dev/null+++ b/tests/gateway/test_api_media_retention.py@@ -0,0 +1,71 @@+"""Native scratch cleanup must not retire API image context sharing its bytes."""+import base64+from pathlib import Path+from types import SimpleNamespace++import pytest++from gateway import hosted_rooms+from gateway.hosted_room_attachments import HostedRoomAttachmentStore+from gateway.platforms import base+from gateway.session_api_turn import admit_api_turn+from gateway.session_hosted_attachments import submission_payload+from gateway.session_ingress_media import _media_root, admit_attachments, release_admission_media, restore_native_media+from hermes_state_runtime import RuntimeStoreError, admit_session_input, claim_session_input, settle_session_input+from tests.gateway.test_api_cutover_contract import api, owner # noqa: F401++PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=')+++def settled_native(owner, paths):+ owner.db.create_session('native-candidate', source='cli')+ payload = {'text': 'native', **admit_attachments([{'path': str(path), 'mime': 'image/png'} for path in paths])}+ row = admit_session_input(owner.db, epoch=owner.epoch, principal_id='native-person',+ session_id='native-candidate', request_id='native', payload=payload)+ started = claim_session_input(owner.db, epoch=owner.epoch, session_id=row['target_session_id'])+ return settle_session_input(owner.db, epoch=owner.epoch, admission_id=row['admission_id'],+ generation=started['generation'], outcome='completed')++[email protected]('settled', [False, True], ids=['queued-holder', 'terminal-holder'])+def test_api_image_survives_native_cleanup_while_unique_native_bytes_are_collected(api, owner, settled):+ _, _, row = admit_api_turn(api, session_id='image-holder', request_id='api-image',+ user_message=[{'type': 'image_url', 'image_url': {+ 'url': 'data:image/png;base64,' + base64.b64encode(PNG).decode()}}], conversation_history=[])+ reference = row['payload']['api_turn_v1']['media'][0]+ if settled:+ started = claim_session_input(owner.db, epoch=owner.epoch, session_id=row['target_session_id'])+ settle_session_input(owner.db, epoch=owner.epoch, admission_id=row['admission_id'],+ generation=started['generation'], outcome='completed')+ # A settled API turn is a holder, never a deletion candidate.+ assert release_admission_media(owner.db, row['admission_id']) == 0+ unique = base.get_image_cache_dir() / 'unique.png'+ unique.write_bytes(PNG + b'unique')+ native = settled_native(owner, [base.get_image_cache_dir() / Path(reference['path']).name, unique])+ shared, unique_reference = native['payload']['attachments_v1']['media']+ assert shared == reference+ assert release_admission_media(owner.db, native['admission_id']) == 1+ assert not Path(unique_reference['path']).exists()+ assert Path(restore_native_media([reference])[0]).read_bytes() == PNG+++def test_hosted_batch_total_is_rejected_before_any_capture(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ db_path = tmp_path / 'state.db'+ hosted_rooms.create_room(db_path, room_id='room', name='Room', authority_gateway_id='home',+ members=[dict(member_id='member', profile='default', handle='member')])+ store = HostedRoomAttachmentStore(db_path)+ manifest = []+ for index in range(2):+ saved = store.put(room_id='room', upload_id=f'upload-{index}', kind='file', name=f'{index}.txt',+ mime='text/plain', data=bytes([65 + index]) * 2048)+ manifest.append({key: saved[key] for key in ('attachment_id', 'kind', 'name', 'size', 'mime')})+ store.commit_message(room_id='room', event_id='source', manifest=manifest, recipient_member_ids=['member'])+ bound = [{**item, 'event_id': 'source'} for item in manifest]+ rpc = SimpleNamespace(authority=SimpleNamespace(db=SimpleNamespace(db_path=db_path)), room_id='room', member_id='member')+ monkeypatch.setattr(base, 'get_inbound_media_max_bytes', lambda: 3072)+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ submission_payload(rpc, 'read', bound)+ assert not _media_root().exists()+ monkeypatch.setattr(base, 'get_inbound_media_max_bytes', lambda: 4096)+ assert submission_payload(rpc, 'read', bound)['text'].count('[Shared attachment] file:') == 2