The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a lost-ACK image retry reconciles after the staging file is gone
Teknium9bf1febd8139
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex ff10cbffe07..8b4e6018793 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -305,8 +305,17 @@ class SessionAuthority:from gateway.session_finite import admit_finitefrom gateway.session_surface import admit_surfacefinite = admit_finite(request.payload)+ def admitted():+ # The exact durable identity (authenticated principal + target + request id); the+ # attachment fields it yields still pass the full payload-digest comparison below.+ with self.db._read_ctx() as conn:+ row = conn.execute('SELECT * FROM session_admissions WHERE principal_id=? AND '+ 'target_session_id=? AND request_id=?', (actor.subject,+ request.ref.session_id, request.request_id)).fetchone()+ from hermes_state_runtime import _row+ return _row(row) if row is not None else Nonepayload = {'text': request.payload['text'], **finite, **admit_surface(request.payload),- **admit_attachments(request.payload.get('attachments'))}+ **admit_attachments(request.payload.get('attachments'), admitted=admitted)}source = self.sessions[request.ref.session_id].sourceif source is not None and source.user_id != actor.subject:# Durable server authorization, not a client payload field. The originaldiff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 86c7fb8e52b..e66033aac96 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -42,8 +42,11 @@ def sniff_image_mime(data):return None-def admit_attachments(attachments):- """Wire ``attachments: [{path, mime}]`` -> committed payload fields (``{}`` when absent)."""+def admit_attachments(attachments, *, admitted=None):+ """Wire ``attachments: [{path, mime}]`` -> committed payload fields (``{}`` when absent).++ ``admitted()`` returns the durable admission already holding this request's identity (or+ ``None``): a lost-ACK retry whose disposable staging file is gone reconciles against it."""if attachments is None:return {}if (not isinstance(attachments, list) or not attachments or len(attachments) > _ATTACHMENT_LIMIT@@ -60,6 +63,17 @@ def admit_attachments(attachments):try:if any(path.lstat().st_nlink != 1 for path in paths):raise RuntimeStoreError('invalid_params')+ except FileNotFoundError as exc:+ row = admitted() if admitted is not None else None+ committed = row['payload'].get('attachments_v1') if row is not None else None+ if (row is None or committed is None or [Path(r['path']).name for r in committed['media']] != [p.name for p in paths]+ or committed['media_types'] != [item['mime'] for item in attachments]):+ raise RuntimeStoreError('invalid_params') from exc+ # A live row still executes these bytes, so they must verify; a terminal row is+ # exact-retry evidence by digest only. ``admit_session_input`` still checks the digest.+ if row['status'] != 'terminal':+ restore_native_media(committed['media'])+ return {'attachments_v1': committed}except OSError as exc:raise RuntimeStoreError('invalid_params') from excreturn {'attachments_v1': {'media': capture_native_media(paths),diff --git a/tests/gateway/test_prompt_attachments.py b/tests/gateway/test_prompt_attachments.pyindex 1a032c59dae..18199a35b86 100644--- a/tests/gateway/test_prompt_attachments.py+++ b/tests/gateway/test_prompt_attachments.py@@ -69,3 +69,33 @@ async def test_staged_attachment_reaches_message_event_media(tmp_path, monkeypatassert 'native-inputs' in path# Retained bytes are exact-retry evidence by digest only; settlement releases them.assert not os.path.exists(path)+++async def test_lost_ack_retry_reconciles_a_queued_image_after_staging_is_gone(tmp_path, monkeypatch):+ """Lost-ACK recovery of a still-queued image admission must not depend on the client's+ disposable staging file: the committed bytes and digest are the evidence. A changed payload+ under the same request id still conflicts, and a fresh request id still needs real staging."""+ from gateway.platforms.base import cache_image_from_bytes+ from gateway.session_contract import Principal, SessionRef, Submission+ from gateway.session_authority import SessionAuthority+ from hermes_state_runtime import RuntimeStoreError, list_session_admissions++ async def answer(event):+ return 'ok'+ authority = await _authority(tmp_path, monkeypatch, answer)+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)+ staged = cache_image_from_bytes(_ONE_PX_PNG, '.png')+ actor = Principal('human', 'p', frozenset({'session:submit'}), 't')+ def submit(request_id, text='look', path=staged):+ return authority.submit(actor, Submission(request_id, SessionRef('p', 's'),+ {'text': text, 'attachments': [{'path': path, 'mime': 'image/png'}]}, 'queue'))+ first = await submit('r-lost')+ assert (await submit('r-lost')).admission_id == first.admission_id+ os.unlink(staged)+ assert (await submit('r-lost')).admission_id == first.admission_id+ with pytest.raises(RuntimeStoreError, match='admission_conflict'):+ await submit('r-lost', text='changed')+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ await submit('r-fresh')+ assert [row['request_id'] for row in list_session_admissions(authority.db, session_id='s')] == ['r-lost']