fix: address track2-reconciler verify findings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 21:04:01 +03:00
co-authored by Claude Opus 5.5
parent a6071dafa0
commit 84f8c353e9
17 changed files with 770 additions and 56 deletions
+158 -2
View File
@@ -112,6 +112,14 @@
сверки — --apply с grace 20 с раз в ~3 с; каждое 201
скачивается с тем же SHA-256, сообщения отдают свои вложения,
повтор — 0; код 1 при расхождении
reconcile-signal только не рабочий проект compose (окружение
COMPOSE_PROJECT_NAME / COMPOSE_FILE; mtusi-lab4 — код 2): спек
graceful-shutdown, разовый проход сверки, прерванный сигналом,
— код 1: docker compose pause s3, run -d cleaner reconcile
--apply, через секунду после «Started cleaner» docker stop;
interrupted_by stop, «Stopped cleaner» с exit_code 1, остановка
быстрее stop_grace_period 10 с; S3 размораживается в finally;
код 1 при расхождении
lb-upload-timeouts [--config F] [--image ТЕГ] без стенда: спек
load-balancing «Загрузки через балансировщик» — временная
сеть, HAProxy закреплённого образа с конфигурацией F (по
@@ -3365,7 +3373,11 @@ def yes(value: bool) -> str:
return "yes" if value else "no"
def report_reconcile(rows: list[tuple[str, str, str]]) -> int:
def report_reconcile(
rows: list[tuple[str, str, str]],
*,
passed: str = "reconcile found and fixed the discrepancies, repeat found 0",
) -> int:
"""Таблица «проверка → ожидаемо → получено»; код 1 при расхождении."""
width = max(len(check) for check, _, _ in rows)
failed = 0
@@ -3379,7 +3391,7 @@ def report_reconcile(rows: list[tuple[str, str, str]]) -> int:
if failed:
print(f"FAIL: {failed} check(s) failed")
return 1
print("PASS: reconcile found and fixed the discrepancies, repeat found 0")
print(f"PASS: {passed}")
return 0
@@ -3610,6 +3622,147 @@ def reconcile_stress(port: int, seconds: float, clients: int) -> int:
return report_reconcile(rows)
# reconcile-signal (design change track2-reconciler, «Уточнения apply», п.
# 23): код разового прохода, прерванного сигналом. S3 заморожен, поэтому
# только не рабочий проект compose
RS_WORKING_PROJECT = "mtusi-lab4"
RS_START_TIMEOUT_S = 30
# SIGTERM — через столько после «Started cleaner»: первая страница списка
# уже ждёт замороженный S3
RS_AFTER_START_S = 1.0
# stop_grace_period уборщика в docker-compose.yml: дольше — был бы SIGKILL
RS_STOP_LIMIT_S = 10
def cmd_reconcile_signal() -> int:
"""Спек `graceful-shutdown`, разовый проход сверки, прерванный сигналом,
— код 1: на стенде проекта compose из окружения (`COMPOSE_PROJECT_NAME`
и др., рабочий `mtusi-lab4` — отказ, код 2) `docker compose pause s3`,
`run -d --no-deps cleaner reconcile --apply`, через секунду после
«Started cleaner» — `docker stop`; S3 размораживается в `finally`.
Таблица и записи процесса без секретов; код 1 при расхождении."""
try:
config = json.loads(compose("config", "--format", "json"))
except (RuntimeError, ValueError) as e:
print(f"FAIL: compose config of the stand: {e}")
return 2
project = str(config.get("name", ""))
if project == RS_WORKING_PROJECT:
print(
"reconcile-signal pauses S3: run it on a temporary stand "
f"(COMPOSE_PROJECT_NAME), not {RS_WORKING_PROJECT}",
)
return 2
services = config.get("services", {})
if "cleaner" not in services or "s3" not in services:
print(f"FAIL: no cleaner or s3 service in project {project}")
return 2
if not compose("ps", "-q", "--status", "running", "s3").strip():
print(f"FAIL: s3 of project {project} is not running")
return 2
name = f"{project}-reconcile-signal"
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
started = False
took = -1.0
exit_code = ""
logs = ""
compose("pause", "s3")
print(f"{project}: s3 paused")
try:
compose(
"run",
"-d",
"--no-deps",
"--name",
name,
"cleaner",
"reconcile",
"--apply",
)
deadline = time.monotonic() + RS_START_TIMEOUT_S
while time.monotonic() < deadline:
logs = docker_logs(name)
if '"Started cleaner"' in logs:
started = True
break
time.sleep(0.2)
if started:
time.sleep(RS_AFTER_START_S)
print("docker stop while reconcile waits for paused S3")
began = time.monotonic()
subprocess.run(["docker", "stop", name], capture_output=True)
took = time.monotonic() - began
exit_code = subprocess.run(
["docker", "inspect", "-f", "{{.State.ExitCode}}", name],
capture_output=True,
text=True,
check=False,
).stdout.strip()
logs = docker_logs(name)
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
compose("unpause", "s3")
print(f"{project}: s3 unpaused")
records = []
for line in logs.splitlines():
if line.startswith("{"):
with contextlib.suppress(json.JSONDecodeError):
records.append(json.loads(line))
shown = ("event", "level", "mode", "operation", "error_type")
shown += ("duration_ms", "interrupted_by", "exit_code", "timestamp")
print("== records of the one-off reconcile")
for record in records:
print(
json.dumps(
{key: record[key] for key in shown if key in record},
ensure_ascii=False,
),
)
finished = rc_finished(records)
stopped = [
item for item in records if item.get("event") == "Stopped cleaner"
]
print(f"docker stop took {took:.1f} s, exit code {exit_code or '-'}")
rows = [
("Started cleaner (mode reconcile)", "yes", yes(started)),
("exit code", "1", exit_code),
(
"Finished reconcile pass interrupted_by",
"stop",
str(finished.get("interrupted_by")),
),
(
"Stopped cleaner exit_code",
"1",
str(stopped[-1].get("exit_code")) if stopped else "-",
),
(
"Fixed storage discrepancy records",
"0",
str(len(rc_events(records, RC_FIXED))),
),
(
f"docker stop faster than {RS_STOP_LIMIT_S} s",
"yes",
yes(0 <= took < RS_STOP_LIMIT_S),
),
]
return report_reconcile(
rows,
passed="one-off reconcile stopped by SIGTERM: exit 1, nothing changed",
)
def docker_logs(name: str) -> str:
proc = subprocess.run(
["docker", "logs", name],
capture_output=True,
text=True,
check=False,
)
return proc.stdout + proc.stderr
# lb-upload-timeouts: сроки LB пути загрузки на заглушке (design change
# upload-memory, решение 7). Молчание заглушки: дольше timeout server
# прочих путей (10 с), но меньше срока пути загрузки (30 с) — и дольше его
@@ -4417,6 +4570,7 @@ def main() -> int:
stress = sub.add_parser("reconcile-stress")
stress.add_argument("--seconds", type=float, default=40)
stress.add_argument("--clients", type=int, default=4)
sub.add_parser("reconcile-signal")
lbto = sub.add_parser("lb-upload-timeouts")
lbto.add_argument(
"--config",
@@ -4518,6 +4672,8 @@ def main() -> int:
seconds=args.seconds,
clients=args.clients,
)
if args.cmd == "reconcile-signal":
return cmd_reconcile_signal()
if args.cmd == "lb-upload-timeouts":
return cmd_lb_upload_timeouts(args.config, args.image)
if args.cmd == "stop-at-start":