forked from mtusi2026/mtusi2026lab4
Release the quarantine only after the object hashes to the row again
A pass without --deep released the quarantine of a missing or resized attachment as soon as an object of the same size appeared under its key, so other bytes of the same length went back to /content. The pass now streams and hashes the object of every quarantined row whose size matches again, deep or not, and releases it only when the SHA-256 matches; other bytes keep the row quarantined. Consistent data still costs no GET. The keyset reads page + 1 rows, so a pass takes exactly ceil(N/page) SQL pages instead of one more for the empty tail. The reconciler is assembled by dishka from PlatformProvider and the attachment storage provider that the API uses too, and it publishes the events of the intents it drops, so audit.attachment_discarded reason=reconcile reaches the journal. Any failure of a pass, not only Unavailable, ends as reconcile.failed with the error type and exit code 1. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b6c04f2296
commit
3de1dcdc84
@@ -5,7 +5,7 @@ from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
@@ -13,9 +13,11 @@ from httpx import AsyncClient
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import actor, keyed, running_app
|
||||
from fakes import MemoryObjectStorage, NullLogger
|
||||
from fakes import MemoryObjectStorage, NullLogger, RecordingPublisher
|
||||
from messenger.attachments.application.commands import ReconcileStorage
|
||||
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded
|
||||
from messenger.attachments.entrypoints import reconcile as entrypoint
|
||||
from messenger.attachments.entrypoints.reconcile import LOCK_KEY
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
@@ -61,6 +63,7 @@ class Stand:
|
||||
store: MemoryObjectStorage
|
||||
database: Database
|
||||
users: tuple[dict[str, Any], ...]
|
||||
published: RecordingPublisher
|
||||
|
||||
async def run(self, *, apply: bool = False, deep: bool = False) -> Reconciliation:
|
||||
reconciler = StorageReconciler(
|
||||
@@ -68,7 +71,8 @@ class Stand:
|
||||
self.store,
|
||||
PostgresSingleRun(self.database, LOCK_KEY),
|
||||
MonotonicUtcClock(),
|
||||
NullLogger(),
|
||||
logger=NullLogger(),
|
||||
publisher=self.published,
|
||||
)
|
||||
command = ReconcileStorage(
|
||||
apply=apply, grace=GRACE, skew=timedelta(0), deep=deep, page_size=2
|
||||
@@ -100,7 +104,7 @@ async def stand(dsn: str) -> AsyncIterator[Stand]:
|
||||
)
|
||||
await database.open()
|
||||
try:
|
||||
yield Stand(http, await storage(http), database, await trio(http))
|
||||
yield Stand(http, await storage(http), database, await trio(http), RecordingPublisher())
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
@@ -166,7 +170,7 @@ async def test_dry_run_reports_every_class_and_changes_nothing(dsn: str) -> None
|
||||
assert dict(shallow.found) == {k: v for k, v in EVERY_CLASS.items() if k != "sha_mismatch"}
|
||||
assert not deep.fixed
|
||||
assert not shallow.fixed
|
||||
assert shallow.requests == {"s3_list": 4, "sql": 4}
|
||||
assert shallow.requests == {"s3_list": 4, "sql": 3}
|
||||
assert deep.requests["s3_get"] == 2
|
||||
|
||||
|
||||
@@ -202,6 +206,11 @@ async def test_apply_fixes_what_it_found_and_repeats_as_noop(dsn: str) -> None:
|
||||
assert reasons[damaged["sized"]["id"]] == "size_mismatch"
|
||||
assert reasons[damaged["flipped"]["id"]] == "sha_mismatch"
|
||||
assert reasons[damaged["healthy"]["id"]] is None
|
||||
assert [
|
||||
(event.attachment_id, event.reason)
|
||||
for event in s.published.events
|
||||
if isinstance(event, AttachmentDiscarded)
|
||||
] == [(UUID(damaged["stale"]["id"]), "reconcile")]
|
||||
assert reasons[damaged["fresh"]["id"]] is None
|
||||
assert damaged["stale"]["id"] not in reasons
|
||||
assert key(damaged["stale"]) not in objects
|
||||
@@ -227,15 +236,69 @@ async def test_restored_object_leaves_quarantine(dsn: str) -> None:
|
||||
s.store.objects[key(lost)] = s.store.objects[key(flipped)] = (SAMPLE, "image/png")
|
||||
s.store.modified[key(lost)] = s.store.modified[key(flipped)]
|
||||
shallow = await s.run(apply=True)
|
||||
deep = await s.run(apply=True, deep=True)
|
||||
again = await s.run(apply=True)
|
||||
content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob))
|
||||
assert isolated.fixed["missing"] == isolated.fixed["sha_mismatch"] == 1
|
||||
assert shallow.fixed["healed"] == 1
|
||||
assert shallow.found["quarantined"] == 1
|
||||
assert deep.fixed["healed"] == 1
|
||||
assert shallow.fixed["healed"] == 2
|
||||
assert shallow.requests["s3_get"] == 2
|
||||
assert not again.fixed
|
||||
assert again.requests["s3_get"] == 0
|
||||
assert hashlib.sha256(content.content).hexdigest() == lost["sha256"]
|
||||
|
||||
|
||||
async def test_other_bytes_of_the_same_length_keep_the_quarantine(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
_, bob, _, _ = s.users
|
||||
lost = await s.upload()
|
||||
del s.store.objects[key(lost)]
|
||||
isolated = await s.run(apply=True)
|
||||
s.store.objects[key(lost)] = (bytes(len(SAMPLE)), "image/png")
|
||||
s.age(key(lost))
|
||||
shallow = await s.run(apply=True)
|
||||
content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob))
|
||||
reason = await s.sql("SELECT quarantine_reason FROM attachments WHERE id = $1", lost["id"])
|
||||
assert isolated.fixed["missing"] == 1
|
||||
assert not shallow.fixed
|
||||
assert shallow.found["quarantined"] == 1
|
||||
assert shallow.requests["s3_get"] == 1
|
||||
assert content.status_code == 404
|
||||
assert reason[0]["quarantine_reason"] == "missing"
|
||||
|
||||
|
||||
async def test_pages_of_rows_are_not_followed_by_an_empty_one(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
empty = await s.run()
|
||||
for _ in range(4):
|
||||
await s.upload()
|
||||
full = await s.run()
|
||||
assert (empty.rows, empty.requests["sql"]) == (0, 1)
|
||||
assert (full.rows, full.requests["sql"]) == (4, 2)
|
||||
|
||||
|
||||
def test_any_pass_failure_ends_as_reconcile_failed(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
async def broken(*_args: Any) -> Reconciliation:
|
||||
cancelled = asyncpg.exceptions.QueryCanceledError("statement timeout")
|
||||
raise ExceptionGroup("pass", [cancelled])
|
||||
|
||||
monkeypatch.setattr(entrypoint, "reconcile", broken)
|
||||
for name, value in {
|
||||
"DATABASE_URL": "postgresql://unused@127.0.0.1:1/unused",
|
||||
"S3_ACCESS_KEY_ID": "reconciler",
|
||||
"S3_SECRET_ACCESS_KEY": "reconciler-secret",
|
||||
}.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
entrypoint.main(["--apply"])
|
||||
captured = capsys.readouterr()
|
||||
assert stopped.value.code == 1
|
||||
assert captured.out == ""
|
||||
assert "reconcile.failed" in captured.err
|
||||
assert "QueryCanceledError" in captured.err
|
||||
assert "Traceback" not in captured.err
|
||||
|
||||
|
||||
async def test_row_written_after_listing_keeps_the_object(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
first, last = await s.upload(), await s.upload()
|
||||
|
||||
Reference in New Issue
Block a user