Tie the track tooling to keys, sets and a clean series

reconcile-inject.sh wrote an orphan under a key whose uuid differed
from the id it printed, so the demo could only compare counts; it now
uses one uuid for both, and the dry-run check compares the found and
the injected sets per class. The heal step returns the original bytes
under one quarantined key and random bytes of the same length under
another, and checks that only the first leaves the quarantine. The
load phase sums rechecked over its passes, and a new step stops a pass
hanging on a paused S3 with docker stop and checks exit code 143 within
seconds and a free lock afterwards.

reconcile_track.py cost clears the run files of the previous series and
measures 1k, 10k, 30k and 100k with --deep everywhere. The scenarios
record date, commit and docker inspect of the replicas or of S3 at the
moment they are down. make load-evidence and make clean-clone-evidence
rerun the message load and the clean clone block with raw output, and
make upload-memory passes ARGS to reproduce the run directories.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-30 09:01:39 +03:00
co-authored by Claude Opus 5.5
parent 3de1dcdc84
commit f1ee385a1b
8 changed files with 241 additions and 34 deletions
+55
View File
@@ -0,0 +1,55 @@
#!/bin/sh
set -u
cd "$(dirname "$0")/.."
repo=$PWD
dir="${CLONE_DIR:-$(dirname "$repo")/mtusi2026lab4-clean}"
out="$repo/evidence/clean-clone.txt"
branch=$(git rev-parse --abbrev-ref HEAD)
project=$(basename "$dir")
[ -e "$dir" ] && { echo "$dir уже существует" >&2; exit 2; }
step() {
echo "\$ $*"
sh -c "$*" 2>&1 | sed "s#$dir#<clone>#g"
}
look() {
echo "\$ $* # наблюдение, не шаг инструкции"
sh -c "$*" 2>&1 | sed "s#$dir#<clone>#g"
}
{
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD) dir: $project (свой compose-проект и volumes)"
echo "# make clean-clone-evidence (scripts/clean-clone.sh): команды блока «Запуск из чистого clone» REPORT.md по очереди"
echo "# с сырым выводом; строки «наблюдение» — проверки между шагами"
echo "\$ git clone <repo> $project && cd $project && git checkout $branch"
git clone -q "$repo" "$dir" && cd "$dir" && git checkout -q "$branch" && git log -1 --format='HEAD %h %s'
look "docker volume ls -q --filter label=com.docker.compose.project=$project | wc -l | tr -d ' '"
step "make secrets"
if [ -n "${LB_HTTP_PORT:-}" ]; then
echo "\$ sed LB_HTTP_PORT=$LB_HTTP_PORT LB_STATS_PORT=${LB_STATS_PORT:-8404} .env # отступление: 8080 занят стендами других лаб"
sed -i.bak "s/^LB_HTTP_PORT=.*/LB_HTTP_PORT=$LB_HTTP_PORT/; s/^LB_STATS_PORT=.*/LB_STATS_PORT=${LB_STATS_PORT:-8404}/" .env && rm -f .env.bak
fi
look "git status --short --ignored secrets .env"
step "docker compose --env-file .env config --quiet && echo valid"
started=$(date +%s)
step "make up"
echo "make up: $(( $(date +%s) - started )) s"
look "docker compose ps -a --format '{{.Service}} {{.State}} {{.Status}} {{.Ports}}'"
look "docker compose logs --no-log-prefix migrate s3-init | grep -v '^\$' | tail -6"
look "curl -s \"http://\$(docker compose port lb 8404)/stats;csv\" | awk -F, '\$1 == \"api\" && \$2 != \"BACKEND\" {print \$2, \$18}' | grep -v MAINT"
step "make test"
step "make test-persistence ACTION_SCRIPT=scripts/restart.sh"
look "docker compose ps -a --format '{{.Service}} {{.State}} {{.RunningFor}} {{.Status}}'"
step "make test-failover ACTION_SCRIPT=scripts/stop-one.sh"
look "docker compose ps -a --format '{{.Service}} {{.Name}} {{.State}} {{.Status}}' api"
step "make restore"
step "make scenario SCENARIO=failover-upload"
step "make scenario SCENARIO=s3-outage"
step "make s3-check"
step "make reconcile"
step "make migrate"
look "docker volume ls --format '{{.Name}}' --filter label=com.docker.compose.project=$project"
step "make down"
look "docker volume ls --format '{{.Name}}' --filter label=com.docker.compose.project=$project"
step "make reset-data"
look "docker volume ls -q --filter label=com.docker.compose.project=$project | wc -l | tr -d ' '"
} > "$out"
cat "$out"
+30 -2
View File
@@ -23,6 +23,19 @@ def compose(*args, stdin=None):
return subprocess.run(cmd, cwd=ROOT, input=stdin, capture_output=True, text=True, check=False)
def containers(service):
ids = compose("ps", "-aq", service).stdout.split()
fields = ("hostname", "status", "exit_code", "started_at", "finished_at")
template = (
"{{.Config.Hostname}} {{.State.Status}} {{.State.ExitCode}}"
" {{.State.StartedAt}} {{.State.FinishedAt}}"
)
out = subprocess.run(
["docker", "inspect", "-f", template, *ids], capture_output=True, text=True, check=False
)
return [dict(zip(fields, line.split())) for line in out.stdout.splitlines()]
def upload(c, actor, chat, expected=201):
path = f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png"
schema = "Attachment" if expected == 201 else None
@@ -89,6 +102,10 @@ def failover_upload(c, args):
recovered = time.monotonic() - started
served = got["headers"].get("X-Instance-Id")
check(served != target, "download served by the stopped replica")
during = containers(args.service)
states = {item["hostname"]: item["status"] for item in during}
check(states.get(target) == "exited", f"target {target} is not exited: {states}")
check(states.get(served) == "running", f"neighbour {served} is not running: {states}")
digest = hashlib.sha256(got["bytes"]).hexdigest()
check(
digest == att["sha256"] == hashlib.sha256(FIXTURE).hexdigest(),
@@ -103,7 +120,9 @@ def failover_upload(c, args):
"sha256_equal": True,
"hook_seconds": round(hook_seconds, 3),
"download_ok_after_seconds": round(recovered, 3),
"replicas_at_download": during,
"restored": args.restore,
"replicas_after_restore": containers(args.service) if args.restore else None,
}
@@ -123,6 +142,7 @@ def s3_outage(c, args):
"text_message": timed(lambda: c.message(alice, chat, "S3 недоступен, текст работает")),
"health_ready": timed(lambda: c.call("GET", "/health/ready", [200, 503])),
}
stopped = containers(args.s3_service)
finally:
started = time.monotonic()
compose("up", "-d", "--wait", "--no-deps", "--no-recreate", args.s3_service)
@@ -132,6 +152,7 @@ def s3_outage(c, args):
expected = {"upload": 503, "download": 503, "text_message": 201}
return {
"scenario": "s3-outage",
"s3_container_during_outage": stopped,
"during_outage": during,
"expected": expected,
"as_expected": all(during[k]["status"] == v for k, v in expected.items()),
@@ -215,10 +236,17 @@ def main():
"s3-outage": s3_outage,
"abort-upload": abort_upload,
}[args.scenario]
commit = subprocess.run(
["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, check=False
)
stamp = {
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"commit": commit.stdout.decode().strip(),
}
try:
report = {"ok": True, **run(c, args)}
report = {"ok": True, **stamp, **run(c, args)}
except Failure as exc:
report = {"scenario": args.scenario, "ok": False, "error": str(exc)}
report = {"scenario": args.scenario, "ok": False, **stamp, "error": str(exc)}
text = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
Path(args.output).write_text(text + "\n")
+59
View File
@@ -0,0 +1,59 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
runs="${RUNS:-3}"
pause="${PAUSE:-15}"
project=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "$(docker compose ps -q lb)")
network="${project}_edge"
image=$(sed -n 's/^FROM \(python:[^ ]*\) AS runtime$/\1/p' Dockerfile)
name="$project-load-client"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p evidence/load
client() {
docker run --rm --name "$name" --network "$network" --cpus 2 --memory 512m \
--sysctl net.ipv4.tcp_tw_reuse=1 -v "$PWD/tests:/w/tests:ro" -v "$PWD/contracts:/w/contracts:ro" \
-v "$PWD/lab.json:/w/lab.json:ro" -v "$PWD/evidence/load:/out" "$image" python /w/tests/load.py "$@"
}
handled() {
docker compose logs --no-log-prefix --since "$1" api | python3 -c 'import collections, json, sys
seen = collections.Counter()
for line in sys.stdin:
if line.startswith("{"):
event = json.loads(line)
if event.get("event") == "request.handled":
seen[(event["status"], event["method"], event["route"])] += 1
for (status, method, route), count in sorted(seen.items()):
print(status, method, route, count)'
}
{
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD) network: $network"
echo "# make load-evidence (scripts/load-evidence.sh): закрытый контур tests/load.py, 64 потока, 8 с, все записи"
echo "# прогона в один новый чат, $runs повтора с паузой $pause с; клиент — одноразовый контейнер в сети <проект>_edge"
echo "# стенда (2 CPU, 512 MiB, базовый образ API по digest, tests/, contracts/ и lab.json только для чтения,"
echo "# tcp_tw_reuse=1), адрес http://lb:8080. На 4-й секунде — docker stats; после прогона — request.handled реплик."
echo "\$ docker ps --format '{{.Names}}' | grep -v '^$project-' # чужие контейнеры на VM во время серии"
docker ps --format '{{.Names}}' | grep -v "^$project-" || true
echo "\$ client() { docker run --rm --name $name --network $network --cpus 2 --memory 512m --sysctl net.ipv4.tcp_tw_reuse=1 -v \"\$PWD/tests:/w/tests:ro\" -v \"\$PWD/contracts:/w/contracts:ro\" -v \"\$PWD/lab.json:/w/lab.json:ro\" -v \"\$PWD/evidence/load:/out\" $image python /w/tests/load.py \"\$@\"; }"
run=1
while [ "$run" -le "$runs" ]; do
since=$(date -u +%FT%TZ)
echo "\$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run$run.json"
client --base-url http://lb:8080 --duration 8 --concurrency 64 --output "/out/run$run.json" > "$work/out" 2>&1 &
pid=$!
sleep 4
stats=$(docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}}' $(docker compose ps -q) "$name" | sed "s/^$project-//" | sort)
if wait "$pid"; then code=0; else code=$?; fi
echo "exit $code"
cat "$work/out"
echo "\$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память"
echo "$stats"
echo "\$ docker compose logs --since $since api | request.handled: статус метод маршрут число"
handled "$since"
[ "$run" -lt "$runs" ] && sleep "$pause"
run=$((run + 1))
done
echo "\$ docker compose exec -T postgres psql -c 'SELECT count(*) FROM messages'"
docker compose exec -T postgres psql -U messenger -d messenger -qAt -c 'SELECT count(*) FROM messages'
} > evidence/load.txt
cat evidence/load.txt
+1 -1
View File
@@ -16,7 +16,7 @@ pending() {
(SELECT gen_random_uuid() AS id FROM generate_series(1, $count)) g
RETURNING id, object_key"
}
fresh() { sql "SELECT gen_random_uuid(), '$prefix' || gen_random_uuid() FROM generate_series(1, $count)"; }
fresh() { sql "SELECT g, '$prefix' || g FROM (SELECT gen_random_uuid() AS g FROM generate_series(1, $count)) s"; }
put_random='printf "%s\n" "$ROWS" | while read -r id key size; do [ -n "$key" ] || continue; head -c "${size:-2048}" /dev/urandom | rc pipe "root/$S3_BUCKET/$key" >/dev/null; echo "$id $key"; done'
case "$kind" in
orphan) rows=$(fresh); s3 "$rows" "$put_random" | sed "s/^/orphan /" ;;
+72 -17
View File
@@ -174,9 +174,11 @@ def faults(c, check, pre):
dry = reconcile("--dry-run", "--deep", *FLAGS)
save("dry-run.json", dry)
after_dry = oracle("--grace", str(GRACE), "--deep")
named = {k: sorted(s.rsplit("/", 1)[-1] for s in dry["samples"].get(k, [])) for k in injected}
check(
"dry-run находит каждый внедрённый класс",
pick(dry["found"], expected) == expected,
"dry-run находит каждый внедрённый класс, и найдено ровно внедрённое",
pick(dry["found"], expected) == expected
and named == {name: sorted(ids) for name, ids in injected.items()},
expected=expected,
found=dry["found"],
)
@@ -241,23 +243,30 @@ def faults(c, check, pre):
meta["status"] == 200 and blocked["status"] == 404 and intact["bytes"] == FIXTURE,
)
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
compose(
"run",
"--rm",
"--no-deps",
"-T",
"s3-cli",
"pipe",
f"root/{bucket}/attachments/{linked[0]}",
stdin=FIXTURE,
)
for attachment, data in ((linked[0], FIXTURE), (linked[1], os.urandom(len(FIXTURE)))):
compose(
"run",
"--rm",
"--no-deps",
"-T",
"s3-cli",
"pipe",
f"root/{bucket}/attachments/{attachment}",
stdin=data,
)
healed = reconcile("--apply", *FLAGS)
save("healed.json", healed)
restored = c.call("GET", f"/api/v1/attachments/{linked[0]}/content", 200, actor=bob)
foreign = c.call("GET", f"/api/v1/attachments/{linked[1]}/content", 404, actor=bob)
check(
"восстановленный объект выходит из карантина",
healed["fixed"]["healed"] == 1 and restored["bytes"] == FIXTURE,
"вернули те же байты — карантин снят; другие байты той же длины — остался",
healed["fixed"]["healed"] == 1
and healed["samples"].get("healed") == [linked[0]]
and linked[1] in healed["samples"].get("quarantined", [])
and restored["bytes"] == FIXTURE
and foreign["status"] == 404,
fixed=healed["fixed"],
s3_get=healed["cost"]["requests"]["s3_get"],
)
return {"injected": injected, "targets": targets, "linked": linked}
@@ -294,6 +303,44 @@ def single(check):
)
def interrupt(check):
name = f"lab4-reconcile-sigterm-{os.getpid()}"
compose("pause", "s3")
try:
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "-T", "--name", name, "reconciler"]
runner = subprocess.Popen(
[*cmd, "--apply", *FLAGS],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
time.sleep(4)
state = must(["docker", "inspect", "-f", "{{.State.Status}} {{.HostConfig.Init}}", name])
started = time.monotonic()
must(["docker", "stop", name])
stopped = round(time.monotonic() - started, 2)
code = runner.wait(timeout=60)
finally:
compose("unpause", "s3")
compose("up", "-d", "--wait", "--no-deps", "s3")
after = reconcile("--dry-run", *FLAGS)
status, init = state.split()
report = {
"s3": "paused",
"state_before_stop": status,
"init": init,
"stop_seconds": stopped,
"exit_code": code,
"next_pass_skipped": after["skipped"],
}
save("sigterm.json", report)
check(
"SIGTERM: идущий проход останавливается за секунды, блокировка освобождена",
status == "running" and code == 143 and stopped < 5 and not after["skipped"],
**report,
)
def outage(check):
before = oracle("--grace", str(GRACE))
compose("stop", "s3")
@@ -388,6 +435,10 @@ def under_load(c, check, base, seconds, threads):
for status, _ in results:
statuses[str(status)] = statuses.get(str(status), 0) + 1
fixed = {name: sum(r["fixed"][name] for r in runs) for name in FIXABLE}
rechecked = {}
for r in runs:
for name, count in r["rechecked"].items():
rechecked[name] = rechecked.get(name, 0) + count
seen = {name: sum(r["found"][name] for r in runs) for name in ("orphan_fresh", "pending_fresh")}
summary = {
"seconds": seconds,
@@ -399,6 +450,7 @@ def under_load(c, check, base, seconds, threads):
"run_seconds": [r["cost"]["seconds"] for r in runs],
"fixed_total": fixed,
"fresh_seen_total": seen,
"rechecked_total": rechecked,
"errors": sum(r["errors"] for r in runs),
"skipped": sum(1 for r in runs if r["skipped"]),
"injected_before_load": {"orphan": len(orphans), "pending_stale": len(intents)},
@@ -439,6 +491,7 @@ def demo(args):
result = {"started_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "commit": head()}
result["faults"] = faults(c, check, pre)
single(check)
interrupt(check)
outage(check)
under_load(c, check, args.base_url, args.load_seconds, args.load_threads)
result.update(seconds=round(time.monotonic() - started, 1), checks=check.items, ok=check.ok)
@@ -642,7 +695,9 @@ def table(rows):
def cost(args):
out = OUT / "cost"
out.mkdir(parents=True, exist_ok=True)
(out / "disturbed").mkdir(parents=True, exist_ok=True)
for stale in [*out.glob("n*-*.json"), *(out / "disturbed").glob("*.json")]:
stale.unlink()
rows = int(psql("SELECT count(*) FROM attachments"))
if rows > args.sizes[0]:
raise SystemExit(f"на стенде уже {rows} вложений: make reset-data && make up && make test")
@@ -701,9 +756,9 @@ def main():
d.add_argument("--load-seconds", type=int, default=75)
d.add_argument("--load-threads", type=int, default=3)
k = sub.add_parser("cost", help="cost of a pass for N objects, repeated")
k.add_argument("--sizes", type=int, nargs="+", default=[1000, 10000, 30000])
k.add_argument("--sizes", type=int, nargs="+", default=[1000, 10000, 30000, 100000])
k.add_argument("--repeats", type=int, default=3)
k.add_argument("--deep-max", type=int, default=30000)
k.add_argument("--deep-max", type=int, default=100000)
k.add_argument("--page-compare", type=int, default=10000)
k.add_argument("--settle", type=float, default=10)
k.add_argument("--s3-memory", default="3g")