- python -m messenger.reconcile: merge-join листинга S3 и attachments по object_key; dry-run read-only конструктивно (default_transaction_read_only + S3 без записи), --apply: orphan/stale intent удаляются, ready-строки только в карантин (обратимо), перепроверка под FOR UPDATE, предохранитель от массового удаления; - attachment_ids хранится в строке сообщения (история остаётся одним index range scan), message_attachments — для FK и обратного поиска; - семафор полной проверки изображений (IMAGE_VERIFY_CONCURRENCY); - тесты: вложения (56), отказ/пауза S3 и деградированный режим LB, failover загрузки, приватность bucket, FAULT_POINTS после PUT/после COMMIT, janitor, reconciler; - бенчмарки памяти загрузок и стоимости обхода reconciler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
431 lines
20 KiB
Python
431 lines
20 KiB
Python
"""Reconciler of the two stores (lab 4, track 2): S3 objects vs attachment rows in PostgreSQL.
|
|
|
|
docker compose run --rm reconciler # dry-run: report only (default)
|
|
docker compose run --rm reconciler --apply # fix what is safe to fix
|
|
docker compose run --rm reconciler --verify-checksums # also read every object (SHA-256)
|
|
|
|
How it walks: both sides are read as key-ordered streams and merge-joined - ListObjectsV2
|
|
pages (prefix o/, byte order) against keyset pages of `attachments ORDER BY object_key`
|
|
(COLLATE "C" = the same byte order, unique index). Memory does not depend on the bucket size;
|
|
cost is ~N/1000 S3 list requests + N/page DB pages (measured: docs/CONSISTENCY.md).
|
|
|
|
What it finds and what --apply does (nothing else is ever changed):
|
|
|
|
kind condition --apply
|
|
orphan_object object, no row, older than --grace delete the object
|
|
stale_intent row 'pending' older than --grace (+/- object) delete object, then row
|
|
missing_object row 'ready', object absent, older than --grace quarantine the row
|
|
size_mismatch row 'ready', object size != size_bytes quarantine the row
|
|
checksum_mismatch row 'ready', SHA-256 differs (--verify-checksums) quarantine the row
|
|
restored_object row quarantined, object present and correct again remove the quarantine
|
|
fresh_* the same, but younger than --grace nothing (in-flight upload)
|
|
|
|
Safety:
|
|
* dry-run is read-only BY CONSTRUCTION: the PostgreSQL session runs with
|
|
default_transaction_read_only=on and the S3 wrapper has no write methods, so even a bug in
|
|
the planner cannot modify a store;
|
|
* ready rows are never deleted - a used (or unused) ready attachment can only be quarantined,
|
|
which is reversible; objects that have a row are never deleted unless the row is a stale
|
|
intent; anything younger than --grace is never touched;
|
|
* every action re-checks its condition right before acting, under a row lock (FOR UPDATE)
|
|
where a row exists, so the live API racing with the reconciler cannot be hurt;
|
|
* object first, row second: an interrupted run leaves a state the next run repairs;
|
|
re-running is idempotent (the second run finds nothing to do);
|
|
* safety valve: --apply refuses to delete more than --max-orphan-fraction of the scanned
|
|
objects (pointing it at the wrong/empty database would otherwise wipe the bucket).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import sys
|
|
import time
|
|
from collections import Counter
|
|
from collections.abc import AsyncIterator
|
|
from dataclasses import dataclass, field
|
|
|
|
import psycopg
|
|
|
|
from .config import ConfigError, Settings, _float, _secret, s3_settings
|
|
from .errors import Unavailable
|
|
from .storage import OBJECT_PREFIX, ListedObject, ObjectMissing, Storage
|
|
|
|
KINDS = ("orphan_object", "stale_intent", "missing_object", "size_mismatch", "checksum_mismatch",
|
|
"restored_object", "fresh_orphan_object", "fresh_intent", "fresh_missing_object")
|
|
MIN_SAFE_GRACE = 60.0 # > the longest possible upload (queue 5 s + body 30 s + verify 10 s + S3)
|
|
ACTION_OF = {"orphan_object": "delete_object", "stale_intent": "delete_intent", "missing_object": "quarantine",
|
|
"size_mismatch": "quarantine", "checksum_mismatch": "quarantine", "restored_object": "unquarantine"}
|
|
|
|
|
|
def log(text: str) -> None:
|
|
print(f"reconcile: {text}", file=sys.stderr, flush=True)
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class Row:
|
|
id: str
|
|
key: str
|
|
status: str
|
|
size: int
|
|
sha256: bytes
|
|
created_at: dt.datetime
|
|
updated_at: dt.datetime
|
|
lost_reason: str | None
|
|
used: bool
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class Finding:
|
|
kind: str
|
|
key: str
|
|
attachment_id: str | None = None
|
|
used: bool = False
|
|
detail: str = ""
|
|
result: str = "planned" # planned | applied | skipped:<why> | failed:<why>
|
|
|
|
|
|
@dataclass
|
|
class Stats:
|
|
objects: int = 0
|
|
rows: int = 0
|
|
consistent: int = 0
|
|
s3_list_requests: int = 0
|
|
s3_head_requests: int = 0
|
|
s3_get_bytes: int = 0
|
|
db_pages: int = 0
|
|
|
|
|
|
class ReadOnlyStorage:
|
|
"""The dry-run view of S3: listing and reading only - there is no delete to call."""
|
|
|
|
def __init__(self, storage: Storage):
|
|
self._s = storage
|
|
|
|
async def list_page(self, *args, **kwargs):
|
|
return await self._s.list_page(*args, **kwargs)
|
|
|
|
async def head(self, key: str):
|
|
return await self._s.head(key)
|
|
|
|
async def read_all(self, key: str, limit: int) -> bytes:
|
|
return await self._s.read_all(key, limit)
|
|
|
|
|
|
class Reconciler:
|
|
def __init__(self, conn: psycopg.AsyncConnection, storage: Storage | ReadOnlyStorage, *, grace: float,
|
|
page_size: int, verify: bool, apply: bool):
|
|
self.conn = conn
|
|
self.s3 = storage
|
|
self.grace = grace
|
|
self.page_size = page_size
|
|
self.verify = verify
|
|
self.apply = apply
|
|
self.stats = Stats()
|
|
self.findings: list[Finding] = []
|
|
|
|
# ---------------------------------------------------------- streams
|
|
async def objects(self) -> AsyncIterator[ListedObject]:
|
|
after = None
|
|
while True:
|
|
page, more = await self.s3.list_page(OBJECT_PREFIX, after, self.page_size)
|
|
self.stats.s3_list_requests += 1
|
|
for item in page:
|
|
self.stats.objects += 1
|
|
yield item
|
|
if not more or not page:
|
|
return
|
|
after = page[-1].key
|
|
|
|
async def rows(self) -> AsyncIterator[Row]:
|
|
after = ""
|
|
while True:
|
|
cur = await self.conn.execute(
|
|
"SELECT a.id, a.object_key, a.status, a.size_bytes, a.sha256, a.created_at, a.updated_at, "
|
|
"a.lost_reason, EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id) "
|
|
"FROM attachments a WHERE a.object_key > %s ORDER BY a.object_key LIMIT %s",
|
|
(after, self.page_size))
|
|
page = await cur.fetchall()
|
|
self.stats.db_pages += 1
|
|
for r in page:
|
|
self.stats.rows += 1
|
|
yield Row(str(r[0]), r[1], r[2], r[3], bytes(r[4]), r[5], r[6], r[7], r[8])
|
|
if len(page) < self.page_size:
|
|
return
|
|
after = page[-1][1]
|
|
|
|
# ---------------------------------------------------------- planning (read-only)
|
|
async def scan(self) -> None:
|
|
cur = await self.conn.execute("SELECT clock_timestamp()")
|
|
self.db_now = (await cur.fetchone())[0]
|
|
self.s3_now = time.time()
|
|
objects, rows = self.objects(), self.rows()
|
|
obj = await anext(objects, None)
|
|
row = await anext(rows, None)
|
|
while obj is not None or row is not None:
|
|
if row is None or (obj is not None and obj.key < row.key):
|
|
self.object_only(obj)
|
|
obj = await anext(objects, None)
|
|
elif obj is None or row.key < obj.key:
|
|
self.row_only(row)
|
|
row = await anext(rows, None)
|
|
else:
|
|
await self.both(obj, row)
|
|
obj = await anext(objects, None)
|
|
row = await anext(rows, None)
|
|
|
|
def row_old(self, row: Row) -> bool:
|
|
return (self.db_now - max(row.created_at, row.updated_at)).total_seconds() > self.grace
|
|
|
|
def object_only(self, obj: ListedObject) -> None:
|
|
old = self.s3_now - obj.last_modified_ts > self.grace
|
|
self.add(Finding("orphan_object" if old else "fresh_orphan_object", obj.key))
|
|
|
|
def row_only(self, row: Row) -> None:
|
|
if row.status == "pending":
|
|
self.add(Finding("stale_intent" if self.row_old(row) else "fresh_intent", row.key, row.id,
|
|
detail="object absent"))
|
|
elif row.lost_reason is not None:
|
|
self.stats.consistent += 1 # already quarantined, still missing: nothing new
|
|
else:
|
|
self.add(Finding("missing_object" if self.row_old(row) else "fresh_missing_object", row.key, row.id,
|
|
used=row.used))
|
|
|
|
async def both(self, obj: ListedObject, row: Row) -> None:
|
|
if row.status == "pending":
|
|
self.add(Finding("stale_intent" if self.row_old(row) else "fresh_intent", row.key, row.id,
|
|
detail="object present"))
|
|
return
|
|
problem = await self.object_problem(row, obj.size)
|
|
if problem:
|
|
if row.lost_reason is None:
|
|
self.add(Finding(problem, row.key, row.id, used=row.used))
|
|
else:
|
|
self.stats.consistent += 1 # quarantined and still broken
|
|
elif row.lost_reason is not None:
|
|
self.add(Finding("restored_object", row.key, row.id, used=row.used))
|
|
else:
|
|
self.stats.consistent += 1
|
|
|
|
async def object_problem(self, row: Row, size: int) -> str | None:
|
|
if size != row.size:
|
|
return "size_mismatch"
|
|
if self.verify:
|
|
data = await self.s3.read_all(row.key, row.size)
|
|
self.stats.s3_get_bytes += len(data)
|
|
if hashlib.sha256(data).digest() != row.sha256:
|
|
return "checksum_mismatch"
|
|
return None
|
|
|
|
def add(self, finding: Finding) -> None:
|
|
if finding.kind not in ACTION_OF:
|
|
finding.result = "not_actionable"
|
|
self.findings.append(finding)
|
|
|
|
# ---------------------------------------------------------- actions (--apply only)
|
|
async def run_actions(self, max_orphan_fraction: float) -> None:
|
|
orphans = sum(1 for f in self.findings if f.kind == "orphan_object")
|
|
if self.stats.objects and orphans > max_orphan_fraction * self.stats.objects:
|
|
raise SafetyValve(f"{orphans} of {self.stats.objects} objects look orphaned "
|
|
f"(> {max_orphan_fraction:.0%}); wrong database? nothing was changed")
|
|
handlers = {"delete_object": self.delete_object, "delete_intent": self.delete_intent,
|
|
"quarantine": self.quarantine, "unquarantine": self.unquarantine}
|
|
for finding in self.findings:
|
|
action = ACTION_OF.get(finding.kind)
|
|
if action is None:
|
|
continue
|
|
try:
|
|
finding.result = await handlers[action](finding)
|
|
except (Unavailable, psycopg.OperationalError) as exc:
|
|
finding.result = f"failed:{type(exc).__name__}"
|
|
raise # a store is down: stop; the next run continues from the committed state
|
|
|
|
async def delete_object(self, f: Finding) -> str:
|
|
cur = await self.conn.execute("SELECT 1 FROM attachments WHERE object_key = %s", (f.key,))
|
|
if await cur.fetchone():
|
|
return "skipped:row_appeared"
|
|
try:
|
|
head = await self.s3.head(f.key)
|
|
self.stats.s3_head_requests += 1
|
|
except ObjectMissing:
|
|
return "skipped:already_gone"
|
|
if time.time() - head.last_modified_ts <= self.grace:
|
|
return "skipped:object_rewritten_recently"
|
|
# No row names this key and the object is older than the grace period. Rows are always
|
|
# written BEFORE their object and keys are random and never reused, so no upload can
|
|
# still claim it.
|
|
await self.s3.delete(f.key)
|
|
return "applied"
|
|
|
|
async def delete_intent(self, f: Finding) -> str:
|
|
async with self.conn.transaction():
|
|
cur = await self.conn.execute(
|
|
"SELECT 1 FROM attachments WHERE id = %s AND status = 'pending' "
|
|
"AND greatest(created_at, updated_at) < clock_timestamp() - make_interval(secs => %s) FOR UPDATE",
|
|
(f.attachment_id, self.grace))
|
|
if await cur.fetchone() is None:
|
|
return "skipped:no_longer_stale_intent"
|
|
await self.s3.delete(f.key) # object first (idempotent), then the row
|
|
await self.conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'pending'",
|
|
(f.attachment_id,))
|
|
return "applied"
|
|
|
|
async def quarantine(self, f: Finding) -> str:
|
|
async with self.conn.transaction():
|
|
cur = await self.conn.execute(
|
|
"SELECT size_bytes, sha256 FROM attachments WHERE id = %s AND status = 'ready' "
|
|
"AND lost_at IS NULL FOR UPDATE", (f.attachment_id,))
|
|
row = await cur.fetchone()
|
|
if row is None:
|
|
return "skipped:row_changed"
|
|
reason = await self.current_problem(f.key, row[0], bytes(row[1]))
|
|
if reason is None:
|
|
return "skipped:object_ok_now"
|
|
await self.conn.execute(
|
|
"UPDATE attachments SET lost_at = clock_timestamp(), lost_reason = %s WHERE id = %s",
|
|
(reason, f.attachment_id))
|
|
return "applied"
|
|
|
|
async def unquarantine(self, f: Finding) -> str:
|
|
async with self.conn.transaction():
|
|
cur = await self.conn.execute(
|
|
"SELECT size_bytes, sha256 FROM attachments WHERE id = %s AND lost_at IS NOT NULL FOR UPDATE",
|
|
(f.attachment_id,))
|
|
row = await cur.fetchone()
|
|
if row is None:
|
|
return "skipped:row_changed"
|
|
if await self.current_problem(f.key, row[0], bytes(row[1])) is not None:
|
|
return "skipped:object_still_bad"
|
|
await self.conn.execute("UPDATE attachments SET lost_at = NULL, lost_reason = NULL WHERE id = %s",
|
|
(f.attachment_id,))
|
|
return "applied"
|
|
|
|
async def current_problem(self, key: str, size: int, sha256: bytes) -> str | None:
|
|
"""Fresh look at the object right before changing the row (the listing may be stale)."""
|
|
try:
|
|
head = await self.s3.head(key)
|
|
self.stats.s3_head_requests += 1
|
|
except ObjectMissing:
|
|
return "missing_object"
|
|
if head.size != size:
|
|
return "size_mismatch"
|
|
if self.verify:
|
|
data = await self.s3.read_all(key, size)
|
|
self.stats.s3_get_bytes += len(data)
|
|
if hashlib.sha256(data).digest() != sha256:
|
|
return "checksum_mismatch"
|
|
return None
|
|
|
|
# ---------------------------------------------------------- report
|
|
def report(self, mode: str, seconds: float, error: str | None, sample: int) -> dict:
|
|
kinds = Counter(f.kind for f in self.findings)
|
|
results = Counter(f.result.split(":")[0] for f in self.findings if f.kind in ACTION_OF)
|
|
samples = {}
|
|
for f in self.findings:
|
|
items = samples.setdefault(f.kind, [])
|
|
if len(items) < sample:
|
|
items.append({"key": f.key, "attachment_id": f.attachment_id, "used": f.used,
|
|
"result": f.result, **({"detail": f.detail} if f.detail else {})})
|
|
return {
|
|
"mode": mode, "grace_seconds": self.grace, "verify_checksums": self.verify,
|
|
"duration_seconds": round(seconds, 3), "error": error,
|
|
"scanned": {"objects": self.stats.objects, "rows": self.stats.rows, "consistent": self.stats.consistent},
|
|
"findings": {k: kinds.get(k, 0) for k in KINDS},
|
|
"used_attachments_in_findings": sum(1 for f in self.findings if f.used),
|
|
"actions": {"planned": sum(1 for f in self.findings if f.kind in ACTION_OF),
|
|
"applied": results.get("applied", 0), "skipped": results.get("skipped", 0),
|
|
"failed": results.get("failed", 0)},
|
|
"cost": {"s3_list_requests": self.stats.s3_list_requests, "s3_head_requests": self.stats.s3_head_requests,
|
|
"s3_get_bytes": self.stats.s3_get_bytes, "db_pages": self.stats.db_pages,
|
|
"page_size": self.page_size},
|
|
"samples": samples,
|
|
}
|
|
|
|
|
|
class SafetyValve(Exception):
|
|
pass
|
|
|
|
|
|
def arguments(argv: list[str] | None = None) -> argparse.Namespace:
|
|
p = argparse.ArgumentParser(prog="python -m messenger.reconcile", description=__doc__.split("\n")[0])
|
|
p.add_argument("--apply", action="store_true", help="fix findings (default: dry-run, read-only)")
|
|
p.add_argument("--grace", type=float, default=3600.0,
|
|
help="seconds; anything younger is never touched (default 3600, >= PENDING_GRACE_SECONDS)")
|
|
p.add_argument("--allow-small-grace", action="store_true",
|
|
help="permit --grace below 60 s (tests only: a grace shorter than an upload could remove the "
|
|
"intent of an upload that is still running; that upload then fails with 503)")
|
|
p.add_argument("--page-size", type=int, default=1000, help="S3 list / DB page size (1..1000)")
|
|
p.add_argument("--verify-checksums", action="store_true", help="read every ready object and compare SHA-256")
|
|
p.add_argument("--samples", type=int, default=20, help="keys listed per finding kind in the report")
|
|
p.add_argument("--max-orphan-fraction", type=float, default=0.5,
|
|
help="--apply refuses if more than this share of objects look orphaned (default 0.5)")
|
|
args = p.parse_args(argv)
|
|
if not 1 <= args.page_size <= 1000:
|
|
p.error("--page-size must be 1..1000")
|
|
if args.grace < 1 or (args.grace < MIN_SAFE_GRACE and not args.allow_small_grace):
|
|
p.error(f"--grace must be >= {MIN_SAFE_GRACE:.0f} s (or >= 1 s with --allow-small-grace)")
|
|
if not 0 < args.max_orphan_fraction <= 1:
|
|
p.error("--max-orphan-fraction must be in (0, 1]")
|
|
return args
|
|
|
|
|
|
async def run(args: argparse.Namespace) -> int:
|
|
url = _secret("DATABASE_URL", required=True)
|
|
base = s3_settings()
|
|
settings = Settings(host="", port=0, env="lab", log_level="info", shutdown_timeout=0, max_body_bytes=1024,
|
|
database_url=url, **base)
|
|
timeout_ms = int(_float("DB_TIMEOUT_SECONDS", 10.0, 1.0, 120.0) * 1000)
|
|
options = f"-c statement_timeout={timeout_ms} -c lock_timeout={timeout_ms // 2}"
|
|
if not args.apply:
|
|
options += " -c default_transaction_read_only=on" # dry-run: PostgreSQL itself refuses writes
|
|
mode = "apply" if args.apply else "dry-run"
|
|
storage = Storage(settings)
|
|
await storage.open()
|
|
started = time.perf_counter()
|
|
error = None
|
|
code = 0
|
|
try:
|
|
conn = await psycopg.AsyncConnection.connect(url, autocommit=True, connect_timeout=5, options=options,
|
|
application_name=f"messenger-reconcile-{mode}")
|
|
except psycopg.OperationalError as exc:
|
|
await storage.close()
|
|
error = f"store_unavailable: database {type(exc).__name__}"
|
|
print(json.dumps({"mode": mode, "error": error}, ensure_ascii=False))
|
|
log(error)
|
|
return 1
|
|
rec = Reconciler(conn, storage if args.apply else ReadOnlyStorage(storage), grace=args.grace,
|
|
page_size=args.page_size, verify=args.verify_checksums, apply=args.apply)
|
|
try:
|
|
log(f"{mode}: scanning bucket {settings.s3_bucket} (prefix {OBJECT_PREFIX}) against table attachments")
|
|
await rec.scan()
|
|
log(f"scan done: {rec.stats.objects} objects, {rec.stats.rows} rows, {len(rec.findings)} findings")
|
|
if args.apply:
|
|
await rec.run_actions(args.max_orphan_fraction)
|
|
except SafetyValve as exc:
|
|
error, code = f"safety_valve: {exc}", 3
|
|
except (Unavailable, psycopg.OperationalError) as exc:
|
|
error, code = f"store_unavailable: {type(exc).__name__}", 1
|
|
finally:
|
|
await conn.close()
|
|
await storage.close()
|
|
print(json.dumps(rec.report(mode, time.perf_counter() - started, error, args.samples), ensure_ascii=False,
|
|
indent=1))
|
|
if error:
|
|
log(error)
|
|
return code
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
args = arguments(argv)
|
|
try:
|
|
return asyncio.run(run(args))
|
|
except ConfigError as exc:
|
|
print(f"configuration error: {exc}", file=sys.stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|