feat: reconcile the bucket against attachment rows in the cleaner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 19:32:08 +03:00
co-authored by Claude Opus 5.5
parent c13df14f36
commit c1648d9b83
53 changed files with 4207 additions and 205 deletions
+548 -2
View File
@@ -10,17 +10,21 @@ Valkey и S3, уборщик незавершённых загрузок (grace
`upload-memory`). На хранилища и API тесты действуют только через фикстуру
`stand` (hook `student-tests/fault_hook.py`) и всегда возвращают их в
рабочее состояние. Решение 4 design change `failure-checks`, решение 10
design change `upload-consistency`.
design change `upload-consistency`, решение 11 design change
`track2-reconciler` (сверка bucket и БД — в конце модуля: её тесты
оставляют помеченные потерянными вложения, прежние тесты таких не ждут).
"""
import hashlib
import json
import os
import statistics
import threading
import time
import uuid
from collections.abc import Callable, Iterator
from collections.abc import Callable, Collection, Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any
import httpx
@@ -1478,3 +1482,545 @@ def test_slow_body(
data,
"image/png",
)
# ---------------------------------------------------------------------------
# Сверка bucket и БД (change track2-reconciler, design, решение 11). Hook
# вносит расхождения с обеих сторон и запускает разовую сверку; плановая
# сверка уборщика стенда выключена. Записи сверки фильтруются по своим id и
# ключам: остатки прежних тестов (строки pending) могут попасть в отчёт, и
# код выхода сверяется с записями того же прохода, а не с числом. Объекты
# состарить нельзя (LastModified ставит S3): тесты объектов без строки ждут
# G + 1 с, строки состаривает hook (age-row)
# ---------------------------------------------------------------------------
# имя базы стенда: ключ объекта вложения — `<база>/attachments/<id>/original`
FAULT_DATABASE = os.environ.get("FAULT_DATABASE", "messenger")
# на сколько hook состаривает строку: заведомо больше grace
AGED_S = CLEANER_GRACE_S + 60
# объекты без строки старше grace: grace и секунда точности LastModified
OBJECT_AGE_WAIT_S = CLEANER_GRACE_S + 1
FOUND = "Found storage discrepancy"
FIXED = "Fixed storage discrepancy"
FINISHED = "Finished reconcile pass"
LIMIT_EXCEEDED = "Reconcile changes exceed limit"
# сверка под нагрузкой: потоки загрузок, период сверки, пауза потока
LOAD_THREADS = 4
LOAD_EXTRA_S = 15
LOAD_RECONCILE_PERIOD_S = 3
LOAD_PAUSE_S = 0.1
# плановая сверка отдельного уборщика: столько секунд он работает
SCHEDULED_RUN_S = 6
@dataclass(frozen=True)
class Reconcile:
"""Один разовый проход сверки: записи журнала процесса и код выхода."""
records: list[dict[str, Any]]
exit_code: int
def events(self, event: str) -> list[dict[str, Any]]:
return [item for item in self.records if item.get("event") == event]
@property
def finished(self) -> dict[str, Any]:
(record,) = self.events(FINISHED)
return record
def about(
self,
event: str,
*,
ids: Collection[str] = (),
keys: Collection[str] = (),
) -> list[dict[str, Any]]:
"""Записи `event` о своих `id` вложений и ключах объектов."""
return [
item
for item in self.events(event)
if item.get("attachment_id") in ids
or item.get("object_key") in keys
]
def kinds(
self,
event: str,
*,
ids: Collection[str] = (),
keys: Collection[str] = (),
) -> dict[str, str]:
"""`id` или ключ → класс расхождения в записях `event`."""
found: dict[str, str] = {}
for item in self.about(event, ids=ids, keys=keys):
name = (
item["attachment_id"]
if item.get("attachment_id") in ids
else item["object_key"]
)
found[name] = item["kind"]
return found
def assert_code_matches(self) -> None:
"""Код выхода соответствует записям прохода: 3 — остались
расхождения (запись `Found`) или отказ по пределу, иначе 0."""
finished = self.finished
assert finished["interrupted_by"] is None, finished
expected = 3 if self.events(FOUND) or finished["refused"] else 0
assert self.exit_code == expected, (self.exit_code, finished)
def run_reconcile(
stand: Stand,
mode: str,
limit: int | None = None,
) -> Reconcile:
"""Разовая сверка hook: `dry-run` или `apply`, с пределом изменений."""
args = [mode] if limit is None else [mode, str(limit)]
lines = stand("reconcile", *args).splitlines()
assert lines and lines[-1].startswith("exit_code="), lines[-5:]
records = []
for line in lines[:-1]:
if line.startswith("{"):
records.append(json.loads(line))
return Reconcile(records=records, exit_code=int(lines[-1].split("=")[1]))
def object_key(attachment_id: str) -> str:
return f"{FAULT_DATABASE}/attachments/{attachment_id}/original"
def lost_ids(stand: Stand) -> set[str]:
return set(stand("lost-ids").splitlines())
def put_object(stand: Stand, key: str, data: bytes) -> None:
stand("put-object", key, stdin=data)
def lose_original(stand: Stand, attachment: dict[str, Any]) -> None:
"""Готовое вложение старше grace без объекта: строка состарена, объект
удалён мимо API."""
stand("age-row", attachment["id"], str(AGED_S))
stand("delete-object", object_key(attachment["id"]))
def assert_lost_content(
api: Api,
actor: Actor,
attachment: dict[str, Any],
*,
aged: bool = False,
) -> None:
"""Помеченное вложение: байты — 404, метаданные — как при загрузке.
`aged` — строку состарил hook (`age-row`): её `created_at` и
`updated_at` сдвинуты им, а не сверкой, и сравниваются остальные поля.
"""
assert_error(api.attachment_content(actor, attachment["id"]), 404)
meta = assert_ok(
api.attachment_meta(actor, attachment["id"]),
200,
"Attachment",
)
if aged:
times = ("created_at", "updated_at")
meta = {key: value for key, value in meta.items() if key not in times}
attachment = {
key: value for key, value in attachment.items() if key not in times
}
assert meta == attachment
@pytest.mark.spec("storage-consistency", "Расхождения с обеих сторон найдены")
@pytest.mark.spec("storage-consistency", "Исправление расхождений")
@pytest.mark.spec("storage-consistency", "Повторная сверка")
@pytest.mark.spec("attachments", "Потерянный оригинал")
def test_reconcile_finds_and_fixes(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
# уборщик стенда стоит: зависшую загрузку P должна убрать сверка
with outage(stand, "stop", "cleaner"):
a, b, c = (api.upload(alice, chat["id"], data) for _ in range(3))
api.send_message(alice, chat["id"], "", attachment_ids=[a["id"]])
orphan = str(uuid.uuid4())
keys = {"o": object_key(orphan), "b": object_key(b["id"])}
put_object(stand, keys["o"], data)
stand("delete-object", object_key(a["id"]))
stand("delete-row", b["id"])
stand("set-size", c["id"], str(len(data) + 1))
filename = fault_filename()
before = attachment_rows(stand)
stand("fail-attachments", "commit", filename)
try:
resp = upload_raw(api, alice, chat, data, filename=filename)
assert_error(resp, 503)
finally:
stand("clear-fail-attachments")
(pending,) = new_ids(before, attachment_rows(stand))
assert pending in stored_ids(stand)
# последний объект записан только что: после G + 1 всё старше grace
time.sleep(OBJECT_AGE_WAIT_S)
ids = {a["id"], c["id"], pending}
snapshot = (attachment_rows(stand), stored_ids(stand), lost_ids(stand))
dry = run_reconcile(stand, "dry-run")
assert dry.kinds(FOUND, ids=ids, keys=keys.values()) == {
keys["o"]: "orphan_object",
keys["b"]: "orphan_object",
a["id"]: "missing_object",
c["id"]: "size_mismatch",
pending: "stale_pending",
}
for record in dry.about(FOUND, ids=ids, keys=keys.values()):
assert record["age_seconds"] >= CLEANER_GRACE_S, record
assert dry.exit_code == 3
# dry-run ничего не меняет: ни строк, ни объектов, ни пометок
after = (attachment_rows(stand), stored_ids(stand), lost_ids(stand))
assert after == snapshot
assert_error(api.attachment_content(alice, a["id"]), 500)
assert_ok(api.attachment_meta(alice, a["id"]), 200, "Attachment")
fixed = run_reconcile(stand, "apply")
actions = {
record.get("attachment_id")
if record.get("attachment_id") in ids
else record["object_key"]: record["action"]
for record in fixed.about(FIXED, ids=ids, keys=keys.values())
}
assert actions == {
keys["o"]: "deleted_object",
keys["b"]: "deleted_object",
a["id"]: "marked_lost",
c["id"]: "marked_lost",
pending: "removed_pending",
}
assert not fixed.about(FOUND, ids=ids, keys=keys.values())
fixed.assert_code_matches()
rows, stored = attachment_rows(stand), stored_ids(stand)
assert not {orphan, b["id"], pending} & stored
assert pending not in rows
assert {a["id"], c["id"]} <= lost_ids(stand)
assert rows[a["id"]] == rows[c["id"]] == "ready"
assert_lost_content(api, alice, a)
# у C размер в метаданных изменил hook (set-size), а не сверка
assert_lost_content(api, alice, c | {"size_bytes": len(data) + 1})
again = run_reconcile(stand, "dry-run")
assert not again.about(FOUND, ids=ids, keys=keys.values())
assert not again.about(FIXED, ids=ids, keys=keys.values())
again.assert_code_matches()
@pytest.mark.spec("storage-consistency", "Свежие не тронуты")
@pytest.mark.spec("storage-consistency", "Используемое вложение не удаляется")
@pytest.mark.spec("storage-consistency", "Чужой объект не удаляется")
def test_reconcile_keeps_fresh_used_and_unknown(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
used = api.upload(alice, chat["id"], data)
message = api.send_message(
alice,
chat["id"],
"",
attachment_ids=[used["id"]],
)
lose_original(stand, used)
# ключ, которого API не пишет: под префиксом вложений, но не <id>/original
unknown = f"{FAULT_DATABASE}/attachments/x-{uuid.uuid4()}"
put_object(stand, unknown, data)
time.sleep(OBJECT_AGE_WAIT_S)
# свежие: готовое вложение без объекта и объект без строки
fresh = api.upload(alice, chat["id"], data)
stand("delete-object", object_key(fresh["id"]))
fresh_object = str(uuid.uuid4())
put_object(stand, object_key(fresh_object), data)
ready_before = ready_ids(attachment_rows(stand))
try:
run = run_reconcile(stand, "apply")
keys = {unknown, object_key(fresh_object)}
ids = {used["id"], fresh["id"], fresh_object}
assert run.kinds(FOUND, ids=ids, keys=keys) == {
unknown: "unknown_object",
}
assert run.kinds(FIXED, ids=ids, keys=keys) == {
used["id"]: "missing_object",
}
assert run.exit_code == 3
assert run.finished["fresh_objects"] >= 1, run.finished
assert run.finished["fresh_rows"] >= 1, run.finished
# свежий объект на месте, свежее вложение не помечено
assert fresh_object in stored_ids(stand)
lost = lost_ids(stand)
assert fresh["id"] not in lost
# используемое: помечено, метаданные и ссылка в истории на месте
assert used["id"] in lost
assert_lost_content(api, alice, used, aged=True)
history = api.all_messages(alice, chat["id"])
(sent,) = (item for item in history if item["id"] == message["id"])
assert sent["attachment_ids"] == [used["id"]]
assert ready_before <= ready_ids(attachment_rows(stand))
# чужой объект не тронут: следующий проход снова его видит
again = run_reconcile(stand, "dry-run")
assert again.kinds(FOUND, keys={unknown}) == {
unknown: "unknown_object",
}
finally:
# стенд — без чужого и лишнего объекта, у свежего — его байты
stand("delete-object", unknown)
stand("delete-object", object_key(fresh_object))
put_object(stand, object_key(fresh["id"]), data)
@pytest.mark.spec("storage-consistency", "Оригинал вернулся")
def test_reconcile_restored_original(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.png_noise(64, 48, seed=7)
restored = api.upload(alice, chat["id"], data)
lose_original(stand, restored)
marked = run_reconcile(stand, "apply")
assert marked.kinds(FIXED, ids={restored["id"]}) == {
restored["id"]: "missing_object",
}
assert restored["id"] in lost_ids(stand)
assert_lost_content(api, alice, restored, aged=True)
# те же байты снова под ключом вложения
put_object(stand, object_key(restored["id"]), data)
cleared = run_reconcile(stand, "apply")
(record,) = cleared.about(FIXED, ids={restored["id"]})
assert (record["kind"], record["action"]) == (
"restored_object",
"cleared_lost",
)
assert restored["id"] not in lost_ids(stand)
assert_content(
api.attachment_content(alice, restored["id"]),
data,
"image/png",
)
again = run_reconcile(stand, "dry-run")
assert not again.about(FOUND, ids={restored["id"]})
@pytest.mark.spec("storage-consistency", "Предел изменений")
def test_reconcile_change_limit(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
limit = 2
batch = [
api.upload(alice, chat["id"], images.sample_png()) for _ in range(3)
]
ids = {item["id"] for item in batch}
for item in batch:
lose_original(stand, item)
refused = run_reconcile(stand, "apply", limit)
assert refused.exit_code == 3
(error,) = refused.events(LIMIT_EXCEEDED)
assert error["level"] == "error"
assert error["changes"] >= len(batch), error
assert error["max_changes"] == limit
assert refused.finished["refused"] is True
assert refused.finished["level"] == "warning"
assert not refused.about(FIXED, ids=ids)
assert not ids & lost_ids(stand)
assert all(
record["kind"] == "missing_object"
for record in refused.about(FOUND, ids=ids)
)
# предел не меньше числа изменений: исправлено всё
applied = run_reconcile(stand, "apply", 100)
assert set(applied.kinds(FIXED, ids=ids)) == ids
assert ids <= lost_ids(stand)
@pytest.mark.spec("storage-consistency", "S3 недоступен во время сверки")
def test_reconcile_object_storage_stopped(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
missing = api.upload(alice, chat["id"], images.sample_png())
lose_original(stand, missing)
with outage(stand, "stop", "s3"):
interrupted = run_reconcile(stand, "apply")
assert interrupted.exit_code == 1
assert interrupted.finished["interrupted_by"] == "object_storage"
assert not interrupted.events(FIXED)
assert missing["id"] not in lost_ids(stand)
applied = run_reconcile(stand, "apply")
assert applied.kinds(FIXED, ids={missing["id"]}) == {
missing["id"]: "missing_object",
}
assert missing["id"] in lost_ids(stand)
@pytest.mark.spec(
"storage-consistency",
"Прерванная сверка доводится повтором",
)
def test_reconcile_interrupted_by_database(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
filename = fault_filename()
failing = api.upload(
alice,
chat["id"],
images.sample_png(),
filename=filename,
)
other = api.upload(alice, chat["id"], images.sample_png())
ids = {failing["id"], other["id"]}
for item in (failing, other):
lose_original(stand, item)
stand("fail-attachments", "mark", filename)
try:
interrupted = run_reconcile(stand, "apply")
assert interrupted.exit_code == 1
assert interrupted.finished["interrupted_by"] == "database"
assert failing["id"] not in lost_ids(stand)
finally:
stand("clear-fail-attachments")
applied = run_reconcile(stand, "apply")
assert ids <= lost_ids(stand)
assert not applied.about(FOUND, ids=ids)
again = run_reconcile(stand, "dry-run")
assert not again.about(FOUND, ids=ids)
@pytest.mark.spec("storage-consistency", "Сверка под нагрузкой")
def test_reconcile_under_load(
api: Api,
stand: Stand,
alice: Actor,
bob: Actor,
chat: dict[str, Any],
) -> None:
"""Загрузки и отправки дольше grace, сверка с `--apply` раз в 3 с:
внесённое исправлено, ни одно подтверждённое вложение не потеряно."""
data = images.sample_png()
orphans = {str(uuid.uuid4()) for _ in range(2)}
for item in orphans:
put_object(stand, object_key(item), data)
injected = [api.upload(alice, chat["id"], data) for _ in range(2)]
for item in injected:
lose_original(stand, item)
lost_before = lost_ids(stand)
deadline = time.monotonic() + CLEANER_GRACE_S + LOAD_EXTRA_S
lock = threading.Lock()
uploads: dict[str, str] = {}
messages: dict[str, list[str]] = {}
failures: list[str] = []
passes: list[Reconcile] = []
def load(worker: int) -> None:
actor = alice if worker % 2 == 0 else bob
with Api(
str(api.client.base_url),
timeout=THREAD_CLIENT_TIMEOUT_S,
) as client:
number = 0
while time.monotonic() < deadline:
number += 1
body = images.png_noise(200, 170, seed=worker * 10**6 + number)
resp = client.post_attachment(actor, chat["id"], body)
if resp.status_code != 201:
with lock:
failures.append(f"upload {resp.status_code}")
continue
attachment = assert_ok(resp, 201, "Attachment")
# загрузка подтверждена: она обязана скачиваться
with lock:
uploads[attachment["id"]] = hashlib.sha256(
body,
).hexdigest()
message = client.send_message(
actor,
chat["id"],
"",
attachment_ids=[attachment["id"]],
)
with lock:
messages[message["id"]] = [attachment["id"]]
time.sleep(LOAD_PAUSE_S)
def reconcile() -> None:
while time.monotonic() < deadline:
started = time.monotonic()
passes.append(run_reconcile(stand, "apply"))
sleep_until(started + LOAD_RECONCILE_PERIOD_S)
def guarded(target: Callable[..., None], *args: Any) -> None:
# исключение потока — в список, а не молча в stderr
try:
target(*args)
except Exception as e:
with lock:
failures.append(repr(e))
threads = [
threading.Thread(target=guarded, args=(load, worker))
for worker in range(LOAD_THREADS)
]
threads.append(threading.Thread(target=guarded, args=(reconcile,)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert not failures, failures[:5]
assert uploads, "no uploads under load"
assert len(passes) >= 3, len(passes)
assert all(item.exit_code in (0, 3) for item in passes), [
item.exit_code for item in passes
]
# внесённые исправлены: объекты без строки удалены, потери помечены
assert not orphans & stored_ids(stand)
assert lost_ids(stand) - lost_before == {item["id"] for item in injected}
# ни одно подтверждённое вложение не потеряно
for attachment_id, digest in uploads.items():
resp = api.attachment_content(alice, attachment_id)
assert resp.status_code == 200, (attachment_id, resp.status_code)
assert hashlib.sha256(resp.content).hexdigest() == digest
history = {
item["id"]: item["attachment_ids"]
for item in api.all_messages(alice, chat["id"])
}
for message_id, attachment_ids in messages.items():
assert history[message_id] == attachment_ids
@pytest.mark.spec("storage-consistency", "Плановая сверка без команды")
def test_scheduled_reconcile(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
scheduled = api.upload(alice, chat["id"], images.sample_png())
lose_original(stand, scheduled)
log = stand("run-cleaner", str(SCHEDULED_RUN_S))
records = [
json.loads(line) for line in log.splitlines() if line.startswith("{")
]
passes = [item for item in records if item.get("event") == FINISHED]
assert passes, log[-2000:]
assert any(item["apply"] for item in passes), passes
assert scheduled["id"] in lost_ids(stand)