Skip to content

The agent that grows with you

fix(gateway): hosted non-image documents are held and released like every retained input

Tekniume217e102ab21
diff --git a/gateway/session_hosted_attachments.py b/gateway/session_hosted_attachments.py
index df960f6945c..457b4182824 100644
--- a/gateway/session_hosted_attachments.py
+++ b/gateway/session_hosted_attachments.py
@@ -6,6 +6,7 @@ from pathlib import Path
import tempfile
from gateway.hosted_room_attachments import HostedRoomAttachmentStore, MAX_ATTACHMENT_BYTES
+from gateway.session_ingress_media import HOSTED_DOCUMENT_LINE
from hermes_state_runtime import RuntimeStoreError
@@ -93,8 +94,9 @@ def submission_payload(rpc, prompt, attachments=None):
data = transferred[index][1]
if len(data) != item['size']:
raise RuntimeStoreError('permission_denied')
- # Retained native-inputs are excluded from age-only document cleanup. The
- # content-addressed destination is stable on retry and refuses corruption.
+ # Retained native-inputs are excluded from age-only document cleanup; a live hosted row
+ # holds its documents through the prompt path lines (``hosted_document_references``).
+ # The content-addressed destination is stable on retry and refuses corruption.
with tempfile.TemporaryDirectory(prefix='hermes-room-input-') as directory:
path = Path(directory) / item['name']
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
@@ -131,7 +133,7 @@ def submission_payload(rpc, prompt, attachments=None):
finally:
Path(temporary).unlink(missing_ok=True)
images.append({'path': str(target), 'mime': item['mime']})
- text = prompt + ''.join('\n[Shared attachment] file: ' + path + '\n' for path in documents)
+ text = prompt + ''.join(HOSTED_DOCUMENT_LINE + path + '\n' for path in documents)
return {'text': text, **({'attachments': images} if images else {})}
@@ -183,7 +185,7 @@ def attested_submission_payload(prompt, attachments, digests):
media_types.append(item['mime'])
else:
documents.append(reference['path'])
- text = prompt + ''.join('\n[Shared attachment] file: ' + path + '\n' for path in documents)
+ text = prompt + ''.join(HOSTED_DOCUMENT_LINE + path + '\n' for path in documents)
return {'text': text, **({'attachments_v1': {'media': media, 'media_types': media_types}} if media else {})}
diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.py
index 791373d6a34..e6b3ca5ff07 100644
--- a/gateway/session_ingress_media.py
+++ b/gateway/session_ingress_media.py
@@ -17,6 +17,10 @@ from hermes_state_runtime import RuntimeStoreError
from utils import fsync_directory
+_API_IMAGE_NAME = re.compile(r'api_[0-9a-f]{32}\.(png|jpg|gif|webp)')
+_SHA256_NAME = re.compile(r'[0-9a-f]{64}')
+
+
def _media_root():
from gateway.platforms.base import get_document_cache_dir
return get_document_cache_dir().resolve() / 'native-inputs'
@@ -202,6 +206,31 @@ def validate_media_batch_size(sizes):
raise RuntimeStoreError('invalid_params') from exc
+# A hosted room's non-image document is retained under ``native-inputs/<sha256>/<name>`` like any
+# other input, but rides in the committed prompt as a path line (``session_hosted_attachments``),
+# not as a structured reference. Same literal the hosted payload builders append.
+HOSTED_DOCUMENT_LINE = '\n[Shared attachment] file: '
+_HOSTED_DOCUMENT_RE = re.compile(re.escape(HOSTED_DOCUMENT_LINE) + r'([^\n]+)\n')
+
+
+def hosted_document_references(request_id, payload):
+ """Retained document references a hosted admission's prompt names (``[]`` for other rows).
+
+ Only content-addressed names under this profile's retained root count, and never an API
+ image name: those are held by ``api_turn_v1`` in every status, so a member's prompt text
+ can name one without gaining deletion authority over it."""
+ if not str(request_id).startswith('hosted:') or not isinstance(payload.get('text'), str):
+ return []
+ root = _media_root()
+ references = []
+ for value in _HOSTED_DOCUMENT_RE.findall(payload['text']):
+ path = Path(value)
+ if (path.is_absolute() and path.parent.parent == root and _SHA256_NAME.fullmatch(path.parent.name)
+ and not _API_IMAGE_NAME.fullmatch(path.name)):
+ references.append({'path': value, 'sha256': path.parent.name})
+ return references
+
+
def admission_media_references(payload):
"""Native references eligible as deletion candidates after terminal settlement."""
return list(payload.get('attachments_v1', {}).get('media', ())) + list(
@@ -209,19 +238,23 @@ def admission_media_references(payload):
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')
+ # Project only references, not potentially large inline-image/history payloads; a live hosted
+ # row's prompt is projected too, because its documents are held by text, not by a reference.
+ rows = conn.execute("""SELECT status, request_id, json_extract(payload_json,
+ '$.attachments_v1.media', '$.native_text_v1.media', '$.api_turn_v1.media'),
+ CASE WHEN status!='terminal' AND request_id LIKE 'hosted:%'
+ THEN json_extract(payload_json, '$.text') END
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:
+ for status, request_id, encoded, text 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 ())
+ references.extend(hosted_document_references(request_id, {'text': text}))
held.update(reference['path'] for reference in references)
return held
@@ -261,10 +294,11 @@ def release_admission_media(db, admission_id):
row = get_session_admission(db, admission_id=admission_id)
if row is None or row['status'] != 'terminal':
return 0
- return release_unheld_media(db, admission_media_references(row['payload']), retain_history=False)
-
-
-_API_IMAGE_NAME = re.compile(r'api_[0-9a-f]{32}\.(png|jpg|gif|webp)')
+ released = release_unheld_media(db, admission_media_references(row['payload']), retain_history=False)
+ # A hosted document is named in the prompt the transcript keeps, so it is history context like
+ # an API image: it goes once no live row and no transcript row names it (session deletion then
+ # collects it through ``retire_media``), never while a follow-up turn can still be told to read it.
+ return released + release_unheld_media(db, hosted_document_references(row['request_id'], row['payload']))
def collect_unheld_api_images(db):
diff --git a/hermes_state_media.py b/hermes_state_media.py
index a22a9ca0583..a816471b8f7 100644
--- a/hermes_state_media.py
+++ b/hermes_state_media.py
@@ -5,9 +5,9 @@ import json
PREFIX = 'gateway.media.retired.v1.'
-def retire_media(conn, payload):
- references = [*payload.get('attachments_v1', {}).get('media', []),
- *payload.get('native_text_v1', {}).get('media', []),
+def retire_media(conn, payload, request_id=''):
+ from gateway.session_ingress_media import admission_media_references, hosted_document_references
+ references = [*admission_media_references(payload), *hosted_document_references(request_id, payload),
*payload.get('api_turn_v1', {}).get('media', [])]
for reference in references:
key = PREFIX + hashlib.sha256(reference['path'].encode()).hexdigest()
diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.py
index 113e549a7e9..a3d6a96e78a 100644
--- a/hermes_state_mutation_retirement.py
+++ b/hermes_state_mutation_retirement.py
@@ -48,7 +48,7 @@ def retire_terminal_receipts(conn, session_ids):
for raw in admissions:
row = dict(raw)
from hermes_state_media import retire_media
- retire_media(conn, json.loads(row['payload_json']))
+ retire_media(conn, json.loads(row['payload_json']), row['request_id'])
# Keep the digest for exact retries, not another copy of user input/history.
row['payload_json'] = '{}'
row['lineage_json'] = '[]'
diff --git a/tests/gateway/test_hosted_document_custody.py b/tests/gateway/test_hosted_document_custody.py
new file mode 100644
index 00000000000..01d4dda7a29
--- /dev/null
+++ b/tests/gateway/test_hosted_document_custody.py
@@ -0,0 +1,41 @@
+"""Hosted non-image documents are retained inputs like any other: the native GC's holder scan
+keeps the bytes a live hosted row still needs, and the row's own terminal release collects them."""
+import json
+
+from gateway.session_ingress_media import 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
+
+
+def _document(tmp_path, name, data):
+ source = tmp_path / 'src' / name
+ source.parent.mkdir(parents=True, exist_ok=True)
+ source.write_bytes(data)
+ return capture_native_media([source])[0]
+
+
+def test_queued_hosted_document_survives_native_cancel_and_is_released_at_its_own_terminal(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ from gateway.session_hosted_attachments import attested_submission_payload
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ db.create_session('s', source='test')
+ epoch = begin_runtime_epoch(db, instance_id='current')
+ data = b'%PDF-1.4 quarterly report\n'
+ native_ref = _document(tmp_path, 'report.pdf', data)
+ native = admit_session_input(db, epoch=epoch, principal_id='bot', session_id='s', request_id='native-1',
+ payload={'text': 'see file', 'native_text_v1': {'media': [native_ref]}})
+ # The hosted row commits exactly what the hosted transport commits for the same bytes and name.
+ manifest = [{'attachment_id': 'att_' + 'a' * 32, 'event_id': 'evt_1', 'kind': 'file', 'name': 'report.pdf',
+ 'mime': 'application/pdf', 'size': len(data)}]
+ payload = attested_submission_payload('summarize', manifest, [native_ref['sha256']])
+ assert native_ref['path'] in payload['text'] and 'attachments_v1' not in payload
+ hosted = admit_session_input(db, epoch=epoch, principal_id='owner', session_id='s',
+ request_id='hosted:' + json.dumps([{'room_id': 'r'}, 1]), payload=payload)
+ cancel_session_input(db, epoch=epoch, admission_id=native['admission_id'])
+ release_admission_media(db, native['admission_id'])
+ from pathlib import Path
+ retained = Path(native_ref['path'])
+ assert retained.read_bytes() == data, 'a queued hosted row still needs this document'
+ cancel_session_input(db, epoch=epoch, admission_id=hosted['admission_id'])
+ release_admission_media(db, hosted['admission_id'])
+ assert not retained.exists(), 'the hosted row was the last holder; its terminal release collects the bytes'