Finalize lab 3 report and evidence provenance

Tie the grade 5 claim to the final SQLAlchemy revalidation and measured scaling results. Clarify clean-clone setup, failure timings, historical evidence, and operational constraints; record report-stage checks and evidence audits.
This commit is contained in:
Artyom
2026-11-06 01:29:44 +03:00
parent f591fa64e5
commit 4513d90e48
6 changed files with 422 additions and 35 deletions
+24 -4
View File
@@ -1,4 +1,4 @@
date: 2026-11-05T22:01:31.561495+00:00 commit: 3fb741e6a84d2b187a0266488b018f0b684dcce5
date: 2026-11-05T22:28:57.204523+00:00 commit: f591fa64e525679a31c9db7f942d36c789e1a12f (report documentation worktree)
# Доказательства
@@ -8,7 +8,27 @@ date: 2026-11-05T22:01:31.561495+00:00 commit: 3fb741e6a84d2b187a0266488b018f0b6
В текстовом выводе удалены пробелы на концах строк Docker/psql; локальный путь заменён на `<repo>`.
В grade4-student-tests.txt замаскирован синтетический неверный Bearer из имени параметризованного теста.
## Уровень «3» после SQLAlchemy — 2026-11-05
## Актуальный итог и финализация отчёта
Заявлена «5», трек 1 «Цена масштабирования». Автор — Костылев Артём, БПИ2303.
Приоритет имеют итоговые проверки после оптимизации; таблицы grade3/grade4 ниже
сохраняют историю отдельных этапов **до кэширования SQL**, а не новые прогоны HEAD.
| Что проверяется | Актуальный источник | Код |
| --- | --- | --- |
| Уровни «3»/«4», публичные проверки, отказы зависимостей | [Команды](track1-sqlalchemy/revalidation/commands.txt), [сценарии](track1-sqlalchemy/revalidation/) | `3fb741e`, API идентичен `57744c5` |
| Каждая реплика: времена, ошибки, потери, реальные контейнеры | [a855a190991a](track1-sqlalchemy/revalidation/failover-each/a855a190991a/result.json), [d4dfe6128c9d](track1-sqlalchemy/revalidation/failover-each/d4dfe6128c9d/result.json); `action.txt` рядом | `3fb741e` |
| Rolling под нагрузкой, один migrate, история | [Результат](track1-sqlalchemy/revalidation/rolling/result.json), [действие](track1-sqlalchemy/revalidation/rolling/action.txt) | `5c8f605` → API `57744c5`, обвязка `3fb741e` |
| 135 измерений, методика и подтверждённое улучшение | [Методика](track1-sqlalchemy/README.md), [аудит](track1-sqlalchemy/audit.txt), [сводка](track1-sqlalchemy/plots/capacity.md) | baseline `5c8f605`, after `57744c5` |
| Исправление сохранения диагностических журналов | [Повторные 290 tests и smoke](track1-sqlalchemy/diagnostics/setup-log-fix-checks.txt) | `55b99a2`; API не менялся |
| Проверки этапа report | [check/validate/lint/student-test/OpenSpec](report-checks.txt), [ссылки, метрики и состав изменений](report-audit.txt) | `f591fa64e525679a31c9db7f942d36c789e1a12f` + только документы |
На этапе report нагрузка заново не снималась: код приложения, миграции, образы и
конфигурация стенда не изменялись. Ссылки и численные выводы сверены с сохранённым
сырьём; собственные тесты выполнены заново. Журналы содержат фактические коды выхода,
включая неуспехи. Публикаций и отправок Telegram на этом этапе нет.
## Уровень «3» после SQLAlchemy, до оптимизации — 2026-11-05
Код всех итоговых прогонов: **`0a1f48bd73e5780c732356880c23fdb476bcff98`**.
Compose-проект `mtusi2026lab3-grade3-final-20261105`, `LB_HTTP_PORT=18083`, `LB_STATS_PORT=23083`,
@@ -54,10 +74,10 @@ volumes сохранены. До конца grade4 код приложения
`clean-clone.txt`, `hooks.txt`, `failover-fe75c6c37e5a.txt`, `failover-ff81f93e8b0d.txt`
и `rolling-from-8d28d45/` — история до SQLAlchemy. Прежние версии перезаписанных доказательств
доступны через `git show ef0b9a3:evidence/<имя>`. Новые измерения трека приведены ниже;
доступны через `git show 72a1e57:evidence/<имя>`. Новые измерения трека приведены ниже;
исходный SQLAlchemy change завершён и архивирован 2026-11-06.
## Уровень «4» после SQLAlchemy — 2026-11-05
## Уровень «4» после SQLAlchemy, до оптимизации — 2026-11-05
Код прогонов: **`252e3e3ffeea5004cfd9dc342e686af1417a77a2`**.
Проект `mtusi2026lab3-grade4-20261105`, порты `18083/23083`, две реплики по 1 CPU/512 MiB,
+161
View File
@@ -0,0 +1,161 @@
date: 2026-11-05T22:28:24.183630+00:00 commit: f591fa64e525679a31c9db7f942d36c789e1a12f
worktree: report documentation changes only
$ python3 <<'PY'
import collections
import csv
import json
import re
import subprocess
from pathlib import Path
from statistics import median
root = Path.cwd()
track = root / "evidence/track1-sqlalchemy"
report = (root / "REPORT.md").read_text()
links = 0
for name in ("REPORT.md", "AGENTS.md", "evidence/README.md"):
path = root / name
for target in re.findall(r"\]\(([^)]+)\)", path.read_text()):
if "://" in target or target.startswith("#"):
continue
assert (path.parent / target.split("#")[0]).exists(), (name, target)
links += 1
print("PASS: local Markdown links exist:", links)
for candidate in re.findall(r"`(evidence/[^`\s]+)`", report):
if not any(char in candidate for char in "{}<>"):
assert list(root.glob(candidate)), candidate
print("PASS: explicit evidence paths and globs in REPORT exist")
all_rows = []
series_rows = {}
expected_sizes = {"series-a": 54, "series-b": 36, "compare": 18, "control-pool": 15, "control-cpus": 12}
for name, size in expected_sizes.items():
folder = track / name
rows = list(csv.DictReader(line for line in (folder / "summary.csv").read_text().splitlines() if not line.startswith("#")))
assert len(rows) == size
groups = collections.defaultdict(list)
for row in rows:
groups[row["variant"], row["config"], row["rate"]].append(row)
raw = folder / row["raw_dir"]
metrics = json.loads((raw / "k6/summary.json").read_text())["metrics"]
count = metrics["http_reqs{scenario:measure}"]["values"]["count"]
failed = metrics["http_req_failed{scenario:measure}"]["values"]["rate"]
dropped = metrics.get("dropped_iterations{scenario:measure}", {}).get("values", {}).get("count", 0)
p95 = metrics["http_req_duration{scenario:measure}"]["values"]["p(95)"]
assert int(row["requests"]) == count
assert abs(float(row["ok_rps"]) - count * (1 - failed) / 30) <= 0.006
assert abs(float(row["failed_ratio"]) - failed) <= 0.000006
assert abs(float(row["p95_ms"]) - p95) <= 0.006
assert int(row["dropped_iterations"]) == dropped
assert row["disturbed"] == "False" and row["k6_exit"] == "0"
metadata = json.loads((raw / "metadata.json").read_text())
apis = [item for item in metadata["containers"] if "-api-" in item["name"]]
assert len(apis) == int(row["replicas"])
assert {item["NanoCpus"] for item in apis} == {round(float(row["cpus"]) * 1e9)}
assert {item["Memory"] for item in apis} == {int(row["memory_mb"]) * 2**20}
assert {item["CpusetCpus"] for item in apis} == {row["api_cpuset"]}
assert all(len(items) == 3 and {item["repeat"] for item in items} == {"1", "2", "3"} for items in groups.values())
series_rows[name] = rows
all_rows.extend(rows)
print("PASS:", name, size, "samples; raw k6 counts/latency/errors, 3 repeats, actual resources")
assert len(all_rows) == 135
assert sum(int(row["requests"]) for row in all_rows) == 8271783
assert len(list((track / "plots").glob("*.png"))) == 12
print("PASS: 135 samples, 8271783 requests, 12 PNG files")
comparison = {}
for variant in ("before", "after"):
for rate in (2400, 3600, 5400):
rows = [row for row in series_rows["compare"] if row["variant"] == variant and int(row["rate"]) == rate]
values = {field: median(float(row[field]) for row in rows) for field in ("ok_rps", "p95_ms", "p99_ms", "cpu_api")}
comparison[variant, rate] = values
line = next(line for line in report.splitlines() if line.startswith(f"| {rate} | {variant} |"))
for field in ("ok_rps", "p95_ms", "p99_ms"):
assert f"{values[field]:.2f}" in line, (variant, rate, field)
print("PASS: REPORT comparison", variant, rate, values)
for rate, field in ((2400, "p95_ms"), (5400, "ok_rps")):
before = [float(row[field]) for row in series_rows["compare"] if row["variant"] == "before" and int(row["rate"]) == rate]
after = [float(row[field]) for row in series_rows["compare"] if row["variant"] == "after" and int(row["rate"]) == rate]
assert max(after) < min(before) if field == "p95_ms" else min(after) > max(before)
gain = (comparison["after", 5400]["ok_rps"] / comparison["before", 5400]["ok_rps"] - 1) * 100
cpu = (1 - comparison["after", 2400]["cpu_api"] / comparison["before", 2400]["cpu_api"]) * 100
assert round(gain, 1) == 8.7 and round(cpu, 1) == 29.3
print("PASS: non-overlapping ranges; throughput +8.7%, API CPU -29.3%")
for name in ("series-a", "series-b"):
groups = collections.defaultdict(list)
for row in series_rows[name]:
groups[row["config"], row["rate"]].append(float(row["ok_rps"]))
for config in sorted({key[0] for key in groups}):
peak = max(median(values) for (cfg, rate), values in groups.items() if cfg == config)
assert f"{peak:.2f}" in report, (name, config, peak)
print("PASS: REPORT peak", name, config, f"{peak:.2f}")
validation = track / "revalidation"
expected = {"a855a190991a": (1.018, 0.058, 14.480, 661), "d4dfe6128c9d": (1.145, 0.096, 16.127, 661)}
for label, values in expected.items():
folder = validation / "failover-each" / label
data = json.loads((folder / "result.json").read_text())
assert data["pass"] and all(data["checks"].values())
assert (data["detection_seconds"], data["probe"]["first_success_s"], data["rejoin_seconds"], data["history"]["confirmed"]) == values
assert data["history"]["confirmed"] == data["history"]["stored"] and data["history"]["exact_match"] and data["history"]["unique"]
assert data["k6"]["failed_ratio"] == data["probe"]["failed_attempts"] == data["k6"]["dropped_iterations"] == 0
assert label in (folder / "action.txt").read_text() and "Exited (0)" in (folder / "action.txt").read_text()
print("PASS: REPORT failure", label, values, "zero errors/losses/duplicates, stopped container recorded")
rolling = json.loads((validation / "rolling/result.json").read_text())
assert rolling["pass"] and all(rolling["checks"].values())
assert rolling["history"]["confirmed"] == rolling["history"]["stored"] == 938
assert rolling["lb_up_min"] == 2 and rolling["probe"]["first_success_s"] == 0.037
print("PASS: rolling, 938 messages preserved, minimum 2 UP")
for scenario, expected_range in {"sigterm": (0.899, 1.326), "kill": (0.273, 0.795), "pause": (2.783, 3.281), "postgres": (1.201, 1.255)}.items():
data = [json.loads(path.read_text()) for path in sorted(validation.glob(f"detection/run*/{scenario}.json"))]
assert len(data) == 3 and all(item["pass"] for item in data)
actual = [item["detection_seconds"] for item in data]
assert (min(actual), max(actual)) == expected_range
print("PASS: REPORT detection", scenario, expected_range)
paths = ["src", "alembic", "infra", "Dockerfile", "compose.yaml", "pyproject.toml", "uv.lock", "student-tests"]
subprocess.run(["git", "diff", "--exit-code", "3fb741e", "--", *paths], check=True)
subprocess.run(["git", "diff", "--exit-code", "upstream/main", "--", "contracts", "tests", "README.md", "COURSE.md"], check=True)
subprocess.run(["git", "diff", "--exit-code", "f591fa6", "--", ".pipeline"], check=True)
print("PASS: application/migrations/stack/tests unchanged since revalidation; normative files unchanged from upstream")
subprocess.run(["git", "diff", "--check"], check=True)
print("PASS: git diff --check")
print("Context7 checked: /sqlalchemy/sqlalchemy/rel_2_0_45 lambda_stmt(enable_tracking=False); /sqlalchemy/alembic/rel_1_16_5 async run_sync/upgrade head")
PY
PASS: local Markdown links exist: 40
PASS: explicit evidence paths and globs in REPORT exist
PASS: series-a 54 samples; raw k6 counts/latency/errors, 3 repeats, actual resources
PASS: series-b 36 samples; raw k6 counts/latency/errors, 3 repeats, actual resources
PASS: compare 18 samples; raw k6 counts/latency/errors, 3 repeats, actual resources
PASS: control-pool 15 samples; raw k6 counts/latency/errors, 3 repeats, actual resources
PASS: control-cpus 12 samples; raw k6 counts/latency/errors, 3 repeats, actual resources
PASS: 135 samples, 8271783 requests, 12 PNG files
PASS: REPORT comparison before 2400 {'ok_rps': 2400.03, 'p95_ms': 14.28, 'p99_ms': 63.16, 'cpu_api': 573.24}
PASS: REPORT comparison before 3600 {'ok_rps': 3562.0, 'p95_ms': 223.99, 'p99_ms': 283.23, 'cpu_api': 774.41}
PASS: REPORT comparison before 5400 {'ok_rps': 3629.17, 'p95_ms': 373.74, 'p99_ms': 480.28, 'cpu_api': 775.03}
PASS: REPORT comparison after 2400 {'ok_rps': 2400.03, 'p95_ms': 4.63, 'p99_ms': 14.2, 'cpu_api': 405.23}
PASS: REPORT comparison after 3600 {'ok_rps': 3587.4, 'p95_ms': 101.01, 'p99_ms': 156.31, 'cpu_api': 593.03}
PASS: REPORT comparison after 5400 {'ok_rps': 3945.63, 'p95_ms': 317.43, 'p99_ms': 415.68, 'cpu_api': 614.42}
PASS: non-overlapping ranges; throughput +8.7%, API CPU -29.3%
PASS: REPORT peak series-a 1x4 2687.13
PASS: REPORT peak series-a 2x2 2531.80
PASS: REPORT peak series-a 4x1 2421.57
PASS: REPORT peak series-b 1x1 750.93
PASS: REPORT peak series-b 2x1 1306.80
PASS: REPORT peak series-b 8x1 3420.37
PASS: REPORT failure a855a190991a (1.018, 0.058, 14.48, 661) zero errors/losses/duplicates, stopped container recorded
PASS: REPORT failure d4dfe6128c9d (1.145, 0.096, 16.127, 661) zero errors/losses/duplicates, stopped container recorded
PASS: rolling, 938 messages preserved, minimum 2 UP
PASS: REPORT detection sigterm (0.899, 1.326)
PASS: REPORT detection kill (0.273, 0.795)
PASS: REPORT detection pause (2.783, 3.281)
PASS: REPORT detection postgres (1.201, 1.255)
PASS: application/migrations/stack/tests unchanged since revalidation; normative files unchanged from upstream
PASS: git diff --check
Context7 checked: /sqlalchemy/sqlalchemy/rel_2_0_45 lambda_stmt(enable_tracking=False); /sqlalchemy/alembic/rel_1_16_5 async run_sync/upgrade head
exit: 0
Final index audit: 40 local Markdown targets exist in git ls-files; exactly six report/documentation files staged.
git diff --cached --check: exit 0
+103
View File
@@ -0,0 +1,103 @@
date: 2026-11-05T22:25:56.847995+00:00 commit: f591fa64e525679a31c9db7f942d36c789e1a12f
worktree: report documentation changes only; application and tests unchanged
$ make check
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
exit: 0
duration_seconds: 0.100
$ make validate
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
exit: 0
duration_seconds: 0.250
$ make lint
.venv/bin/ruff check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
All checks passed!
.venv/bin/ruff format --check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
109 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
exit: 0
duration_seconds: 0.113
$ make student-test
.venv/bin/pytest
============================= test session starts ==============================
platform darwin -- Python 3.14.5, pytest-9.1.1, pluggy-1.6.0
rootdir: <repo>
configfile: pyproject.toml
testpaths: student-tests
plugins: asyncio-1.4.0, anyio-4.15.1
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
collected 302 items / 12 deselected / 290 selected
student-tests/api/test_access.py ......... [ 3%]
student-tests/api/test_bounded_contexts.py .................. [ 9%]
student-tests/api/test_cache.py ...... [ 11%]
student-tests/api/test_concurrency.py .... [ 12%]
student-tests/api/test_consistency.py ........ [ 15%]
student-tests/api/test_drain.py .. [ 16%]
student-tests/api/test_events.py ...... [ 18%]
student-tests/api/test_idempotency.py ............... [ 23%]
student-tests/api/test_instance.py .... [ 24%]
student-tests/api/test_migrations.py ...................... [ 32%]
student-tests/api/test_negative.py ..................................... [ 45%]
[ 45%]
student-tests/api/test_operability.py .............. [ 50%]
student-tests/api/test_pagination.py .................. [ 56%]
student-tests/api/test_pool.py ............ [ 60%]
student-tests/api/test_sessions.py .................. [ 66%]
student-tests/api/test_timeout.py ...... [ 68%]
student-tests/api/test_wire_format.py .. [ 69%]
student-tests/unit/test_authentication.py ..................... [ 76%]
student-tests/unit/test_cursor.py ........... [ 80%]
student-tests/unit/test_domain.py ..................................... [ 93%]
student-tests/unit/test_probe.py .............. [ 97%]
student-tests/unit/test_scaling.py ..... [ 99%]
student-tests/unit/test_timeouts.py . [100%]
===================== 290 passed, 12 deselected in 31.49s ======================
exit: 0
duration_seconds: 32.073
$ uv lock --check
Resolved 64 packages in 5ms
exit: 0
duration_seconds: 0.019
$ openspec validate --all --strict
- Validating...
✓ spec/lab1-event-publication
✓ spec/lab1-messenger-chats
✓ spec/lab1-messenger-history
✓ spec/lab1-messenger-identity
✓ spec/lab1-service-operability
✓ spec/lab2-auth-sessions
✓ spec/lab2-dependency-failures
✓ spec/lab2-history-index
✓ spec/lab2-persistent-storage
✓ spec/lab2-session-cache
✓ spec/lab3-failover-operations
✓ spec/lab3-idempotent-messages
✓ spec/lab3-load-balancing
✓ spec/lab3-scaling-cost
Totals: 14 passed, 0 failed (14 items)
exit: 0
duration_seconds: 0.831
$ docker ps --format '{{.ID}} {{.Names}} {{.Ports}}'
(empty)
exit: 0
$ make lint
.venv/bin/ruff check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
All checks passed!
.venv/bin/ruff format --check src student-tests alembic scripts/probe.py scripts/limits.py scripts/scaling.py tools
109 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
exit: 0
duration_seconds: 0.118