The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: reject expired room commitments and verify retention restart
Teknium50c6e32b7d90
diff --git a/gateway/hosted_room_attachments.py b/gateway/hosted_room_attachments.pyindex 0be79d38828..91346b584e1 100644--- a/gateway/hosted_room_attachments.py+++ b/gateway/hosted_room_attachments.py@@ -732,6 +732,8 @@ class HostedRoomAttachmentStore:raise AttachmentConflictError("attachment manifest metadata does not match the uploaded bytes")+ if row["expires_at"] is not None and float(row["expires_at"]) <= now:+ raise AttachmentNotFoundError("attachment has expired")state = str(row["state"])if state == "disbanded":raise AttachmentNotFoundError("attachment belongs to a disbanded room")@@ -1196,27 +1198,6 @@ class HostedRoomAttachmentStore:return row- def list_published(- self,- *,- room_id: Any,- authority_gateway_id: Any,- authority_epoch: Any,- cursor: Any = None,- limit: Any = None,- query: Any = None,- producer_member_id: Any = None,- recipient_member_id: Any = None,- ) -> dict[str, Any]:- """Read the bounded catalog without duplicating the byte store."""- from gateway.hosted_room_attachment_catalog import list_published-- return list_published(- self, room_id=room_id, authority_gateway_id=authority_gateway_id,- authority_epoch=authority_epoch, cursor=cursor, limit=limit,- query=query, producer_member_id=producer_member_id,- recipient_member_id=recipient_member_id,- )__all__ = [diff --git a/tests/gateway/test_hosted_room_attachment_publication.py b/tests/gateway/test_hosted_room_attachment_publication.pynew file mode 100644index 00000000000..f9bea5fe628--- /dev/null+++ b/tests/gateway/test_hosted_room_attachment_publication.py@@ -0,0 +1,237 @@+"""Canonical message insertion and attachment rollback share one write fence."""++import sqlite3+from contextlib import contextmanager++import pytest++from gateway import hosted_rooms+from gateway.hosted_room_attachments import (+ AttachmentNotFoundError,+ HostedRoomAttachmentStore,+ UNCOMMITTED_TTL_SECONDS,+)+++def _staged(tmp_path, *, kind="message.member", viewer=True):+ db = tmp_path / "state.db"+ hosted_rooms.create_room(+ db, room_id="files", name="Files", members=[], authority_gateway_id="home"+ )+ store = HostedRoomAttachmentStore(db, clock=lambda: 1000.0)+ uploaded = store.put(+ room_id="files",+ upload_id="upload",+ kind="file",+ name="result.txt",+ mime="text/plain",+ data=b"exact output",+ )+ manifest = [+ {+ key: uploaded[key]+ for key in ("attachment_id", "kind", "name", "size", "mime")+ }+ ]+ store.commit_message(+ room_id="files",+ event_id="message",+ manifest=manifest,+ recipient_member_ids=["member"],+ viewer_access=viewer,+ hold_until_event=True,+ )+ args = dict(+ room_id="files",+ event_id="message",+ kind=kind,+ actor={"kind": "user", "id": "owner"}+ if kind == "message.user"+ else {"kind": "member", "id": "member"},+ payload={"text": "result", "attachments": manifest},+ authority_gateway_id="home",+ authority_epoch=1,+ now=1001.0,+ expected_latest_seq=0,+ )+ return db, store, manifest, args+++def _abort(store, manifest):+ return store.abort_message_commit(+ room_id="files",+ event_id="message",+ attachment_ids=[item["attachment_id"] for item in manifest],+ )+++def _read(store, manifest):+ return store.read(+ room_id="files",+ event_id="message",+ recipient_member_id="member",+ attachment_id=manifest[0]["attachment_id"],+ ).data++[email protected]("kind", ["message.user", "message.member"])[email protected]("publish_first", [False, True])+def test_rollback_and_canonical_append_have_one_winner(tmp_path, kind, publish_first):+ db, store, manifest, args = _staged(tmp_path, kind=kind)+ if publish_first:+ committed = hosted_rooms.append_event(db, **args)+ assert not _abort(store, manifest)+ assert _read(store, manifest) == b"exact output"+ assert hosted_rooms.append_event(db, **args)["idempotent"]+ assert (+ hosted_rooms.read_events(db, room_id="files")["events"][0]["seq"]+ == committed["seq"]+ )+ else:+ assert _abort(store, manifest)+ with pytest.raises(hosted_rooms.EventCursorConflictError):+ hosted_rooms.append_event(db, **args)+ assert hosted_rooms.room_state(db, room_id="files")["latest_seq"] == 0+ with pytest.raises(AttachmentNotFoundError):+ _read(store, manifest)+ store.commit_message(+ room_id="files",+ event_id="message",+ manifest=manifest,+ recipient_member_ids=["member"],+ viewer_access=True,+ hold_until_event=True,+ )+ hosted_rooms.append_event(db, **args)+ assert _read(store, manifest) == b"exact output"+++def test_append_validates_after_entering_its_sql_write_transaction(+ tmp_path, monkeypatch+):+ db, store, manifest, args = _staged(tmp_path)+ transaction = hosted_rooms._transaction++ @contextmanager+ def rollback_before_begin(*values, **kwargs):+ _abort(store, manifest)+ with transaction(*values, **kwargs) as conn:+ yield conn++ monkeypatch.setattr(hosted_rooms, "_transaction", rollback_before_begin)+ with pytest.raises(hosted_rooms.EventCursorConflictError):+ hosted_rooms.append_event(db, **args)+ assert hosted_rooms.read_events(db, room_id="files")["events"] == []++[email protected]("invalid", ["room", "event", "metadata", "private", "expired"])+def test_append_requires_exact_live_room_visible_commitment(tmp_path, invalid):+ db, store, manifest, args = _staged(tmp_path, viewer=invalid != "private")+ if invalid == "room":+ hosted_rooms.create_room(+ db, room_id="other", name="Other", members=[], authority_gateway_id="home"+ )+ args["room_id"] = "other"+ elif invalid == "event":+ args["event_id"] = "other"+ elif invalid == "metadata":+ args["payload"]["attachments"][0]["name"] = "different.txt"+ elif invalid == "expired":+ args["now"] = 1000.0 + UNCOMMITTED_TTL_SECONDS+ with pytest.raises(hosted_rooms.EventCursorConflictError):+ hosted_rooms.append_event(db, **args)+ assert hosted_rooms.room_state(db, room_id=args["room_id"])["latest_seq"] == 0+ with sqlite3.connect(db) as conn:+ assert (+ conn.execute("SELECT expires_at FROM hosted_room_attachments").fetchone()[0]+ is not None+ )+++def test_canonical_append_retains_files_before_caller_can_crash_or_prune(tmp_path):+ db, store, manifest, args = _staged(tmp_path)+ hosted_rooms.append_event(db, **args)+ # No service retain_event/ACK call has run after append.+ assert store.prune(now=1001.0 + UNCOMMITTED_TTL_SECONDS) == 0+ assert _read(store, manifest) == b"exact output"+++def test_failed_event_insert_rolls_back_attachment_retention(tmp_path, monkeypatch):+ db, store, manifest, args = _staged(tmp_path)++ def fail(*values, **kwargs):+ assert values[0].in_transaction+ assert (+ values[0]+ .execute("SELECT expires_at FROM hosted_room_attachments")+ .fetchone()[0]+ is None+ )+ raise RuntimeError("event capacity failed")++ monkeypatch.setattr(hosted_rooms, "_prepare_event", fail)+ with pytest.raises(RuntimeError, match="event capacity failed"):+ hosted_rooms.append_event(db, **args)+ assert _abort(store, manifest) == 1+ with sqlite3.connect(db) as conn:+ assert (+ conn.execute("SELECT COUNT(*) FROM hosted_room_events").fetchone()[0] == 0+ )+ assert (+ conn.execute("SELECT expires_at FROM hosted_room_attachments").fetchone()[0]+ is not None+ )+++def test_receipt_rollback_releases_only_files_absent_from_durable_manifest(tmp_path):+ db, store, manifest, args = _staged(tmp_path)+ hosted_rooms.append_event(db, **args)+ extra = store.put(+ room_id="files",+ upload_id="extra",+ kind="file",+ name="extra.txt",+ mime="text/plain",+ data=b"not published",+ )+ extended = manifest + [{key: extra[key] for key in manifest[0]}]+ store.commit_message(+ room_id="files",+ event_id="message",+ manifest=extended,+ recipient_member_ids=["member"],+ viewer_access=True,+ hold_until_event=True,+ )+ assert _abort(store, extended) == 1+ assert _read(store, manifest) == b"exact output"+ with pytest.raises(AttachmentNotFoundError):+ _read(store, extended[1:])++[email protected]("viewer", [False, True])+def test_room_visible_staging_denied_until_exact_owner_is_durable(tmp_path, viewer):+ db, store, manifest, args = _staged(tmp_path, kind="message.user")+ access = dict(+ room_id="files",+ attachment_id=manifest[0]["attachment_id"],+ event_id="message",+ recipient_member_id="member",+ viewer=viewer,+ )+ with pytest.raises(AttachmentNotFoundError):+ store.read(**access)+ hosted_rooms.append_event(db, **args)+ assert store.read(**access).data == b"exact output"+++def test_append_does_not_read_blob_bytes_inside_its_write_fence(tmp_path, monkeypatch):+ db, store, manifest, args = _staged(tmp_path)++ def unexpected_io(*values, **kwargs):+ raise AssertionError("canonical append must do metadata-only SQL work")++ with monkeypatch.context() as fence:+ fence.setattr(HostedRoomAttachmentStore, "_read_blob", unexpected_io)+ hosted_rooms.append_event(db, **args)+ assert _read(store, manifest) == b"exact output"diff --git a/tests/gateway/test_hosted_room_attachments.py b/tests/gateway/test_hosted_room_attachments.pynew file mode 100644index 00000000000..40c66d9a338--- /dev/null+++ b/tests/gateway/test_hosted_room_attachments.py@@ -0,0 +1,521 @@+import os+import sqlite3+import threading++import pytest++from gateway import hosted_rooms+from gateway.hosted_room_attachments import (+ AttachmentConflictError,+ AttachmentError,+ AttachmentIntegrityError,+ AttachmentNotFoundError,+ AttachmentQuotaError,+ HostedRoomAttachmentStore,+ MAX_TASK_ATTACHMENT_BYTES,+ MAX_TASK_ATTACHMENTS,+ UNCOMMITTED_TTL_SECONDS,+ decode_content_base64,+ validate_task_manifest,+)+++PNG = b"\x89PNG\r\n\x1a\n" + b"image-payload"+PDF = b"%PDF-1.7\nattachment\n%%EOF\n"+++def _put(store, *, upload_id="upload-1", data=PNG, **overrides):+ params = {+ "room_id": "room-1",+ "upload_id": upload_id,+ "kind": "image",+ "name": "diagram.png",+ "mime": "image/png",+ "data": data,+ }+ params.update(overrides)+ return store.put(**params)+++def _manifest(*attachments):+ return [+ {+ "attachment_id": item["attachment_id"],+ "kind": item["kind"],+ "name": item["name"],+ "size": item["size"],+ "mime": item["mime"],+ }+ for item in attachments+ ]+++def test_store_is_private_atomic_deduplicated_and_upload_idempotent(tmp_path):+ store = HostedRoomAttachmentStore(tmp_path / "state.db")++ first = _put(store)+ repeated = _put(store)+ second = _put(store, upload_id="upload-2")++ assert repeated["attachment_id"] == first["attachment_id"]+ assert repeated["idempotent"] is True+ assert second["attachment_id"] != first["attachment_id"]+ assert store.stats() == {+ "attachments": 2,+ "logical_bytes": len(PNG) * 2,+ "blobs": 1,+ "physical_bytes": len(PNG),+ }+ if os.name != "nt":+ assert store.root.stat().st_mode & 0o777 == 0o700+ assert store.blob_root.stat().st_mode & 0o777 == 0o700+ blob = next(path for path in store.blob_root.iterdir() if path.name.startswith("blob_"))+ assert blob.stat().st_mode & 0o777 == 0o600+ assert not list(store.blob_root.glob(".tmp-*"))+++def test_orphan_sweep_serializes_with_concurrent_canonical_blob_commit(+ tmp_path,+ monkeypatch,+):+ store = HostedRoomAttachmentStore(tmp_path / "state.db")+ entered_sweep = threading.Event()+ release_sweep = threading.Event()+ writer_done = threading.Event()+ errors: list[BaseException] = []+ original_iterdir = type(store.blob_root).iterdir++ def blocking_iterdir(path):+ if (+ path == store.blob_root+ and threading.current_thread().name == "stale-sweep"+ ):+ entered_sweep.set()+ assert release_sweep.wait(5)+ return original_iterdir(path)++ monkeypatch.setattr(type(store.blob_root), "iterdir", blocking_iterdir)+ sweep_thread = threading.Thread(+ target=store._sweep_orphans,+ name="stale-sweep",+ )+ sweep_thread.start()+ assert entered_sweep.wait(5)++ def write_blob():+ try:+ _put(store)+ except BaseException as exc: # pragma: no cover - asserted below+ errors.append(exc)+ finally:+ writer_done.set()++ writer_thread = threading.Thread(target=write_blob, name="blob-writer")+ writer_thread.start()+ assert not writer_done.wait(0.1)+ release_sweep.set()+ sweep_thread.join(5)+ writer_thread.join(5)++ assert not errors+ assert writer_done.is_set()+ assert _put(store)["idempotent"] is True+ assert len(list(store.blob_root.iterdir())) == 1+++def test_upload_id_conflict_and_manifest_metadata_conflict_fail_closed(tmp_path):+ store = HostedRoomAttachmentStore(tmp_path / "state.db")+ attachment = _put(store)++ with pytest.raises(AttachmentConflictError):+ _put(store, data=PNG + b"different")++ manifest = _manifest(attachment)+ manifest[0]["name"] = "renamed.png"+ with pytest.raises(AttachmentConflictError):+ store.commit_message(+ room_id="room-1",+ event_id="event-1",+ manifest=manifest,+ recipient_member_ids=("research", "builder"),+ )+++def test_failed_replay_rolls_back_only_attachments_transitioned_by_that_attempt(+ tmp_path,+):+ db = tmp_path / "state.db"+ store = HostedRoomAttachmentStore(db)+ committed = _put(store, upload_id="already-committed")+ new_upload = _put(store, upload_id="new-upload", data=PNG + b"new")+ store.commit_message(+ room_id="room-1",+ event_id="event-1",+ manifest=_manifest(committed),+ recipient_member_ids=("research",),+ hold_until_event=True,+ )++ _normalized, transitioned = store.commit_message_with_receipt(+ room_id="room-1",+ event_id="event-1",+ manifest=_manifest(committed, new_upload),+ recipient_member_ids=("research",),+ hold_until_event=True,+ )+ assert transitioned == (new_upload["attachment_id"],)++ assert store.abort_message_commit(+ room_id="room-1",+ event_id="event-1",+ attachment_ids=transitioned,+ ) == 1+ assert store.read(+ room_id="room-1",+ attachment_id=committed["attachment_id"],+ recipient_member_id="research",+ ).data == PNG+ conn = sqlite3.connect(db)+ states = dict(+ conn.execute(+ "SELECT upload_id, state FROM hosted_room_attachments ORDER BY upload_id"+ )+ )+ conn.close()+ assert states == {+ "already-committed": "committed",+ "new-upload": "uploaded",+ }+++def test_image_pdf_text_and_binary_round_trip_with_frozen_recipients(tmp_path):+ store = HostedRoomAttachmentStore(tmp_path / "state.db")+ image = _put(store)+ pdf = _put(+ store,+ upload_id="upload-pdf",+ data=PDF,+ kind="pdf",+ name="brief.pdf",+ mime="application/pdf",+ )+ text = _put(+ store,+ upload_id="upload-text",+ data=b"release notes\n",+ kind="file",+ name="notes.txt",+ mime="text/plain",+ )+ binary = _put(+ store,+ upload_id="upload-bin",+ data=b"\x00\x01\x02\xff",+ kind="file",+ name="payload.bin",+ mime="application/octet-stream",+ )+ manifest = _manifest(image, pdf, text, binary)++ committed = store.commit_message(+ room_id="room-1",+ event_id="event-1",+ manifest=manifest,+ recipient_member_ids=("research", "builder"),+ )+ repeated = store.commit_message(+ room_id="room-1",+ event_id="event-1",+ manifest=manifest,+ recipient_member_ids=("research", "builder"),+ )++ assert committed == repeated == manifest+ assert store.read(+ room_id="room-1",+ attachment_id=image["attachment_id"],+ recipient_member_id="research",+ event_id="event-1",+ ).data == PNG+ assert store.read(+ room_id="room-1",+ attachment_id=pdf["attachment_id"],+ recipient_member_id="builder",+ ).data == PDF+ with pytest.raises(AttachmentNotFoundError):+ store.read(+ room_id="room-1",+ attachment_id=image["attachment_id"],+ recipient_member_id="late-member",+ )+++ ("kind", "mime", "data"),+ [+ ("image", "image/png", b"not an image"),+ ("pdf", "application/pdf", b"not a pdf"),+ ("file", "text/plain", b"text\x00binary"),+ ("file", "image/png", PNG),+ ],+)+def test_mime_mismatches_are_rejected(tmp_path, kind, mime, data):+ store = HostedRoomAttachmentStore(tmp_path / "state.db")++ with pytest.raises(AttachmentError, match="MIME|mime|kind|bytes"):+ _put(store, data=data, kind=kind, mime=mime, name="claimed.dat")+++ ("name", "mime"),+ [+ (+ "brief.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ ),+ (+ "budget.xlsx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ ),+ (+ "deck.pptx",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ ),+ ("book.epub", "application/epub+zip"),+ ("library.jar", "application/java-archive"),+ ("mobile.apk", "application/vnd.android.package-archive"),+ ],+)+def test_generic_zip_container_formats_are_accepted_as_opaque_files(+ tmp_path, name, mime+):+ store = HostedRoomAttachmentStore(tmp_path / "state.db")+ container = b"PK\x03\x04" + b"opaque-container-payload"++ attachment = _put(+ store,+ data=container,+ kind="file",+ name=name,+ mime=mime,+ )++ assert attachment["name"] == name+ assert attachment["mime"] == mime+++def test_task_manifest_has_independent_count_and_byte_budgets():+ entry = {+ "attachment_id": "att_00000000000000000000000000000000",+ "kind": "file",+ "name": "part.bin",+ "size": 1,+ "mime": "application/octet-stream",+ }+ too_many = [+ {+ **entry,+ "attachment_id": f"att_{index:032x}",+ "name": f"part-{index}.bin",+ }+ for index in range(MAX_TASK_ATTACHMENTS + 1)+ ]+ with pytest.raises(AttachmentError, match="at most"):+ validate_task_manifest(too_many)++ too_large = [+ {+ **entry,+ "attachment_id": f"att_{index + 1:032x}",+ "name": f"chunk-{index}.bin",+ "size": 13_000_000,+ }+ for index in range(4)+ ]+ with pytest.raises(AttachmentError, match="aggregate byte limit"):+ validate_task_manifest(too_large)+++def test_uncommitted_expiry_and_disband_grace_release_deduplicated_blob(tmp_path):+ now = [100.0]+ store = HostedRoomAttachmentStore(tmp_path / "state.db", clock=lambda: now[0])+ first = _put(store)+ second = _put(store, upload_id="upload-2")+ store.commit_message(+ room_id="room-1",+ event_id="event-1",+ manifest=_manifest(first),+ recipient_member_ids=("research",),+ )++ now[0] += UNCOMMITTED_TTL_SECONDS + 1+ assert store.prune() == 1+ assert store.stats()["blobs"] == 1+ assert store.stats()["attachments"] == 1++ assert store.mark_room_disbanded("room-1") == 1+ now[0] += 15 * 60 + 1+ assert store.prune() == 1+ assert store.stats()["blobs"] == 0+ assert not any(store.blob_root.iterdir())+ with pytest.raises(AttachmentNotFoundError):+ store.read(+ room_id="room-1",+ attachment_id=second["attachment_id"],+ recipient_member_id="research",+ )+++def test_new_upload_reclaims_expired_uncommitted_quota_without_restart(tmp_path):+ now = [100.0]+ store = HostedRoomAttachmentStore(+ tmp_path / "state.db",+ clock=lambda: now[0],+ room_quota_bytes=len(PNG),+ )+ _put(store, upload_id="expired")+ now[0] += UNCOMMITTED_TTL_SECONDS + 1++ current = _put(store, upload_id="current")++ assert current["attachment_id"].startswith("att_")+ assert store.stats()["attachments"] == 1+++def test_integrity_check_rejects_tampering_and_symlink_replacement(tmp_path):+ store = HostedRoomAttachmentStore(tmp_path / "state.db")+ attachment = _put(store)+ store.commit_message(+ room_id="room-1",+ event_id="event-1",+ manifest=_manifest(attachment),+ recipient_member_ids=("research",),+ )+ blob = next(path for path in store.blob_root.iterdir() if path.name.startswith("blob_"))+ blob.write_bytes(PNG + b"tampered")+ with pytest.raises(AttachmentIntegrityError):+ store.read(+ room_id="room-1",+ attachment_id=attachment["attachment_id"],+ recipient_member_id="research",+ )++ blob.unlink()+ target = tmp_path / "outside"+ target.write_bytes(PNG)+ try:+ blob.symlink_to(target)+ except OSError:+ pytest.skip("symlink creation is unavailable")+ with pytest.raises(AttachmentIntegrityError):+ store.read(+ room_id="room-1",+ attachment_id=attachment["attachment_id"],+ recipient_member_id="research",+ )+++def test_room_and_gateway_quotas_are_bounded(tmp_path):+ room_limited = HostedRoomAttachmentStore(+ tmp_path / "room.db", room_quota_bytes=len(PNG)+ )+ _put(room_limited)+ with pytest.raises(AttachmentQuotaError, match="room"):+ _put(room_limited, upload_id="upload-2")++ gateway_limited = HostedRoomAttachmentStore(+ tmp_path / "gateway.db", gateway_quota_bytes=len(PNG)+ )+ _put(gateway_limited)+ with pytest.raises(AttachmentQuotaError, match="gateway"):+ _put(gateway_limited, upload_id="upload-2", data=PNG + b"other")+++def test_base64_decoder_is_bounded_and_rejects_data_urls():+ with pytest.raises(AttachmentError, match="data URL"):+ decode_content_base64("data:image/png;base64,AAAA")+ with pytest.raises(AttachmentError, match="valid base64"):+ decode_content_base64("not-base64")+++def test_metadata_database_never_contains_blob_bytes_or_paths(tmp_path):+ db = tmp_path / "state.db"+ store = HostedRoomAttachmentStore(db)+ attachment = _put(store)+ store.commit_message(+ room_id="room-1",+ event_id="event-1",+ manifest=_manifest(attachment),+ recipient_member_ids=("research",),+ )++ conn = sqlite3.connect(db)+ row = conn.execute(+ "SELECT * FROM hosted_room_attachments WHERE attachment_id=?",+ (attachment["attachment_id"],),+ ).fetchone()+ conn.close()+ encoded = repr(row)+ assert repr(PNG) not in encoded+ assert str(store.root) not in encoded+++def test_restart_reconciles_event_commit_and_expires_abandoned_commit(tmp_path):+ now = [100.0]+ db = tmp_path / "state.db"+ hosted_rooms.create_room(+ db,+ room_id="room-1",+ name="Release",+ members=[{"member_id": "research"}],+ authority_gateway_id="gateway-a",+ now=now[0],+ )+ store = HostedRoomAttachmentStore(db, clock=lambda: now[0])+ retained = _put(store, upload_id="retained")+ abandoned = _put(store, upload_id="abandoned", data=PNG + b"other")+ store.commit_message(+ room_id="room-1",+ event_id="event-retained",+ manifest=_manifest(retained),+ recipient_member_ids=("research",),+ viewer_access=True,+ hold_until_event=True,+ )+ store.commit_message(+ room_id="room-1",+ event_id="event-abandoned",+ manifest=_manifest(abandoned),+ recipient_member_ids=("research",),+ hold_until_event=True,+ )+ hosted_rooms.append_event(+ db,+ room_id="room-1",+ event_id="event-retained",+ kind="message.user",+ actor={"kind": "user", "id": "desktop"},+ authority_gateway_id="gateway-a",+ authority_epoch=1,+ payload={+ "text": "inspect",+ "thread_id": "thread-1",+ "attachments": _manifest(retained),+ },+ now=now[0],+ )++ now[0] += UNCOMMITTED_TTL_SECONDS + 1+ restarted = HostedRoomAttachmentStore(db, clock=lambda: now[0])++ assert restarted.read(+ room_id="room-1",+ attachment_id=retained["attachment_id"],+ recipient_member_id="research",+ ).data == PNG+ with pytest.raises(AttachmentNotFoundError):+ restarted.read(+ room_id="room-1",+ attachment_id=abandoned["attachment_id"],+ recipient_member_id="research",+ )diff --git a/tests/gateway/test_hosted_room_expired_commit.py b/tests/gateway/test_hosted_room_expired_commit.pynew file mode 100644index 00000000000..25b7294ab7d--- /dev/null+++ b/tests/gateway/test_hosted_room_expired_commit.py@@ -0,0 +1,13 @@+"""Expired staged bytes cannot be revived by a delayed share."""+import pytest+from gateway.hosted_room_attachments import HostedRoomAttachmentStore, AttachmentNotFoundError, UNCOMMITTED_TTL_SECONDS+++def test_expired_upload_cannot_be_committed_without_pruning(tmp_path):+ now = [100.0]+ store = HostedRoomAttachmentStore(tmp_path / 'state.db', clock=lambda: now[0])+ uploaded = store.put(room_id='room', upload_id='upload', kind='file', name='a.txt', mime='text/plain', data=b'bytes')+ manifest = [{key: uploaded[key] for key in ('attachment_id', 'kind', 'name', 'size', 'mime')}]+ now[0] += UNCOMMITTED_TTL_SECONDS+ with pytest.raises(AttachmentNotFoundError, match='expired'):+ store.commit_message(room_id='room', event_id='event', manifest=manifest, recipient_member_ids=['member'], viewer_access=True, hold_until_event=True)diff --git a/tests/gateway/test_hosted_room_retention_restart.py b/tests/gateway/test_hosted_room_retention_restart.pynew file mode 100644index 00000000000..fca0b635b1a--- /dev/null+++ b/tests/gateway/test_hosted_room_retention_restart.py@@ -0,0 +1,43 @@+"""Real process reopen and SQL failures preserve the accepted file boundary."""+import json+import os+import sqlite3+import subprocess+import sys+from contextlib import closing++import pytest+from gateway import hosted_rooms+from gateway.hosted_room_attachments import HostedRoomAttachmentStore, UNCOMMITTED_TTL_SECONDS+++def test_accepted_file_survives_fresh_process_after_staging_expiry(tmp_path):+ db = tmp_path / 'state.db'+ hosted_rooms.create_room(db, room_id='room', name='Room', members=[], authority_gateway_id='home')+ store = HostedRoomAttachmentStore(db, clock=lambda: 100.0)+ item = store.put(room_id='room', upload_id='upload', kind='file', name='proof.txt', mime='text/plain', data=b'accepted bytes')+ manifest = [{k: item[k] for k in ('attachment_id', 'kind', 'name', 'size', 'mime')}]+ store.commit_message(room_id='room', event_id='share', manifest=manifest, recipient_member_ids=['member'], viewer_access=True, hold_until_event=True)+ args = dict(room_id='room', event_id='share', kind='message.user', actor={'kind':'user', 'id':'owner'}, payload={'attachments':manifest}, authority_gateway_id='home', authority_epoch=1, now=101.0, expected_latest_seq=0)+ with closing(sqlite3.connect(db)) as conn:+ conn.execute("CREATE TRIGGER reject_share BEFORE INSERT ON hosted_room_events BEGIN SELECT RAISE(ABORT, 'disk rejected'); END")+ conn.commit()+ with pytest.raises(sqlite3.IntegrityError, match='disk rejected'):+ hosted_rooms.append_event(db, **args)+ with closing(sqlite3.connect(db)) as conn:+ assert conn.execute('SELECT expires_at FROM hosted_room_attachments').fetchone()[0] is not None+ assert conn.execute('SELECT count(*) FROM hosted_room_events').fetchone()[0] == 0+ conn.execute('DROP TRIGGER reject_share')+ conn.commit()+ with pytest.raises(hosted_rooms.EventCursorConflictError):+ hosted_rooms.append_event(db, **{**args, 'expected_latest_seq':1})+ hosted_rooms.append_event(db, **args)+ script = '''import json,sys+from gateway.hosted_room_attachments import HostedRoomAttachmentStore+from gateway import hosted_rooms+store=HostedRoomAttachmentStore(sys.argv[1],clock=lambda:float(sys.argv[3]))+data=store.read(room_id='room',attachment_id=sys.argv[2],recipient_member_id='member').data+print(json.dumps({'data':data.decode(),'events':len(hosted_rooms.read_events(sys.argv[1],room_id='room')['events']),'pruned':store.prune()}))+'''+ result = subprocess.run([sys.executable, '-c', script, str(db), item['attachment_id'], str(100 + UNCOMMITTED_TTL_SECONDS + 1)], env={**os.environ, 'HERMES_HOME':str(tmp_path)}, stdin=subprocess.DEVNULL, capture_output=True, text=True, check=True)+ assert json.loads(result.stdout) == {'data':'accepted bytes', 'events':1, 'pruned':0}