The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): hold captured media from capture until its admission commits
Teknium15cd9a82eea5
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex d0ecd63c40f..ddf416d7c7d 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -314,6 +314,11 @@ class SessionAuthority:async def admit_native(self, event):"""Await current connector policy, then commit before ACK or scheduling execution."""+ from gateway.session_ingress_media import capture_lease+ with capture_lease(): # captured bytes are held from capture until commit or refusal+ return await self._admit_native(event)++ async def _admit_native(self, event):import jsonfrom gateway.session_envelope import prepare_native, restore_nativeself._require_admission_open()@@ -334,11 +339,18 @@ class SessionAuthority:def _admit_native_write(self, *, principal_id, session_id, request_id, payload, authorize):# Off the loop and in admission order: the redelivery reconcile reads the ledger it decides# against, so a concurrent first delivery of the same message cannot slip between them.- from gateway.session_ingress_media import reconcile_native_retry- payload = reconcile_native_retry(self.db, principal_id=principal_id, session_id=session_id,- request_id=request_id, payload=payload)- return admit_session_input(self.db, epoch=self.epoch, principal_id=principal_id, session_id=session_id,- request_id=request_id, payload=payload, _authorize_write=authorize)+ from gateway.session_ingress_media import drop_capture_lease, reconcile_native_retry, release_unheld_media+ fresh = payload.get('native_text_v1', {}).get('media', [])+ try:+ payload = reconcile_native_retry(self.db, principal_id=principal_id, session_id=session_id,+ request_id=request_id, payload=payload)+ return admit_session_input(self.db, epoch=self.epoch, principal_id=principal_id, session_id=session_id,+ request_id=request_id, payload=payload, _authorize_write=authorize)+ except Exception:+ # A refused admission owns nothing it captured (unless another admission holds the same bytes).+ drop_capture_lease()+ release_unheld_media(self.db, fresh, retain_history=False)+ raisedef _admitted(self, ref, event, row):if event is not None:@@ -396,7 +408,9 @@ class SessionAuthority:async with self.sessions[request.ref.session_id].mutation_lock:# Deletion can retire this session while the caller waits on its writer.self.authorize(actor, request.ref, 'session:submit')- return await self._submit(actor, request, _authorize_write=_authorize_write)+ from gateway.session_ingress_media import capture_lease+ with capture_lease(): # captured bytes are held from capture until commit or refusal+ return await self._submit(actor, request, _authorize_write=_authorize_write)async def _submit(self, actor, request, *, _authorize_write=None):self._require_admission_open()@@ -452,6 +466,8 @@ class SessionAuthority:media = payload.get('attachments_v1', {}).get('media', [])if not media:return+ from gateway.session_ingress_media import drop_capture_lease+ drop_capture_lease() # its own lease must not keep the refused bytes from collectionfrom hermes_state_media import collect_retired_media, retire_mediatry:self.db._execute_write(lambda conn: retire_media(conn, {'attachments_v1': {'media': media}}))diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 46e787e93c4..2828e3d1f50 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -5,6 +5,9 @@ and upload limits. Its flat age-based cleanup skips this retained subdirectory:native bytes are released by ``release_admission_media`` once their row isterminal and no live native input or retained API image context still holds them."""+from collections import Counter+from contextlib import contextmanager+from contextvars import ContextVarimport hashlibimport jsonimport os@@ -12,6 +15,7 @@ from pathlib import Pathimport reimport statimport tempfile+import threadingfrom hermes_state_runtime import RuntimeStoreErrorfrom utils import fsync_directory@@ -21,6 +25,41 @@ _API_IMAGE_NAME = re.compile(r'api_[0-9a-f]{32}\.(png|jpg|gif|webp)')_SHA256_NAME = re.compile(r'[0-9a-f]{64}')+# Retained paths a capture published or reused whose admission has not committed or been refused+# yet: no committed row holds them, so ``release_unheld_media`` must treat them as held. The lock+# orders a capture's lease-then-publish against a release's lease-check-then-unlink, per path.+_leases = Counter()+_lease_lock = threading.Lock()+_lease_scope = ContextVar('native_media_lease_scope', default=None)+++@contextmanager+def capture_lease():+ """Hold every path captured inside this block (capture through admission commit or refusal)+ against a concurrent release: an older turn's settlement or cancellation that names the same+ content-addressed bytes would otherwise unlink them before the new admission holds them."""+ token = _lease_scope.set([])+ try:+ yield+ finally:+ drop_capture_lease()+ _lease_scope.reset(token)+++def drop_capture_lease(paths=None):+ """End this scope's lease on *paths* (default: all) early, e.g. before a refused admission+ releases its own fresh capture, which its lease would otherwise keep from collection."""+ held = _lease_scope.get()+ if not held:+ return+ with _lease_lock:+ for path in [path for path in held if paths is None or path in paths]:+ held.remove(path)+ _leases[path] -= 1+ if _leases[path] <= 0:+ del _leases[path]++def _media_root():from gateway.platforms.base import get_document_cache_dirreturn get_document_cache_dir().resolve() / 'native-inputs'@@ -113,7 +152,9 @@ def reconcile_native_retry(db, *, principal_id, session_id, request_id, payload)# A live row still executes these bytes, so they must verify (a terminal one is digest evidence).restore_native_media(committed)kept = {reference['path'] for reference in committed}- release_unheld_media(db, [reference for reference in fresh if reference['path'] not in kept], retain_history=False)+ unowned = [reference for reference in fresh if reference['path'] not in kept]+ drop_capture_lease({reference['path'] for reference in unowned})+ release_unheld_media(db, unowned, retain_history=False)return {**payload, 'native_text_v1': {**payload['native_text_v1'], 'media': committed}}@@ -174,10 +215,15 @@ def capture_native_media(paths):if target.parent.resolve() != target.parent:raise RuntimeStoreError('invalid_params')target.parent.mkdir(mode=0o700, exist_ok=True)- if target.exists() or target.is_symlink():- restore_native_media([reference])- else:- os.replace(temporary, target)+ with _lease_lock:+ scope = _lease_scope.get()+ if scope is not None:+ scope.append(str(target))+ _leases[str(target)] += 1+ if target.exists() or target.is_symlink():+ restore_native_media([reference])+ else:+ os.replace(temporary, target)for directory in (target.parent, root, root.parent, root.parent.parent, root.parent.parent.parent):fsync_directory(directory)finally:@@ -411,9 +457,11 @@ def release_unheld_media(db, references, *, retain_history=True):if reference['path'] in held:continuetry:- if path.parent.resolve() != path.parent or _file_identity(path) in identities:- continue- path.unlink()+ with _lease_lock:+ if (reference['path'] in _leases or path.parent.resolve() != path.parent+ or _file_identity(path) in identities):+ continue+ path.unlink()released += 1path.parent.rmdir()except (OSError, ValueError):diff --git a/tests/gateway/test_native_media_capture_lease.py b/tests/gateway/test_native_media_capture_lease.pynew file mode 100644index 00000000000..836ca218d9d--- /dev/null+++ b/tests/gateway/test_native_media_capture_lease.py@@ -0,0 +1,94 @@+"""Retained media a capture published or reused is held from capture until its admission commits+or is refused (andrexibiza-7, JoaoMarcos44-R2), and a refused admission leaves no capture behind+(andrexibiza-17). One row per content-addressed capture site whose admission the authority owns."""+import asyncio+from pathlib import Path+import threading++import pytest++PNG = bytes.fromhex(+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"+ "890000000a49444154789c6300010000000500010d0a2db40000000049454e44ae426082")+++async def _authority(tmp_path, monkeypatch):+ from gateway.session_authority import SessionAuthority+ from tests.gateway.test_prompt_attachments import _authority as store_authority++ async def answer(event):+ return 'ok'+ authority = await store_authority(tmp_path, monkeypatch, answer)+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)+ return authority+++def _submit(authority, request_id, staged, text='look'):+ from gateway.session_contract import Principal, SessionRef, Submission+ actor = Principal('human', 'p', frozenset({'session:submit'}), 't')+ return authority.submit(actor, Submission(request_id, SessionRef('p', 's'), {'text': text, 'attachments': [+ {'path': staged, 'mime': 'image/png'}]}, 'queue'))++[email protected]('cleanup', ['settled', 'cancelled'])+async def test_same_bytes_captured_for_a_new_turn_survive_an_older_turns_cleanup(tmp_path, monkeypatch, cleanup):+ """The same staged image is sent again (a queued prompt edited: cancel + resubmit, or a re-send+ while the previous turn settles): admit_attachments reuses the content-addressed path the older+ row holds, and that row's cleanup runs while the new admission write is still in flight."""+ from gateway import session_authority+ from gateway.session_ingress_media import release_admission_media, restore_attachments+ from hermes_state_runtime import (cancel_session_input, claim_session_input, get_session_admission,+ settle_session_input)+ from gateway.platforms.base import cache_image_from_bytes+ authority = await _authority(tmp_path, monkeypatch)+ staged = cache_image_from_bytes(PNG, '.png')+ old = await _submit(authority, 'old', staged)+ if cleanup == 'settled':+ claim = claim_session_input(authority.db, epoch=authority.epoch, session_id='s')+ settle_session_input(authority.db, epoch=authority.epoch, admission_id=old.admission_id,+ generation=claim['generation'], outcome='completed')+ else:+ cancel_session_input(authority.db, epoch=authority.epoch, admission_id=old.admission_id)+ entered, release = threading.Event(), threading.Event()+ real = session_authority.admit_session_input++ def parked(*args, **kwargs):+ entered.set()+ release.wait(10)+ return real(*args, **kwargs)+ monkeypatch.setattr(session_authority, 'admit_session_input', parked)+ new = asyncio.create_task(_submit(authority, 'new', staged))+ assert await asyncio.to_thread(entered.wait, 10)+ await asyncio.to_thread(release_admission_media, authority.db, old.admission_id)+ release.set()+ receipt = await asyncio.wait_for(new, 10)+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ assert receipt.status == 'queued'+ restore_attachments(row['payload']) # raises storage_unavailable when the bytes were unlinked+++async def test_refused_native_admission_leaves_no_fresh_capture(tmp_path, monkeypatch):+ """admit_native captured the message's media, then the write refused it (admission_conflict+ on a changed redelivery): the fresh capture no admission owns must not stay retained."""+ from gateway import session_authority+ from gateway.session_ingress_media import _media_root, capture_native_media+ from hermes_state_runtime import RuntimeStoreError+ authority = await _authority(tmp_path, monkeypatch)+ from gateway.platforms.base import cache_image_from_bytes++ async def prepare(runner, event):+ return {'text': 'x', 'native_text_v1': {'source': {}, 'event': {'message_id': 'm'},+ 'media': capture_native_media([cache_image_from_bytes(PNG + b'fresh', '.png')])}}+ monkeypatch.setattr('gateway.session_envelope.prepare_native', prepare)+ monkeypatch.setattr('gateway.session_envelope.restore_native',+ lambda payload: type('E', (), {'source': authority.sessions['s'].source})())++ def refused(*args, **kwargs):+ raise RuntimeStoreError('admission_conflict')+ monkeypatch.setattr(session_authority, 'admit_session_input', refused)+ with pytest.raises(RuntimeStoreError, match='admission_conflict'):+ await authority.admit_native(object())+ assert not [p for p in _media_root().rglob('*') if p.is_file()], 'a refused capture stayed retained'+ assert Path(_media_root()).is_dir()