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
+176 -33
View File
@@ -119,7 +119,12 @@
--apply, через секунду после «Started cleaner» docker stop;
interrupted_by stop, «Stopped cleaner» с exit_code 1, остановка
быстрее stop_grace_period 10 с; S3 размораживается в finally;
код 1 при расхождении
код 1 при расхождении. --pace (change track2-reconcile-cost):
вместо pause s3 — объекты пробы мимо API (botocore в одноразовом
контейнере api его ключами), reconcile --max-objects-per-second
1, docker stop через 2 с после «Started cleaner» во время паузы
предела скорости — остановка не дольше секунды; объекты
удаляются в finally
s3-idle [--rounds 3] [--downloads 10] [--puts 12] [--size-mib 4]
[--pause-ms 0.5] только стенд с LB: спеки object-storage
«Вызов после простоя» и attachments «Загрузка после простоя
@@ -3644,15 +3649,81 @@ RS_START_TIMEOUT_S = 30
RS_AFTER_START_S = 1.0
# stop_grace_period уборщика в docker-compose.yml: дольше — был бы SIGKILL
RS_STOP_LIMIT_S = 10
# режим --pace (design change track2-reconcile-cost, решение 14): пауза
# предела скорости вместо замороженного S3. Объекты под префиксом вложений
# с ключом, которого API не пишет (чужие для сверки): при пределе 1 объект/с
# проход после страницы списка ждёт столько секунд, сколько ключей
RS_PACE_OBJECTS = 8
RS_PACE_RATE = "1"
RS_PACE_AFTER_START_S = 2.0
# остановка во время паузы — не позже секунды после сигнала
RS_PACE_STOP_LIMIT_S = 1.0
# объекты пробы — botocore в одноразовом контейнере сервиса api его
# ключами из окружения (как put-object hook стенда отказов); в argv и
# вывод ключи не попадают
RS_PACE_OBJECTS_PY = r"""
import os, sys
import botocore.session
from botocore.config import Config
s3 = botocore.session.get_session().create_client(
"s3",
endpoint_url=f"http://{os.environ['S3__HOST']}:{os.environ['S3__PORT']}",
region_name="us-east-1",
aws_access_key_id=os.environ["S3__ACCESS_KEY_ID"],
aws_secret_access_key=os.environ["S3__SECRET_ACCESS_KEY"],
config=Config(s3={"addressing_style": "path"}),
)
bucket = os.environ["S3__BUCKET"]
prefix = os.environ["DATABASE__NAME"] + "/attachments/pace-signal-"
for i in range(int(sys.argv[2])):
key = f"{prefix}{i}"
if sys.argv[1] == "put":
s3.put_object(Bucket=bucket, Key=key, Body=b"pace", ContentType="image/png")
else:
s3.delete_object(Bucket=bucket, Key=key)
print(f"{sys.argv[1]} {sys.argv[2]} objects")
"""
def cmd_reconcile_signal() -> int:
def rfc3339_ns(text: str) -> int:
"""`2026-10-23T01:33:32.338748123Z` (Docker) → наносекунды эпохи;
без `fromisoformat`: Python 3.9 не принимает `Z` и наносекунды."""
base, _, rest = text.strip().partition(".")
digits = "".join(ch for ch in rest if ch.isdigit())
moment = datetime.strptime(base.rstrip("Z"), "%Y-%m-%dT%H:%M:%S")
seconds = int(moment.replace(tzinfo=UTC).timestamp())
return seconds * 10**9 + int((digits + "0" * 9)[:9])
def rs_pace_objects(action: str) -> None:
"""`put` или `delete` объектов пробы режима `--pace`."""
compose(
"run",
"--rm",
"--no-deps",
"-T",
"--entrypoint",
"python",
"api",
"-",
action,
str(RS_PACE_OBJECTS),
stdin=RS_PACE_OBJECTS_PY,
)
def cmd_reconcile_signal(*, pace: bool = False) -> 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 при расхождении."""
`pace` — вместо замороженного S3 пауза предела скорости: объекты пробы,
`reconcile --max-objects-per-second 1` (dry-run), `docker stop` через
2 с после «Started cleaner», остановка не дольше секунды; объекты
удаляются в `finally`. Таблица и записи процесса без секретов; код 1
при расхождении."""
try:
config = json.loads(compose("config", "--format", "json"))
except (RuntimeError, ValueError) as e:
@@ -3661,8 +3732,8 @@ def cmd_reconcile_signal() -> int:
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}",
"reconcile-signal pauses S3 or adds probe objects: run it on a "
f"temporary stand (COMPOSE_PROJECT_NAME), not {RS_WORKING_PROJECT}",
)
return 2
services = config.get("services", {})
@@ -3676,21 +3747,23 @@ def cmd_reconcile_signal() -> int:
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
started = False
took = -1.0
after_signal = -1.0
exit_code = ""
logs = ""
compose("pause", "s3")
print(f"{project}: s3 paused")
if pace:
rs_pace_objects("put")
print(f"{project}: {RS_PACE_OBJECTS} probe objects put")
args = ["reconcile", "--max-objects-per-second", RS_PACE_RATE]
after_start, limit = RS_PACE_AFTER_START_S, RS_PACE_STOP_LIMIT_S
waiting = "the rate limit pause"
else:
compose("pause", "s3")
print(f"{project}: s3 paused")
args = ["reconcile", "--apply"]
after_start, limit = RS_AFTER_START_S, float(RS_STOP_LIMIT_S)
waiting = "paused S3"
try:
compose(
"run",
"-d",
"--no-deps",
"--name",
name,
"cleaner",
"reconcile",
"--apply",
)
compose("run", "-d", "--no-deps", "--name", name, "cleaner", *args)
deadline = time.monotonic() + RS_START_TIMEOUT_S
while time.monotonic() < deadline:
logs = docker_logs(name)
@@ -3699,28 +3772,68 @@ def cmd_reconcile_signal() -> int:
break
time.sleep(0.2)
if started:
time.sleep(RS_AFTER_START_S)
print("docker stop while reconcile waits for paused S3")
time.sleep(after_start)
print(f"docker stop while reconcile waits for {waiting}")
# момент сигнала — событие kill Docker (часы ВМ, как FinishedAt):
# время docker stop включает ещё разбор контейнера демоном
events = subprocess.Popen(
[
"docker",
"events",
"--filter",
f"container={name}",
"--filter",
"event=kill",
"--format",
"{{.TimeNano}}",
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
time.sleep(0.3)
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()
time.sleep(0.3)
events.terminate()
kill_lines = (events.communicate()[0] or "").split()
exit_code, finished_at = (
subprocess.run(
[
"docker",
"inspect",
"-f",
"{{.State.ExitCode}}|{{.State.FinishedAt}}",
name,
],
capture_output=True,
text=True,
check=False,
).stdout.strip()
+ "|"
).split("|")[:2]
if kill_lines and finished_at:
after_signal = (
rfc3339_ns(finished_at) - int(kill_lines[0])
) / 1e9
logs = docker_logs(name)
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
compose("unpause", "s3")
print(f"{project}: s3 unpaused")
if pace:
rs_pace_objects("delete")
print(f"{project}: probe objects deleted")
else:
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 += ("reconcile_max_objects_per_second", "listed_objects")
shown += ("storage_objects", "max_objects_per_second")
shown += ("duration_ms", "interrupted_by", "exit_code", "timestamp")
print("== records of the one-off reconcile")
for record in records:
@@ -3734,7 +3847,11 @@ def cmd_reconcile_signal() -> int:
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 '-'}")
print(
f"docker stop took {took:.1f} s, container exited "
f"{after_signal:.2f} s after the kill event, exit code "
f"{exit_code or '-'}",
)
rows = [
("Started cleaner (mode reconcile)", "yes", yes(started)),
("exit code", "1", exit_code),
@@ -3754,14 +3871,39 @@ def cmd_reconcile_signal() -> int:
str(len(rc_events(records, RC_FIXED))),
),
(
f"docker stop faster than {RS_STOP_LIMIT_S} s",
f"exited within {limit:g} s after the signal"
if pace
else f"docker stop faster than {limit:g} s",
"yes",
yes(0 <= took < RS_STOP_LIMIT_S),
yes(0 <= after_signal <= limit if pace else 0 <= took < limit),
),
]
if pace:
rate = next(
(
item.get("reconcile_max_objects_per_second")
for item in records
if item.get("event") == "Started cleaner"
),
None,
)
rows.insert(
1,
(
"Started cleaner reconcile_max_objects_per_second",
RS_PACE_RATE,
"-" if rate is None else f"{float(rate):g}",
),
)
return report_reconcile(
rows,
passed="one-off reconcile stopped by SIGTERM: exit 1, nothing changed",
passed=(
"one-off reconcile stopped by SIGTERM during the rate limit "
"pause: exit 1 within a second"
if pace
else "one-off reconcile stopped by SIGTERM: exit 1, nothing "
"changed"
),
)
@@ -4999,7 +5141,8 @@ 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")
signal_cmd = sub.add_parser("reconcile-signal")
signal_cmd.add_argument("--pace", action="store_true")
idle_s3 = sub.add_parser("s3-idle")
idle_s3.add_argument("--rounds", type=int, default=3)
idle_s3.add_argument("--downloads", type=int, default=10)
@@ -5113,7 +5256,7 @@ def main() -> int:
clients=args.clients,
)
if args.cmd == "reconcile-signal":
return cmd_reconcile_signal()
return cmd_reconcile_signal(pace=args.pace)
if args.cmd == "s3-idle":
return cmd_s3_idle(
port,