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:
@@ -96,6 +96,22 @@
|
||||
нет, готовое вложение скачивается с тем же SHA-256; триггер
|
||||
снимается в finally и в начале следующего прогона; код 1 при
|
||||
расхождении, без LB — код 2
|
||||
reconcile-cycle только стенд с LB: спек storage-consistency, сверка
|
||||
bucket и БД — исходный dry-run без расхождений (иначе код 2),
|
||||
расхождения с обеих сторон (объект мимо API и чужой ключ —
|
||||
docker exec реплики своими ключами, удалённые объекты — weed
|
||||
shell fs.rm, удалённая строка и другой размер — psql, обрыв
|
||||
между объектом и фиксацией — триггер COMMIT на уникальный
|
||||
filename), после grace 30 с dry-run без изменений, 500 до
|
||||
сверки, --apply, 404 и 200 после, повтор, удаление чужого
|
||||
объекта, свежий объект после grace, возврат оригинала; код 1
|
||||
при расхождении, без LB — код 2
|
||||
reconcile-stress [--seconds S] [--clients N] только стенд с LB:
|
||||
«Сверка под нагрузкой» — внесённые расхождения, N клиентов S
|
||||
секунд загружают PNG ~100 KiB и отправляют сообщения, поток
|
||||
сверки — --apply с grace 20 с раз в ~3 с; каждое 201
|
||||
скачивается с тем же SHA-256, сообщения отдают свои вложения,
|
||||
повтор — 0; код 1 при расхождении
|
||||
lb-upload-timeouts [--config F] [--image ТЕГ] без стенда: спек
|
||||
load-balancing «Загрузки через балансировщик» — временная
|
||||
сеть, HAProxy закреплённого образа с конфигурацией F (по
|
||||
@@ -137,6 +153,7 @@ import re
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
@@ -145,7 +162,9 @@ import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
from collections import Counter
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
@@ -2771,6 +2790,826 @@ def report_rows(rows: list[tuple[str, str, str]]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
# reconcile-cycle и reconcile-stress (design change track2-reconciler,
|
||||
# решение 12): разовая сверка — в одноразовом контейнере уборщика стенда с
|
||||
# grace прогона. Триггер обрыва между объектом и фиксацией — отложенный
|
||||
# триггер ограничения на уникальный filename: COMMIT перевода в ready
|
||||
# падает (08006), объект остаётся, строка pending. Имя постоянное: остаток
|
||||
# прерванного прогона убирается в начале следующего
|
||||
RC_TRIGGER = "driver_rc_fail_commit"
|
||||
RC_FAIL_COMMIT_SQL = """\
|
||||
CREATE OR REPLACE FUNCTION {name}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.filename = TG_ARGV[0] AND OLD.status = 'pending'
|
||||
AND NEW.status = 'ready' THEN
|
||||
RAISE EXCEPTION 'driver: attachment ready commit failure'
|
||||
USING ERRCODE = '08006';
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END
|
||||
$$;
|
||||
DROP TRIGGER IF EXISTS {name} ON attachments;
|
||||
CREATE CONSTRAINT TRIGGER {name} AFTER UPDATE ON attachments
|
||||
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW
|
||||
EXECUTE FUNCTION {name}('{filename}');
|
||||
"""
|
||||
RC_CLEAR_SQL = f"""\
|
||||
DROP TRIGGER IF EXISTS {RC_TRIGGER} ON attachments;
|
||||
DROP FUNCTION IF EXISTS {RC_TRIGGER}();
|
||||
"""
|
||||
# grace прогона цикла и стресса: больше границы живой загрузки (17 с)
|
||||
RC_GRACE_S = 30
|
||||
RC_STRESS_GRACE_S = 20
|
||||
RC_STRESS_PERIOD_S = 3
|
||||
RC_STRESS_PAUSE_S = 0.2
|
||||
# объект мимо API: botocore образа с настройками процесса реплики (адрес,
|
||||
# регион, ключи API — из окружения контейнера, в драйвер не попадают)
|
||||
RC_PUT_OBJECT_PY = """\
|
||||
import sys
|
||||
import botocore.session
|
||||
from botocore.config import Config
|
||||
from src.config import settings
|
||||
s3 = settings.s3
|
||||
client = botocore.session.get_session().create_client(
|
||||
"s3",
|
||||
endpoint_url=s3.endpoint_url,
|
||||
region_name=s3.region,
|
||||
aws_access_key_id=s3.access_key_id.get_secret_value(),
|
||||
aws_secret_access_key=s3.secret_access_key.get_secret_value(),
|
||||
config=Config(s3={"addressing_style": "path"},
|
||||
retries={"total_max_attempts": 1}),
|
||||
)
|
||||
body = sys.stdin.buffer.read()
|
||||
client.put_object(Bucket=s3.bucket, Key=sys.argv[1], Body=body)
|
||||
"""
|
||||
RC_FOUND = "Found storage discrepancy"
|
||||
RC_FIXED = "Fixed storage discrepancy"
|
||||
RC_FINISHED = "Finished reconcile pass"
|
||||
|
||||
|
||||
def rc_reconcile(
|
||||
*,
|
||||
apply: bool,
|
||||
grace: int | None = None,
|
||||
) -> tuple[int, list[dict[str, object]]]:
|
||||
"""Разовая сверка в контейнере уборщика: код выхода и записи журнала."""
|
||||
env = (
|
||||
[]
|
||||
if grace is None
|
||||
else ["-e", f"CLEANER__PENDING_GRACE_SECONDS={grace}"]
|
||||
)
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
*env,
|
||||
"cleaner",
|
||||
"reconcile",
|
||||
*(["--apply"] if apply else []),
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
records = []
|
||||
for line in proc.stdout.splitlines():
|
||||
if line.startswith("{"):
|
||||
with contextlib.suppress(json.JSONDecodeError):
|
||||
records.append(json.loads(line))
|
||||
return proc.returncode, records
|
||||
|
||||
|
||||
def rc_events(
|
||||
records: list[dict[str, object]],
|
||||
event: str,
|
||||
) -> list[dict[str, object]]:
|
||||
return [item for item in records if item.get("event") == event]
|
||||
|
||||
|
||||
def rc_finished(records: list[dict[str, object]]) -> dict[str, object]:
|
||||
found = rc_events(records, RC_FINISHED)
|
||||
return found[-1] if found else {}
|
||||
|
||||
|
||||
def rc_print_pass(
|
||||
title: str,
|
||||
code: int,
|
||||
records: list[dict[str, object]],
|
||||
) -> None:
|
||||
"""Таблица «класс → ключ → id → возраст» прохода и его итог."""
|
||||
finished = rc_finished(records)
|
||||
print(f"{title}: exit {code}")
|
||||
for record in (
|
||||
*rc_events(records, RC_FOUND),
|
||||
*rc_events(records, RC_FIXED),
|
||||
):
|
||||
action = record.get("action") or "-"
|
||||
sizes = ""
|
||||
if record.get("stored_size") is not None:
|
||||
sizes = (
|
||||
f" size {record.get('size_bytes')} stored "
|
||||
f"{record.get('stored_size')}"
|
||||
)
|
||||
print(
|
||||
f" {record.get('level', ''):<7} {record.get('kind', ''):<16} "
|
||||
f"{action:<15} {record.get('object_key')} id "
|
||||
f"{record.get('attachment_id') or '-'} age "
|
||||
f"{record.get('age_seconds')} s{sizes}",
|
||||
)
|
||||
keys = (
|
||||
"listed_objects",
|
||||
"checked_rows",
|
||||
"found",
|
||||
"fixed",
|
||||
"remaining",
|
||||
"fresh_objects",
|
||||
"fresh_rows",
|
||||
"lost_known",
|
||||
"refused",
|
||||
"interrupted_by",
|
||||
"duration_ms",
|
||||
)
|
||||
print(
|
||||
" total: " + ", ".join(f"{key}={finished.get(key)}" for key in keys),
|
||||
)
|
||||
|
||||
|
||||
def rc_kinds(
|
||||
records: list[dict[str, object]],
|
||||
event: str,
|
||||
names: dict[str, str],
|
||||
) -> dict[str, str]:
|
||||
"""Свои находки: имя в прогоне → класс (по ключу объекта)."""
|
||||
by_key = {value: name for name, value in names.items()}
|
||||
return {
|
||||
by_key[str(record.get("object_key"))]: str(record.get("kind"))
|
||||
for record in rc_events(records, event)
|
||||
if str(record.get("object_key")) in by_key
|
||||
}
|
||||
|
||||
|
||||
def rc_put_object(key: str, data: bytes) -> int:
|
||||
"""Объект мимо API процессом в контейнере реплики; код выхода."""
|
||||
replicas = compose("ps", "-q", "--status", "running", "api").split()
|
||||
if not replicas:
|
||||
return 1
|
||||
proc = subprocess.run(
|
||||
["docker", "exec", "-i", replicas[0], "python", "-c", RC_PUT_OBJECT_PY]
|
||||
+ [key],
|
||||
input=data,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
return proc.returncode
|
||||
|
||||
|
||||
def rc_lost_ids() -> set[str]:
|
||||
return set(
|
||||
stand_psql(
|
||||
"SELECT id FROM attachments WHERE lost_at IS NOT NULL;\n",
|
||||
).split(),
|
||||
)
|
||||
|
||||
|
||||
def rc_rows() -> dict[str, str]:
|
||||
"""Строки вложений рабочей базы: `id` → `статус размер`."""
|
||||
rows = stand_psql(
|
||||
"SELECT id || '|' || status || ' ' || size_bytes FROM attachments;\n",
|
||||
).splitlines()
|
||||
return dict(line.split("|") for line in rows if "|" in line)
|
||||
|
||||
|
||||
def rc_png(seed: int, *, width: int = 200, height: int = 170) -> bytes:
|
||||
"""Настоящий RGB PNG из шума (~100 KiB при 200 × 170) на stdlib."""
|
||||
noise = random_bytes(seed, height * (width * 3))
|
||||
rows = b"".join(
|
||||
b"\x00" + noise[row * width * 3 : (row + 1) * width * 3]
|
||||
for row in range(height)
|
||||
)
|
||||
|
||||
def chunk(kind: bytes, body: bytes) -> bytes:
|
||||
crc = zlib.crc32(kind + body)
|
||||
return (
|
||||
struct.pack(">I", len(body)) + kind + body + struct.pack(">I", crc)
|
||||
)
|
||||
|
||||
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"IDAT", zlib.compress(rows, 1))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def random_bytes(seed: int, size: int) -> bytes:
|
||||
"""Детерминированные «шумовые» байты по зерну: PNG из них почти не
|
||||
сжимается, и размер файла — около `size`."""
|
||||
out = bytearray()
|
||||
counter = 0
|
||||
while len(out) < size:
|
||||
out += hashlib.sha256(f"{seed}:{counter}".encode()).digest()
|
||||
counter += 1
|
||||
return bytes(out[:size])
|
||||
|
||||
|
||||
def rc_stand() -> tuple[str, str] | None:
|
||||
"""Bucket и имя базы рабочего стенда из `docker compose config`."""
|
||||
try:
|
||||
stand = s3_stand()
|
||||
config = json.loads(compose("config", "--format", "json"))
|
||||
database = str(
|
||||
config["services"]["api"]["environment"]["DATABASE__NAME"],
|
||||
)
|
||||
except (RuntimeError, KeyError, StopIteration, ValueError) as e:
|
||||
print(f"FAIL: compose config of the stand: {e}")
|
||||
return None
|
||||
return stand["bucket"], database
|
||||
|
||||
|
||||
def rc_signals(body: Callable[[], int]) -> int:
|
||||
"""SIGTERM и SIGHUP — как Ctrl+C: `finally` тела снимает триггер."""
|
||||
|
||||
def interrupted(signum: int, _frame: object) -> None:
|
||||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||||
|
||||
previous = {
|
||||
signum: signal.signal(signum, interrupted)
|
||||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||||
}
|
||||
try:
|
||||
return body()
|
||||
finally:
|
||||
for signum, handler in previous.items():
|
||||
signal.signal(signum, handler)
|
||||
|
||||
|
||||
def cmd_reconcile_cycle(port: int) -> int:
|
||||
"""Спек `storage-consistency`, сверка bucket и БД на рабочем стенде
|
||||
через LB (design change `track2-reconciler`, решение 12): исходный
|
||||
dry-run без расхождений, расхождения с обеих сторон, dry-run без
|
||||
изменений, 500 до сверки, `--apply`, 404 и 200 после, повтор, удаление
|
||||
чужого объекта оператором, свежий объект после grace, возврат
|
||||
оригинала. Триггер — на уникальный `filename`, снимается в `finally` и
|
||||
в начале следующего прогона. Токенов и секретов в выводе нет."""
|
||||
if no_lb(port):
|
||||
print("reconcile-cycle needs the stand with the load balancer")
|
||||
return 2
|
||||
return rc_signals(lambda: reconcile_cycle(port))
|
||||
|
||||
|
||||
def reconcile_cycle(port: int) -> int:
|
||||
"""Тело `cmd_reconcile_cycle`."""
|
||||
names = rc_stand()
|
||||
if names is None:
|
||||
return 1
|
||||
bucket, database = names
|
||||
prefix = f"{database}/{ATTACHMENT_KEY_PREFIX}"
|
||||
stand_psql(RC_CLEAR_SQL)
|
||||
rows: list[tuple[str, str, str]] = []
|
||||
|
||||
# 1. исходный dry-run с grace по умолчанию: стенд сведён
|
||||
code, records = rc_reconcile(apply=False)
|
||||
rc_print_pass("initial dry-run (default grace)", code, records)
|
||||
if code != 0 or rc_events(records, RC_FOUND):
|
||||
print("FAIL: the stand is not reconciled, run make reconcile first")
|
||||
return 2
|
||||
|
||||
# 2. участники и вложения через LB
|
||||
people = attachment_people(port, "rc")
|
||||
if people is None:
|
||||
return 1
|
||||
_, tokens, chat_id = people
|
||||
data = FIXTURE_PNG.read_bytes()
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
uploaded: dict[str, dict[str, object]] = {}
|
||||
for name in ("A", "B", "C"):
|
||||
status, _, attachment = upload_bytes(
|
||||
port,
|
||||
tokens["alice"],
|
||||
chat_id,
|
||||
data,
|
||||
content_type="image/png",
|
||||
filename=f"rc-{tag}-{name}.png",
|
||||
)
|
||||
rows.append((f"upload {name}", "201", str(status)))
|
||||
if status != 201 or not isinstance(attachment, dict):
|
||||
return report_reconcile(rows)
|
||||
uploaded[name] = attachment
|
||||
status, _, message = call(
|
||||
port,
|
||||
"POST",
|
||||
f"{CHATS}/{chat_id}/messages",
|
||||
token=tokens["alice"],
|
||||
body={"text": "", "attachment_ids": [uploaded["A"]["id"]]},
|
||||
extra=key_header(),
|
||||
)
|
||||
rows.append(("message with A", "201", str(status)))
|
||||
message_id = message.get("id") if isinstance(message, dict) else None
|
||||
keys = {
|
||||
name: f"{prefix}/{attachment['id']}/{ATTACHMENT_ORIGINAL}"
|
||||
for name, attachment in uploaded.items()
|
||||
}
|
||||
keys["O"] = f"{prefix}/{uuid.uuid4()}/{ATTACHMENT_ORIGINAL}"
|
||||
keys["X"] = f"{prefix}/x-{uuid.uuid4()}"
|
||||
ids = {
|
||||
name: str(attachment["id"]) for name, attachment in uploaded.items()
|
||||
}
|
||||
try:
|
||||
# 3. расхождения с обеих сторон
|
||||
rows.append(
|
||||
("put O without a row", "0", str(rc_put_object(keys["O"], data))),
|
||||
)
|
||||
rows.append(
|
||||
("put X (unknown key)", "0", str(rc_put_object(keys["X"], data))),
|
||||
)
|
||||
weed_shell(f"fs.rm /buckets/{bucket}/{keys['A']}")
|
||||
# id — UUID из ответа API: безопасны в тексте SQL
|
||||
stand_psql(f"DELETE FROM attachments WHERE id = '{ids['B']}';\n")
|
||||
stand_psql(
|
||||
"UPDATE attachments SET size_bytes = size_bytes + 1 "
|
||||
f"WHERE id = '{ids['C']}';\n",
|
||||
)
|
||||
fail_name = f"rc-{tag}-P.png"
|
||||
before = attachment_statuses()
|
||||
stand_psql(
|
||||
RC_FAIL_COMMIT_SQL.format(name=RC_TRIGGER, filename=fail_name),
|
||||
)
|
||||
status, _, _ = upload_bytes(
|
||||
port,
|
||||
tokens["alice"],
|
||||
chat_id,
|
||||
data,
|
||||
content_type="image/png",
|
||||
filename=fail_name,
|
||||
)
|
||||
stand_psql(RC_CLEAR_SQL)
|
||||
rows.append(("upload P with COMMIT failure", "503", str(status)))
|
||||
pending = sorted(set(attachment_statuses()) - set(before))
|
||||
rows.append(("pending rows of P", "1", str(len(pending))))
|
||||
if len(pending) != 1:
|
||||
return report_reconcile(rows)
|
||||
ids["P"] = pending[0]
|
||||
keys["P"] = f"{prefix}/{ids['P']}/{ATTACHMENT_ORIGINAL}"
|
||||
print("keys of the run:")
|
||||
for name, key in sorted(keys.items()):
|
||||
print(f" {name}: {key}")
|
||||
|
||||
# 4. после grace прогона — dry-run без изменений
|
||||
print(f"waiting {RC_GRACE_S + 1} s for grace {RC_GRACE_S} s")
|
||||
time.sleep(RC_GRACE_S + 1)
|
||||
snapshot = (
|
||||
rc_rows(),
|
||||
stored_attachment_ids(bucket, database),
|
||||
rc_lost_ids(),
|
||||
)
|
||||
code, records = rc_reconcile(apply=False, grace=RC_GRACE_S)
|
||||
rc_print_pass(f"dry-run (grace {RC_GRACE_S} s)", code, records)
|
||||
after = (
|
||||
rc_rows(),
|
||||
stored_attachment_ids(bucket, database),
|
||||
rc_lost_ids(),
|
||||
)
|
||||
rows.append(("dry-run exit code", "3", str(code)))
|
||||
found = rc_kinds(records, RC_FOUND, keys)
|
||||
for name, kind in (
|
||||
("O", "orphan_object"),
|
||||
("B", "orphan_object"),
|
||||
("A", "missing_object"),
|
||||
("C", "size_mismatch"),
|
||||
("P", "stale_pending"),
|
||||
("X", "unknown_object"),
|
||||
):
|
||||
rows.append((f"dry-run finds {name}", kind, found.get(name, "-")))
|
||||
rows.append(
|
||||
(
|
||||
"dry-run changes rows, objects, marks",
|
||||
"no",
|
||||
"no" if after == snapshot else "yes",
|
||||
),
|
||||
)
|
||||
|
||||
# 5. байты потерянного до сверки
|
||||
status, _, _ = call_bytes(
|
||||
port,
|
||||
"GET",
|
||||
f"{ATTACHMENTS}/{ids['A']}/content",
|
||||
token=tokens["bob"],
|
||||
)
|
||||
rows.append(("A content before apply", "500", str(status)))
|
||||
|
||||
# 6. --apply; свежий объект F записан прямо перед ним
|
||||
keys["F"] = f"{prefix}/{uuid.uuid4()}/{ATTACHMENT_ORIGINAL}"
|
||||
rows.append(("put fresh F", "0", str(rc_put_object(keys["F"], data))))
|
||||
fresh_written = time.monotonic()
|
||||
code, records = rc_reconcile(apply=True, grace=RC_GRACE_S)
|
||||
rc_print_pass(f"apply (grace {RC_GRACE_S} s)", code, records)
|
||||
rows.append(("apply exit code (X left)", "3", str(code)))
|
||||
fixed = {
|
||||
name: str(record.get("action"))
|
||||
for record in rc_events(records, RC_FIXED)
|
||||
for name, key in keys.items()
|
||||
if record.get("object_key") == key
|
||||
}
|
||||
for name, action in (
|
||||
("O", "deleted_object"),
|
||||
("B", "deleted_object"),
|
||||
("A", "marked_lost"),
|
||||
("C", "marked_lost"),
|
||||
("P", "removed_pending"),
|
||||
):
|
||||
rows.append((f"apply fixes {name}", action, fixed.get(name, "-")))
|
||||
rows.append(("apply touches F (fresh)", "-", fixed.get("F", "-")))
|
||||
stored = stored_attachment_ids(bucket, database)
|
||||
statuses = attachment_statuses()
|
||||
lost = rc_lost_ids()
|
||||
rows.append(
|
||||
("A and C marked lost", "yes", yes({ids["A"], ids["C"]} <= lost)),
|
||||
)
|
||||
rows.append(
|
||||
(
|
||||
"P row and object",
|
||||
"absent",
|
||||
"present"
|
||||
if ids["P"] in statuses or ids["P"] in stored
|
||||
else "absent",
|
||||
),
|
||||
)
|
||||
for name in ("O", "B"):
|
||||
object_id = keys[name].split("/")[-2]
|
||||
rows.append(
|
||||
(
|
||||
f"object {name}",
|
||||
"absent",
|
||||
"present" if object_id in stored else "absent",
|
||||
),
|
||||
)
|
||||
rows.append(
|
||||
(
|
||||
"fresh F kept",
|
||||
"present",
|
||||
"present" if keys["F"].split("/")[-2] in stored else "absent",
|
||||
),
|
||||
)
|
||||
status, _, _ = call_bytes(
|
||||
port,
|
||||
"GET",
|
||||
f"{ATTACHMENTS}/{ids['A']}/content",
|
||||
token=tokens["bob"],
|
||||
)
|
||||
rows.append(("A content after apply", "404", str(status)))
|
||||
status, _, meta = call(
|
||||
port,
|
||||
"GET",
|
||||
f"{ATTACHMENTS}/{ids['A']}",
|
||||
token=tokens["bob"],
|
||||
)
|
||||
rows.append(("A metadata after apply", "200", str(status)))
|
||||
rows.append(
|
||||
(
|
||||
"A metadata = upload response",
|
||||
"yes",
|
||||
yes(meta == uploaded["A"]),
|
||||
),
|
||||
)
|
||||
status, _, page = call(
|
||||
port,
|
||||
"GET",
|
||||
f"{CHATS}/{chat_id}/messages",
|
||||
token=tokens["bob"],
|
||||
)
|
||||
linked = [
|
||||
item.get("attachment_ids")
|
||||
for item in (
|
||||
page.get("items", []) if isinstance(page, dict) else []
|
||||
)
|
||||
if item.get("id") == message_id
|
||||
]
|
||||
rows.append(
|
||||
(
|
||||
"history keeps A in the message",
|
||||
"yes",
|
||||
yes(linked == [[ids["A"]]]),
|
||||
),
|
||||
)
|
||||
|
||||
# 7. повтор: остался только чужой X; оператор удаляет его
|
||||
code, records = rc_reconcile(apply=False, grace=RC_GRACE_S)
|
||||
rc_print_pass("repeat dry-run", code, records)
|
||||
found = rc_kinds(records, RC_FOUND, keys)
|
||||
rows.append(
|
||||
("repeat finds only X", "X", ",".join(sorted(found)) or "-"),
|
||||
)
|
||||
rows.append(("repeat exit code", "3", str(code)))
|
||||
weed_shell(f"fs.rm /buckets/{bucket}/{keys['X']}")
|
||||
print("operator removed X (weed shell fs.rm)")
|
||||
code, records = rc_reconcile(apply=False, grace=RC_GRACE_S)
|
||||
rc_print_pass("dry-run after X is removed", code, records)
|
||||
rows.append(("exit code after X is removed", "0", str(code)))
|
||||
wait = max(0.0, fresh_written + RC_GRACE_S + 1 - time.monotonic())
|
||||
print(f"waiting {wait:.0f} s until F is older than grace")
|
||||
time.sleep(wait)
|
||||
code, records = rc_reconcile(apply=True, grace=RC_GRACE_S)
|
||||
rc_print_pass("apply after F aged", code, records)
|
||||
fixed = rc_kinds(records, RC_FIXED, keys)
|
||||
rows.append(
|
||||
("F removed after grace", "orphan_object", fixed.get("F", "-")),
|
||||
)
|
||||
rows.append(("apply exit code (F)", "0", str(code)))
|
||||
|
||||
# 8. возврат оригинала
|
||||
rows.append(
|
||||
("put A original back", "0", str(rc_put_object(keys["A"], data))),
|
||||
)
|
||||
code, records = rc_reconcile(apply=True, grace=RC_GRACE_S)
|
||||
rc_print_pass("apply after A is back", code, records)
|
||||
fixed = rc_kinds(records, RC_FIXED, keys)
|
||||
rows.append(("A restored", "restored_object", fixed.get("A", "-")))
|
||||
status, _, payload = call_bytes(
|
||||
port,
|
||||
"GET",
|
||||
f"{ATTACHMENTS}/{ids['A']}/content",
|
||||
token=tokens["bob"],
|
||||
)
|
||||
rows.append(("A content after restore", "200", str(status)))
|
||||
rows.append(
|
||||
(
|
||||
"A sha256 = uploaded",
|
||||
"yes",
|
||||
yes(sha256_hex(payload) == uploaded["A"]["sha256"]),
|
||||
),
|
||||
)
|
||||
code, records = rc_reconcile(apply=False, grace=RC_GRACE_S)
|
||||
rc_print_pass("final dry-run", code, records)
|
||||
rows.append(("final dry-run exit code", "0", str(code)))
|
||||
finally:
|
||||
stand_psql(RC_CLEAR_SQL)
|
||||
# чужой и свежий объект не остаются при любом исходе
|
||||
for name in ("X", "F", "O"):
|
||||
if name in keys:
|
||||
weed_shell(f"fs.rm /buckets/{bucket}/{keys[name]}")
|
||||
triggers = stand_psql(
|
||||
f"SELECT count(*) FROM pg_trigger WHERE tgname = '{RC_TRIGGER}';\n",
|
||||
).strip()
|
||||
rows.append(("driver trigger left", "0", triggers))
|
||||
return report_reconcile(rows)
|
||||
|
||||
|
||||
def yes(value: bool) -> str:
|
||||
return "yes" if value else "no"
|
||||
|
||||
|
||||
def report_reconcile(rows: list[tuple[str, str, str]]) -> int:
|
||||
"""Таблица «проверка → ожидаемо → получено»; код 1 при расхождении."""
|
||||
width = max(len(check) for check, _, _ in rows)
|
||||
failed = 0
|
||||
for check, expected, got in rows:
|
||||
ok = expected == got
|
||||
failed += not ok
|
||||
print(
|
||||
f"{check:<{width}} expected {expected:<15} got {got}"
|
||||
+ ("" if ok else " FAIL"),
|
||||
)
|
||||
if failed:
|
||||
print(f"FAIL: {failed} check(s) failed")
|
||||
return 1
|
||||
print("PASS: reconcile found and fixed the discrepancies, repeat found 0")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_reconcile_stress(port: int, *, seconds: float, clients: int) -> int:
|
||||
"""Спек `storage-consistency`, «Сверка под нагрузкой», на рабочем
|
||||
стенде через LB (design change `track2-reconciler`, решение 12):
|
||||
внесённые расхождения, `clients` клиентов `seconds` секунд загружают
|
||||
PNG ~100 KiB и отправляют сообщения, поток сверки — `--apply` с grace
|
||||
20 с раз в ~3 с. В конце — каждое 201 скачивается с тем же SHA-256,
|
||||
каждое сообщение отдаёт своё вложение, повтор — 0. Проверка
|
||||
корректности, не замер: тихий хост не нужен."""
|
||||
if no_lb(port):
|
||||
print("reconcile-stress needs the stand with the load balancer")
|
||||
return 2
|
||||
if seconds <= RC_STRESS_GRACE_S:
|
||||
print(f"--seconds must be longer than grace {RC_STRESS_GRACE_S} s")
|
||||
return 2
|
||||
return rc_signals(lambda: reconcile_stress(port, seconds, clients))
|
||||
|
||||
|
||||
def reconcile_stress(port: int, seconds: float, clients: int) -> int:
|
||||
"""Тело `cmd_reconcile_stress`."""
|
||||
names = rc_stand()
|
||||
if names is None:
|
||||
return 1
|
||||
bucket, database = names
|
||||
prefix = f"{database}/{ATTACHMENT_KEY_PREFIX}"
|
||||
code, records = rc_reconcile(apply=False, grace=RC_STRESS_GRACE_S)
|
||||
rc_print_pass(
|
||||
f"precondition dry-run (grace {RC_STRESS_GRACE_S} s)",
|
||||
code,
|
||||
records,
|
||||
)
|
||||
if code != 0 or rc_events(records, RC_FOUND):
|
||||
print("FAIL: the stand is not reconciled, run make reconcile first")
|
||||
return 2
|
||||
people = attachment_people(port, "rs")
|
||||
if people is None:
|
||||
return 1
|
||||
_, tokens, chat_id = people
|
||||
data = FIXTURE_PNG.read_bytes()
|
||||
rows: list[tuple[str, str, str]] = []
|
||||
orphans = [
|
||||
f"{prefix}/{uuid.uuid4()}/{ATTACHMENT_ORIGINAL}" for _ in range(2)
|
||||
]
|
||||
for key in orphans:
|
||||
rows.append(
|
||||
("put object without a row", "0", str(rc_put_object(key, data))),
|
||||
)
|
||||
injected: list[str] = []
|
||||
for _ in range(2):
|
||||
status, _, attachment = upload_bytes(
|
||||
port,
|
||||
tokens["alice"],
|
||||
chat_id,
|
||||
data,
|
||||
content_type="image/png",
|
||||
filename="rs-lost.png",
|
||||
)
|
||||
if status != 201 or not isinstance(attachment, dict):
|
||||
print(f"FAIL: upload {status}")
|
||||
return 1
|
||||
injected.append(str(attachment["id"]))
|
||||
weed_shell(
|
||||
f"fs.rm /buckets/{bucket}/{prefix}/{attachment['id']}/"
|
||||
f"{ATTACHMENT_ORIGINAL}",
|
||||
)
|
||||
lost_before = rc_lost_ids()
|
||||
deadline = time.monotonic() + seconds
|
||||
lock = threading.Lock()
|
||||
uploads: dict[str, str] = {}
|
||||
messages: dict[str, str] = {}
|
||||
codes: Counter[int] = Counter()
|
||||
passes: list[tuple[int, list[dict[str, object]]]] = []
|
||||
errors: list[str] = []
|
||||
|
||||
def load(worker: int) -> None:
|
||||
token = tokens["alice"] if worker % 2 == 0 else tokens["bob"]
|
||||
number = 0
|
||||
while time.monotonic() < deadline:
|
||||
number += 1
|
||||
body = rc_png(worker * 1_000_000 + number)
|
||||
status, _, attachment = upload_bytes(
|
||||
port,
|
||||
token,
|
||||
chat_id,
|
||||
body,
|
||||
content_type="image/png",
|
||||
filename="rs.png",
|
||||
)
|
||||
with lock:
|
||||
codes[status] += 1
|
||||
if status != 201 or not isinstance(attachment, dict):
|
||||
continue
|
||||
attachment_id = str(attachment["id"])
|
||||
with lock:
|
||||
uploads[attachment_id] = sha256_hex(body)
|
||||
status, _, message = call(
|
||||
port,
|
||||
"POST",
|
||||
f"{CHATS}/{chat_id}/messages",
|
||||
token=token,
|
||||
body={"text": "", "attachment_ids": [attachment_id]},
|
||||
extra=key_header(),
|
||||
timeout=30,
|
||||
)
|
||||
if status == 201 and isinstance(message, dict):
|
||||
with lock:
|
||||
messages[str(message["id"])] = attachment_id
|
||||
else:
|
||||
with lock:
|
||||
errors.append(f"message {status}")
|
||||
# пауза клиента: синтетические объекты остаются в рабочем
|
||||
# bucket, без неё 4 клиента за 40 с пишут ~5 800 по 100 KiB
|
||||
time.sleep(RC_STRESS_PAUSE_S)
|
||||
|
||||
def reconcile() -> None:
|
||||
while time.monotonic() < deadline:
|
||||
started = time.monotonic()
|
||||
passes.append(rc_reconcile(apply=True, grace=RC_STRESS_GRACE_S))
|
||||
time.sleep(
|
||||
max(0.0, started + RC_STRESS_PERIOD_S - time.monotonic()),
|
||||
)
|
||||
|
||||
def guarded(target: Callable[..., None], *args: object) -> None:
|
||||
try:
|
||||
target(*args)
|
||||
except Exception as e: # noqa: BLE001 — в отчёт, а не в stderr
|
||||
with lock:
|
||||
errors.append(repr(e))
|
||||
|
||||
print(
|
||||
f"load: {clients} clients for {seconds:.0f} s, apply every {RC_STRESS_PERIOD_S} s",
|
||||
)
|
||||
threads = [
|
||||
threading.Thread(target=guarded, args=(load, worker))
|
||||
for worker in range(clients)
|
||||
]
|
||||
threads.append(threading.Thread(target=guarded, args=(reconcile,)))
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
# проход после нагрузки: всё внесённое уже старше grace
|
||||
final_code, final_records = rc_reconcile(
|
||||
apply=True,
|
||||
grace=RC_STRESS_GRACE_S,
|
||||
)
|
||||
passes.append((final_code, final_records))
|
||||
fixed: Counter[str] = Counter()
|
||||
for _, pass_records in passes:
|
||||
for record in rc_events(pass_records, RC_FIXED):
|
||||
fixed[str(record.get("kind"))] += 1
|
||||
stored = stored_attachment_ids(bucket, database)
|
||||
lost_new = rc_lost_ids() - lost_before
|
||||
mismatched = 0
|
||||
for attachment_id, digest in uploads.items():
|
||||
status, _, payload = call_bytes(
|
||||
port,
|
||||
"GET",
|
||||
f"{ATTACHMENTS}/{attachment_id}/content",
|
||||
token=tokens["bob"],
|
||||
)
|
||||
if status != 200 or sha256_hex(payload) != digest:
|
||||
mismatched += 1
|
||||
history: dict[str, list[object]] = {}
|
||||
cursor = None
|
||||
while True:
|
||||
path = f"{CHATS}/{chat_id}/messages?limit=100"
|
||||
if cursor:
|
||||
path += "&" + urllib.parse.urlencode({"cursor": cursor})
|
||||
status, _, page = call(port, "GET", path, token=tokens["alice"])
|
||||
if status != 200 or not isinstance(page, dict):
|
||||
errors.append(f"history {status}")
|
||||
break
|
||||
for item in page["items"]:
|
||||
history[str(item["id"])] = item["attachment_ids"]
|
||||
cursor = page.get("next_cursor")
|
||||
if not cursor:
|
||||
break
|
||||
broken = sum(
|
||||
history.get(message_id) != [attachment_id]
|
||||
for message_id, attachment_id in messages.items()
|
||||
)
|
||||
code, records = rc_reconcile(apply=False, grace=RC_STRESS_GRACE_S)
|
||||
rc_print_pass("repeat dry-run", code, records)
|
||||
print(
|
||||
"uploads by status: "
|
||||
+ ", ".join(f"{k}={v}" for k, v in sorted(codes.items())),
|
||||
)
|
||||
print(f"messages sent: {len(messages)}")
|
||||
print("reconcile passes: " + ", ".join(str(item[0]) for item in passes))
|
||||
print(
|
||||
"fixed by class: "
|
||||
+ (", ".join(f"{k}={v}" for k, v in sorted(fixed.items())) or "-"),
|
||||
)
|
||||
rows.append(("uploads 201", ">0", ">0" if uploads else "0"))
|
||||
rows.append(
|
||||
(
|
||||
"uploads not 201",
|
||||
"0",
|
||||
str(sum(v for k, v in codes.items() if k != 201)),
|
||||
),
|
||||
)
|
||||
rows.append(
|
||||
(
|
||||
"passes interrupted (exit 1)",
|
||||
"0",
|
||||
str(sum(item[0] == 1 for item in passes)),
|
||||
),
|
||||
)
|
||||
rows.append(
|
||||
(
|
||||
"objects without a row removed",
|
||||
"yes",
|
||||
yes(not {key.split("/")[-2] for key in orphans} & stored),
|
||||
),
|
||||
)
|
||||
rows.append(
|
||||
("new lost marks = injected", "yes", yes(lost_new == set(injected))),
|
||||
)
|
||||
rows.append(("downloads with other sha256", "0", str(mismatched)))
|
||||
rows.append(("messages with unavailable attachment", "0", str(broken)))
|
||||
rows.append(("thread errors", "0", str(len(errors))))
|
||||
rows.append(("repeat dry-run exit code", "0", str(code)))
|
||||
for error in errors[:5]:
|
||||
print(f" error: {error}")
|
||||
return report_reconcile(rows)
|
||||
|
||||
|
||||
# lb-upload-timeouts: сроки LB пути загрузки на заглушке (design change
|
||||
# upload-memory, решение 7). Молчание заглушки: дольше timeout server
|
||||
# прочих путей (10 с), но меньше срока пути загрузки (30 с) — и дольше его
|
||||
@@ -3574,6 +4413,10 @@ def main() -> int:
|
||||
failover.add_argument("--mode", choices=("stop", "kill"), default="stop")
|
||||
sub.add_parser("attachment-storage")
|
||||
sub.add_parser("upload-consistency")
|
||||
sub.add_parser("reconcile-cycle")
|
||||
stress = sub.add_parser("reconcile-stress")
|
||||
stress.add_argument("--seconds", type=float, default=40)
|
||||
stress.add_argument("--clients", type=int, default=4)
|
||||
lbto = sub.add_parser("lb-upload-timeouts")
|
||||
lbto.add_argument(
|
||||
"--config",
|
||||
@@ -3667,6 +4510,14 @@ def main() -> int:
|
||||
return cmd_attachment_storage(port)
|
||||
if args.cmd == "upload-consistency":
|
||||
return cmd_upload_consistency(port)
|
||||
if args.cmd == "reconcile-cycle":
|
||||
return cmd_reconcile_cycle(port)
|
||||
if args.cmd == "reconcile-stress":
|
||||
return cmd_reconcile_stress(
|
||||
port,
|
||||
seconds=args.seconds,
|
||||
clients=args.clients,
|
||||
)
|
||||
if args.cmd == "lb-upload-timeouts":
|
||||
return cmd_lb_upload_timeouts(args.config, args.image)
|
||||
if args.cmd == "stop-at-start":
|
||||
|
||||
Reference in New Issue
Block a user