feat: add reconcile strategies, deep check, rate limit and cost profile

- reconcile --strategy head, --deep (checksum_mismatch), restore needs the same SHA-256
- [reconciler] max_objects_per_second (2000), pause interrupted by signal
- --apply stops rechecks once the limit is exceeded (unchecked)
- pass cost in the summary: S3 objects and requests, bytes, DB sessions, phases
- S3 client counters, cleaner exits with os._exit after main()
- fault tests, hook args, driver reconcile-signal --pace
- bench profile reconcile / reconcile_quick: fill outside the API, gateway metrics, background load
- sync spec deltas, rules, AGENTS.md, PLAN.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 04:52:56 +03:00
co-authored by Claude Opus 5.5
parent dcdfe5f2e4
commit 8d4cf7eebf
41 changed files with 5344 additions and 441 deletions
+53 -7
View File
@@ -82,11 +82,18 @@
`attachments/`, символы [A-Za-z0-9._/-]
lost-ids `id` вложений с потерянным оригиналом
(lost_at задан)
reconcile dry-run|apply [<предел>]
reconcile dry-run|apply [<предел>] [--strategy batch|head] [--deep]
[--max-objects-per-second R]
разовая сверка (`docker compose run --rm
--no-deps -T cleaner reconcile [--apply]
[--max-changes N]`): записи процесса и
строка `exit_code=<n>`; код hook — 0
[--max-changes N] …`): стратегия обхода,
глубокая сверка и предел скорости (R —
неотрицательное число, 0 — без предела)
проверяются по списку и передаются команде
как есть (design change
`track2-reconcile-cost`, решение 14);
записи процесса и строка `exit_code=<n>`;
код hook — 0
stop|start cleaner сервис уборщика стенда
run-cleaner <секунд> отдельный уборщик
`<FAULT_PROJECT>-cleaner-scheduled` с
@@ -421,6 +428,10 @@ client.put_object(Bucket=s3.bucket, Key=sys.argv[1], Body=body)
# символы ключа объекта, который hook пишет или удаляет мимо API
OBJECT_KEY_RE = re.compile(r"^[A-Za-z0-9._/-]+$")
RECONCILE_MODES = {"dry-run": (), "apply": ("--apply",)}
# стратегии обхода и предел скорости сверки (change track2-reconcile-cost):
# неотрицательное число, целое или с дробной частью
RECONCILE_STRATEGIES = ("batch", "head")
RATE_PATTERN = re.compile(r"[0-9]+(\.[0-9]+)?")
# плановая сверка отдельного уборщика: раз в секунду
SCHEDULED_CLEANER_ENV = "RECONCILER__INTERVAL_SECONDS=1"
SCHEDULED_CLEANER_MAX_S = 60
@@ -817,12 +828,47 @@ def row_change(project: str, sql: str, attachment_id: str, value: str) -> str:
return ""
def reconcile_options(args: list[str]) -> list[str]:
"""Аргументы сверки после режима: необязательный предел изменений
первым, затем `--strategy batch|head`, `--deep`,
`--max-objects-per-second R`. Каждый — по списку разрешённых, иначе
код 2 hook."""
usage = (
"reconcile dry-run|apply [<max changes>] [--strategy batch|head] "
"[--deep] [--max-objects-per-second R]"
)
options: list[str] = []
rest = list(args)
if rest and not rest[0].startswith("--"):
if not rest[0].isdigit() or int(rest[0]) < 1:
raise HookError(usage)
options += ["--max-changes", str(int(rest.pop(0)))]
seen: set[str] = set()
while rest:
name = rest.pop(0)
if name in seen:
raise HookError(usage)
seen.add(name)
if name == "--deep":
options.append(name)
elif name == "--strategy" and rest and rest[0] in RECONCILE_STRATEGIES:
options += [name, rest.pop(0)]
elif name == "--max-objects-per-second" and rest:
value = rest.pop(0)
if not RATE_PATTERN.fullmatch(value):
raise HookError(usage)
options += [name, value]
else:
raise HookError(usage)
return options
def reconcile(project: str, mode: str, args: list[str]) -> str:
"""Разовая сверка в одноразовом контейнере уборщика стенда: записи
процесса и строка `exit_code=<n>`."""
if mode not in RECONCILE_MODES or len(args) > 1:
raise HookError("reconcile dry-run|apply [<max changes>]")
limit = ("--max-changes", str(int(args[0]))) if args else ()
if mode not in RECONCILE_MODES:
raise HookError("reconcile dry-run|apply [<max changes>] [options]")
options = reconcile_options(args)
result = compose_run(
project,
"run",
@@ -832,7 +878,7 @@ def reconcile(project: str, mode: str, args: list[str]) -> str:
"cleaner",
"reconcile",
*RECONCILE_MODES[mode],
*limit,
*options,
)
lines = [*result.stdout.splitlines(), *result.stderr.splitlines()]
return "\n".join([*lines, f"exit_code={result.returncode}"])
+288 -3
View File
@@ -20,12 +20,14 @@ change `fix-upload-put-flake`.
import hashlib
import json
import math
import os
import random
import statistics
import threading
import time
import uuid
from collections.abc import Callable, Collection, Iterator
from collections.abc import Callable, Collection, Iterator, Sequence
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import dataclass
@@ -1670,10 +1672,14 @@ def run_reconcile(
stand: Stand,
mode: str,
limit: int | None = None,
*,
options: Sequence[str] = (),
) -> Reconcile:
"""Разовая сверка hook: `dry-run` или `apply`, с пределом изменений."""
"""Разовая сверка hook: `dry-run` или `apply`, с пределом изменений;
`options` — стратегия, глубина и предел скорости (change
`track2-reconcile-cost`) как аргументы команды."""
args = [mode] if limit is None else [mode, str(limit)]
lines = stand("reconcile", *args).splitlines()
lines = stand("reconcile", *args, *options).splitlines()
assert lines and lines[-1].startswith("exit_code="), lines[-5:]
records = []
for line in lines[:-1]:
@@ -2292,3 +2298,282 @@ def test_scheduled_reconcile(
assert passes, log[-2000:]
assert any(item["apply"] for item in passes), passes
assert scheduled["id"] in lost_ids(stand)
# ---------------------------------------------------------------------------
# Стоимость сверки (change track2-reconcile-cost, design, решение 14):
# стратегия HEAD, глубокая сверка и класс «другой SHA-256», снятие пометки
# только при том же SHA-256, предел скорости, отказ по пределу без лишних
# перепроверок. Аргументы сверки hook передаёт команде как есть
# ---------------------------------------------------------------------------
HEAD_STRATEGY = ("--strategy", "head")
DEEP = ("--deep",)
NO_RATE_LIMIT = ("--max-objects-per-second", "0")
# сколько вложений загружает тест предела скорости: объектов в bucket
# заведомо хватает на несколько секунд прохода
RATE_UPLOADS = 8
# во сколько раз проход с пределом длиннее числа объектов на предел
# (допуск на округление `duration_ms`)
RATE_SLACK = 0.95
def same_size_bytes(data: bytes, *, seed: int) -> bytes:
"""Другие байты того же размера, от зерна теста."""
other = random.Random(seed).randbytes(len(data))
assert other != data
return other
def findings(run: Reconcile) -> set[tuple[str, str]]:
"""Все расхождения прохода: класс и ключ объекта."""
return {(item["kind"], item["object_key"]) for item in run.events(FOUND)}
@pytest.mark.spec("storage-consistency", "Стратегия HEAD находит то же")
def test_reconcile_head_strategy_same_findings(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Те же расхождения, что в `test_reconcile_finds_and_fixes`: dry-run
стратегией по умолчанию и `--strategy head` называют одно и то же, а
HEAD-проход дороже по запросам к S3 и сеансам PostgreSQL."""
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))
time.sleep(OBJECT_AGE_WAIT_S)
ids = {a["id"], c["id"], pending}
expected = {
keys["o"]: "orphan_object",
keys["b"]: "orphan_object",
a["id"]: "missing_object",
c["id"]: "size_mismatch",
pending: "stale_pending",
}
snapshot = (attachment_rows(stand), stored_ids(stand), lost_ids(stand))
batch = run_reconcile(stand, "dry-run")
head = run_reconcile(stand, "dry-run", options=HEAD_STRATEGY)
assert batch.kinds(FOUND, ids=ids, keys=keys.values()) == expected
assert head.kinds(FOUND, ids=ids, keys=keys.values()) == expected
# не только свои: весь отчёт и итог по классам одинаковы
assert findings(head) == findings(batch)
for field in ("found", "listed_objects", "checked_rows"):
assert head.finished[field] == batch.finished[field], field
assert head.exit_code == batch.exit_code == 3
assert (batch.finished["strategy"], head.finished["strategy"]) == (
"batch",
"head",
)
assert (
head.finished["s3_requests"]["head"]
> batch.finished["s3_requests"]["head"]
), (head.finished, batch.finished)
assert head.finished["db_sessions"] > batch.finished["db_sessions"]
after = (attachment_rows(stand), stored_ids(stand), lost_ids(stand))
assert after == snapshot
# стенд — без внесённых расхождений для следующих тестов
fixed = run_reconcile(stand, "apply")
assert set(fixed.kinds(FIXED, ids=ids, keys=keys.values())) == set(
expected,
)
@pytest.mark.spec(
"storage-consistency",
"Другой SHA-256 находит глубокая сверка",
)
def test_reconcile_deep_checksum(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.png_noise(64, 48, seed=11)
a = api.upload(alice, chat["id"], data)
api.send_message(alice, chat["id"], "", attachment_ids=[a["id"]])
other = same_size_bytes(data, seed=11)
# объект перезаписан мимо API байтами того же размера
put_object(stand, object_key(a["id"]), other)
stand("age-row", a["id"], str(AGED_S))
time.sleep(OBJECT_AGE_WAIT_S)
snapshot = (attachment_rows(stand), stored_ids(stand), lost_ids(stand))
shallow = run_reconcile(stand, "dry-run")
assert not shallow.about(FOUND, ids={a["id"]})
assert shallow.finished["deep"] is False
deep = run_reconcile(stand, "dry-run", options=DEEP)
assert deep.kinds(FOUND, ids={a["id"]}) == {a["id"]: "checksum_mismatch"}
assert deep.finished["deep"] is True
assert deep.finished["read_bytes"] >= len(data), deep.finished
assert deep.finished["s3_requests"]["get"] >= 1, deep.finished
assert deep.exit_code == 3
after = (attachment_rows(stand), stored_ids(stand), lost_ids(stand))
assert after == snapshot
# SHA-256 объектов в журнале нет
journal = json.dumps(deep.records)
for body in (data, other):
assert hashlib.sha256(body).hexdigest() not in journal
applied = run_reconcile(stand, "apply", options=DEEP)
(record,) = applied.about(FIXED, ids={a["id"]})
assert (record["kind"], record["action"]) == (
"checksum_mismatch",
"marked_lost",
)
assert a["id"] in lost_ids(stand)
assert_lost_content(api, alice, a, aged=True)
@pytest.mark.spec(
"storage-consistency",
"Вернулся другой объект того же размера",
)
@pytest.mark.spec("storage-consistency", "Оригинал вернулся")
def test_reconcile_restore_needs_same_bytes(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.png_noise(64, 48, seed=13)
restored = api.upload(alice, chat["id"], data)
ids = {restored["id"]}
lose_original(stand, restored)
marked = run_reconcile(stand, "apply")
assert marked.kinds(FIXED, ids=ids) == {restored["id"]: "missing_object"}
assert restored["id"] in lost_ids(stand)
# под ключом — другие байты того же размера: пометка остаётся
put_object(
stand,
object_key(restored["id"]),
same_size_bytes(data, seed=13),
)
time.sleep(OBJECT_AGE_WAIT_S)
wrong = run_reconcile(stand, "apply")
assert not wrong.about(FIXED, ids=ids)
assert all(
record["kind"] != "restored_object"
for record in wrong.about(FOUND, ids=ids)
)
assert restored["id"] in lost_ids(stand)
assert_lost_content(api, alice, restored, aged=True)
# те же байты, что были загружены: пометка снята
put_object(stand, object_key(restored["id"]), data)
time.sleep(OBJECT_AGE_WAIT_S)
cleared = run_reconcile(stand, "apply")
(record,) = cleared.about(FIXED, ids=ids)
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=ids)
@pytest.mark.spec("storage-consistency", "Скорость прохода ограничена")
@pytest.mark.spec("storage-consistency", "Без ограничения скорости")
def test_reconcile_rate_limit(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Предел на четверть объектов прохода: проход длится не меньше
объектов на предел, находки и код — как без предела."""
data = images.sample_png()
for _ in range(RATE_UPLOADS):
api.upload(alice, chat["id"], data)
lost = api.upload(alice, chat["id"], data)
ids = {lost["id"]}
lose_original(stand, lost)
# уборщик стенда стоит: между проходами стенд не меняется
with outage(stand, "stop", "cleaner"):
free = run_reconcile(stand, "dry-run", options=NO_RATE_LIMIT)
rate = max(5, math.ceil(free.finished["storage_objects"] / 4))
limited = run_reconcile(
stand,
"dry-run",
options=("--max-objects-per-second", str(rate)),
)
assert free.finished["max_objects_per_second"] == 0
assert limited.finished["max_objects_per_second"] == rate
objects = limited.finished["storage_objects"]
assert objects >= RATE_UPLOADS, limited.finished
assert (
limited.finished["duration_ms"] >= 1000 * objects / rate * RATE_SLACK
), limited.finished
assert free.finished["duration_ms"] < limited.finished["duration_ms"]
expected = {lost["id"]: "missing_object"}
assert free.kinds(FOUND, ids=ids) == expected
assert limited.kinds(FOUND, ids=ids) == expected
assert free.exit_code == limited.exit_code == 3
# стенд — без внесённой потери
applied = run_reconcile(stand, "apply")
assert applied.kinds(FIXED, ids=ids) == expected
@pytest.mark.spec(
"storage-consistency",
"Отказ по пределу без лишних перепроверок",
)
def test_reconcile_limit_stops_rechecks(
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(6)
]
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"] == limit + 1, error
assert error["max_changes"] == limit
assert error["unchecked"] >= len(batch) - (limit + 1), error
assert refused.finished["unchecked"] == error["unchecked"]
assert refused.finished["refused"] is True
assert not refused.about(FIXED, ids=ids)
assert not ids & lost_ids(stand)
# dry-run перепроверяет каждого и называет все шесть
dry = run_reconcile(stand, "dry-run")
assert dry.kinds(FOUND, ids=ids) == dict.fromkeys(ids, "missing_object")
assert dry.finished["unchecked"] == 0
applied = run_reconcile(stand, "apply", 100)
assert set(applied.kinds(FIXED, ids=ids)) == ids
assert ids <= lost_ids(stand)