"""Fault injection at real S3/DB boundaries and safe compensation.""" import uuid from unittest.mock import patch import pytest from sqlalchemy.exc import OperationalError from sqlalchemy.ext.asyncio import AsyncSession from starlette.requests import ClientDisconnect, Request from app.cleanup import cleanup_once from app.storage import StorageUnavailable from conftest import assert_error, run_sql from test_attachments import upload, uploaded def rows(chat): return run_sql("SELECT id,object_key,status FROM attachments WHERE chat_id=$1", uuid.UUID(chat["id"])) def clean(client, dry=False): return client.portal.call(cleanup_once, client.app.state.sessionmaker, client.app.state.storage, 3600, dry) def age(ident): run_sql("UPDATE attachments SET created_at=clock_timestamp()-interval '2 hours' WHERE id=$1", ident) @pytest.mark.parametrize("after_put", [False, True]) def test_s3_failure_leaves_accounted_intent_and_cleanup_retries(client, alice, chat, after_put): storage = client.app.state.storage original = storage.put def fail(key, stream, size, mime): if after_put: original(key, stream, size, mime) raise StorageUnavailable() with patch.object(storage, "put", side_effect=fail): assert_error(upload(client, alice, chat), 503, "unavailable") pending = rows(chat) assert len(pending) == 1 and pending[0]["status"] == "uploading" row = pending[0] assert clean(client)["deleted"] == 0 # Fresh intent protected even after a failure. age(row["id"]) assert clean(client, dry=True)["candidates"] >= 1 assert rows(chat) with patch.object(storage, "delete", side_effect=StorageUnavailable()): assert clean(client)["failed"] >= 1 assert rows(chat) assert clean(client)["deleted"] >= 1 assert not rows(chat) with pytest.raises(StorageUnavailable): storage.stat(row["object_key"]) assert clean(client)["deleted"] == 0 def test_database_failure_after_put_is_compensated(client, alice, chat): original = AsyncSession.commit count = 0 async def fail_final(session): nonlocal count count += 1 if count == 2: raise OperationalError("", {}, Exception("injected before final commit")) return await original(session) with patch.object(AsyncSession, "commit", fail_final): assert_error(upload(client, alice, chat), 503, "unavailable") row = rows(chat)[0] assert row["status"] == "uploading" assert client.app.state.storage.stat(row["object_key"]).size > 0 age(row["id"]) assert clean(client)["deleted"] >= 1 assert not rows(chat) def test_ambiguous_successful_commit_never_deletes_ready_file(client, alice, bob, chat): original = AsyncSession.commit count = 0 async def lost_ack(session): nonlocal count count += 1 await original(session) if count == 2: raise OperationalError("", {}, Exception("lost final commit acknowledgement")) with patch.object(AsyncSession, "commit", lost_ack): assert_error(upload(client, alice, chat), 503, "unavailable") row = rows(chat)[0] assert row["status"] == "ready" age(row["id"]) clean(client) assert rows(chat)[0]["status"] == "ready" assert client.get("/api/v1/attachments/" + str(row["id"]) + "/content", headers=bob.headers).status_code == 200 def test_cleanup_never_removes_old_ready_attachment(client, alice, bob, chat): attachment = uploaded(client, alice, chat) age(uuid.UUID(attachment["id"])) clean(client) assert client.get("/api/v1/attachments/" + attachment["id"] + "/content", headers=bob.headers).status_code == 200 def test_interrupted_body_creates_neither_metadata_nor_object(client, alice, chat): original = Request.stream async def interrupted(request): if request.url.path.endswith("/attachments"): yield b"\x89PNG\r\n\x1a\n" raise ClientDisconnect() async for chunk in original(request): yield chunk with patch.object(Request, "stream", interrupted), patch.object(client.app.state.storage, "put") as put: assert_error(upload(client, alice, chat), 400, "invalid_request") put.assert_not_called() assert not rows(chat)