From 483d7eecb38eb4addc99143ad718417dd00582f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D1=82=D0=B2=D0=B5=D0=B9?= Date: Thu, 22 Oct 2026 11:55:41 +0300 Subject: [PATCH] add level 5 --- Makefile | 5 +- REPORT.md | 16 +++++- evidence/environment.json | 17 ++++--- evidence/reconcile-benchmark.txt | 2 + evidence/reconcile.txt | 4 +- src/reconcile.py | 14 +++++- src/storage/s3.py | 9 +++- student-tests/reconcile.py | 9 +++- student-tests/reconcile_benchmark.py | 74 ++++++++++++++++++++++++++++ 9 files changed, 133 insertions(+), 17 deletions(-) create mode 100644 evidence/reconcile-benchmark.txt create mode 100644 student-tests/reconcile_benchmark.py diff --git a/Makefile b/Makefile index ff530d52..47d3331e 100644 --- a/Makefile +++ b/Makefile @@ -29,7 +29,7 @@ test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) -.PHONY: test-attachments test-private test-upload-failover test-s3-outage reconcile reconcile-apply test-reconcile test-upload-memory test-s3-permissions +.PHONY: test-attachments test-private test-upload-failover test-s3-outage reconcile reconcile-apply test-reconcile test-reconcile-benchmark test-upload-memory test-s3-permissions test-attachments: uv run python student-tests/attachments.py --base-url "$(BASE_URL)" @@ -51,6 +51,9 @@ reconcile-apply: test-reconcile: $(PYTHON) student-tests/reconcile.py --base-url "$(BASE_URL)" +test-reconcile-benchmark: + $(PYTHON) student-tests/reconcile_benchmark.py --base-url "$(BASE_URL)" + test-upload-memory: uv run python student-tests/upload_memory.py --base-url "$(BASE_URL)" diff --git a/REPORT.md b/REPORT.md index 0fb4ad3b..6ac19112 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,7 +1,7 @@ # Отчёт — лабораторная 4 - Автор, группа: Матвей Козырев, БВТ2301. -- Целевая оценка: **4 — уровень стажёра/джуна**. +- Целевая оценка: **5 — исследование и доказанный результат; трек 2: согласованность PostgreSQL и S3**. - Ветка: `solution/BVT2301-Kozyrev`. - Проверки: 22 октября 2026 года. Базовый commit и SHA-256 исходников проверенного рабочего дерева — [evidence/environment.json](evidence/environment.json). - Использованные библиотеки: FastAPI, Uvicorn, asyncpg, argon2-cffi, boto3, Pillow. Помощь ИИ: Codex — перенос основы lab3, реализация вложений, тесты и документация. @@ -75,6 +75,16 @@ SeaweedFS закреплён digest `sha256:186de7ef977a20343ee9a5544073f081976a Missing object считается наблюдаемой ошибкой, а не поводом удалить метаданные: download вернёт 503, а maintenance output содержит attachment ID и object key. Восстановление байтов требует оператора или резервной копии; автоматическое восстановление не заявляется. Это безопаснее удаления используемого сообщения/метаданных без источника оригинала. +### Трек 2 — гипотеза, методика и результат + +**Гипотеза.** Полный inventory ключей `originals/` в S3 и `attachments.object_key` в PostgreSQL позволяет повторяемо обнаружить оба направления рассогласования. При удалении только aged orphan и при запрете автоматического удаления метаданных свежий или используемый файл не будет удалён maintenance-командой. + +**Методика.** [student-tests/reconcile.py](student-tests/reconcile.py) создаёт используемое вложение, новый orphan и запускает dry-run, apply с grace 3600 с и apply с grace 0. Затем повторяет apply и проверяет, что уже исправленный orphan не появился снова. Ошибка на стороне PostgreSQL моделируется контролируемым отказом API после успешного S3 PUT и до INSERT; следующая сверка обнаруживает orphan и удаляет его. Ошибка на стороне S3 моделируется удалением оригинала после созданной metadata; сверка сообщает пару `attachment_id`/`object_key`, не удаляет metadata, после восстановления байтов следующий обход не сообщает missing. Во всех проверках скачивается защищённое используемое вложение. + +**Стоимость обхода.** [student-tests/reconcile_benchmark.py](student-tests/reconcile_benchmark.py) добавляет 32, затем 128 свежих неиспользуемых объектов с уникальным префиксом. Для каждого размера выполняются три dry-run обхода; после измерения fixtures удаляются. Reconciler возвращает число объектов, metadata-строк, S3 list pages и длительности стадий, поэтому результат не зависит от ручного таймера. + +В зафиксированном прогоне для 32 добавленных объектов проверены 119 S3 keys и 87 metadata-строк, одна S3 page; длительности 0,299804, 0,204790 и 0,321822 с, медиана 0,299804 с. Для 128 добавленных объектов: 215 keys, те же 87 metadata-строк, одна page; 0,311197, 0,301204 и 0,220673 с, медиана 0,301204 с. Полный машинный вывод — [evidence/reconcile-benchmark.txt](evidence/reconcile-benchmark.txt). Шесть локальных замеров недостаточны для вывода о производительности при большом числе объектов или нескольких S3 pages; это измерение стоимости именно данного стенда. + Недоступность S3: upload/download и readiness возвращают 503 в формате Error; liveness остаётся 200. HAProxy исключает unready backend, поэтому при недоступности обеих реплик сам LB может вернуть собственный 503. Проверка формата ошибки API при таком отказе выполняется напрямую внутри Docker-сети. ## Проверки и доказательства @@ -97,6 +107,7 @@ make test-failover ACTION_SCRIPT=scripts/stop-one.sh docker compose start api-a api-b make reconcile make test-reconcile +make test-reconcile-benchmark make test-upload-memory make test-s3-permissions ``` @@ -116,6 +127,7 @@ make test-s3-permissions | Конкурентная идемпотентность и регрессии lab3 | Собственные проверки lab3 | [Результат](evidence/lab3-regressions.txt) | | Повторный bootstrap bucket | `docker compose run --rm --no-deps s3-init` | [Результат](evidence/bootstrap.txt) | | Reconcile: dry-run, grace period, protected object, missing object, post-PUT/pre-DB отказ | `make test-reconcile` | [PASS](evidence/reconcile.txt) | +| Трек 2: три обхода для 32 и 128 добавленных S3-объектов; метрики inventory | `make test-reconcile-benchmark` | [PASS](evidence/reconcile-benchmark.txt) | | Ограниченные S3 credentials | `make test-s3-permissions`: API не создаёт bucket; отдельный maintenance principal выполняет admin list | [PASS](evidence/s3-permissions.txt) | | 10 одновременных потоковых upload по 5 MiB | `make test-upload-memory`, cgroup `memory.current` каждые 0,1 с | [PASS](evidence/upload-memory.txt), [raw JSON](evidence/upload-memory.json) | @@ -123,7 +135,7 @@ make test-s3-permissions ## Ограничения -- Между S3 PUT и COMMIT PostgreSQL нет общей транзакции; orphan закрывает reconciler с grace period, но missing-object запись восстанавливается только оператором/backup. Автоматический repair исходного файла не реализован. +- Между S3 PUT и COMMIT PostgreSQL нет общей транзакции; orphan закрывает reconciler с grace period, но missing-object запись восстанавливается только оператором/backup. Автоматический repair исходного файла не реализован. Inventory выполняет полный обход keyspace `originals/` и таблицы metadata, поэтому его стоимость растёт с их размером. - API буферизует скачивание не более 10 MiB, чтобы проверить checksum до ответа. Эксперимент 10 upload измеряет cgroup memory.current, но не является capacity benchmark и не покрывает произвольные медленные клиенты, filesystem quota и одновременные скачивания. - Readiness проверяет доступность БД и bucket, но не наличие каждого отдельного объекта. Потеря одного объекта при доступном S3 обнаруживается при скачивании как 503. - Перезапуск с volumes и отказ API подтверждены на одном Docker-host. Потеря volumes/host не покрывается, резервное копирование не реализовано. diff --git a/evidence/environment.json b/evidence/environment.json index 0f7d10ba..21ec1b75 100644 --- a/evidence/environment.json +++ b/evidence/environment.json @@ -1,6 +1,6 @@ { - "recorded_at_utc": "2026-10-22T08:32:17.051591+00:00", - "base_commit": "e9ef559c349cf8b6fc32138fed0ea7a7600ce1ca", + "recorded_at_utc": "2026-10-22T08:46:03.568305+00:00", + "base_commit": "901786170792195f6dd95d0939db98236eb932ff", "branch": "solution/BVT2301-Kozyrev", "note": "Results apply to this working tree, not only the base commit. Functional tests; no load benchmark.", "host": "macOS-26.1-arm64-arm-64bit-Mach-O", @@ -12,7 +12,7 @@ "compose_version": "5.5.1", "sources_sha256": { "Dockerfile": "efede941e2ccf21cd1e70ebbf8af7647209bd030b2962f9446bee497a2ed6a8c", - "Makefile": "b417167d9d5baae110b2963a26ec12cea8ad8c96ce3d627a6c9e4fe8f51b74d3", + "Makefile": "3255468d0a33aae6c111e99a51bc22008171a493d69b4a01aecabc49a0a99eb3", "compose.yaml": "b239915436be84c7b1000346669ae9a10c89e83c55555a5e9eac0e20828f6fb6", "infra/README.md": "0e804fa51debba4c38d3cc84abf4704897665e0335b272060363f03aadd6354f", "infra/filer.toml": "ae3c01bf7708f5d4a319fdb454f753be0f137fe7c31269f1c413cbccc860f5c7", @@ -40,17 +40,18 @@ "src/main.py": "6980cdbb09c3b356ff870ee7fc972d85e835c58228d3c0ea27de8a668dc41ece", "src/migrate.py": "1d164c8921df2b5369e30b1f8936c2b71858c5279070f0fd593f62f66e1f0b7d", "src/models.py": "b94e6b26559afc5fd90f58d34d906c77bf4b4a78c716ac552358795496ad1d1b", - "src/reconcile.py": "67682de753e3331a5bb5c884ab6dabaad458c49e27d4a0f2c849d79b63a7c44b", + "src/reconcile.py": "db7cc30de97f62a172024e1ffa94d75f8e6e91b4e80db8b491ce5c213e37aae7", "src/routes.py": "3c21149a30ea7c2f695547c42133dcebcfbacbd6544bcb73c353be46fa35a2e6", "src/storage/__init__.py": "05ef66318c4c436eaafc493072640817219ab37bce464a265a2306233389064a", "src/storage/postgres.py": "c69fea94937fdf00b077a8f1d301e83f35e120c3a7c5153fe205725be0aa0428", - "src/storage/s3.py": "c51c8a804ca1ed869556c80252e119372696110443df30bd84f0836a01a0c305", + "src/storage/s3.py": "0779e6131c699055a1cff74e62addf207476819252e9a7aaf46c77af6d9044e6", "student-tests/attachment_resilience.py": "c72c431b355dda919c1b6b854d260f8c7420672ca9f86bf0848692da35dcb0ac", "student-tests/attachments.py": "a948fabfe83b73eb8e494c80fb9d1f2a949e2a95b7a21809a05975d65d68fc15", "student-tests/idempotency_concurrency.py": "db5d139009e4660ac1801af45d10e24665aa81cba737731e527c0f5b4152231e", "student-tests/readiness_failover.py": "0ef8355d85be66597d7d44eb7308dcb58c6c9a174d18f360b2d6d22fdcfbed14", "student-tests/readiness_unavailable.py": "46e3f680a3ff9cb79e95568004d97f1752dbdcd88fd4b5f160a9cc38af65a237", - "student-tests/reconcile.py": "298537cda6523631def290e750a651db1eace0647b99c68647c68e0fdb8f34ca", + "student-tests/reconcile.py": "25547bd5d41ff7e6650a7f30f8404cbb9dd8e61e5ab97897e065d82296b6c73a", + "student-tests/reconcile_benchmark.py": "9ae60097cb70e63baf5653559e727e02da246827a256e02580f03b5d47e1ca15", "student-tests/review_regressions.py": "de58f63b2c794c2775247ddd3fccc523870ccbe673ffa404fdd566274d1d41de", "student-tests/s3_permissions.py": "f265a64f900952db79d545e6c058a7605870c2843ed2298f5c68ad4a177663ff", "student-tests/session_expiry.py": "ba8ead4356e4d12c4047ac2b5704d3d3342f71c37b3c13f65a0a9d7c37186ad6", @@ -82,7 +83,7 @@ }, "api-a": { "image": "mtusi2026lab4-api-a", - "image_id": "sha256:679085dc5870799c12f9251cccbd62a1bf4d75e80a9706bc052b57d51d8251e7", + "image_id": "sha256:c6f7a7d42d87e0edbd0b8880e6c4b5b5594dea953154af4ff50158c78db66233", "state": "running", "health": "healthy", "memory_limit_bytes": 536870912, @@ -91,7 +92,7 @@ }, "api-b": { "image": "mtusi2026lab4-api-b", - "image_id": "sha256:0ca4765ed83bf21e802b8b90f2687839d761519271423bc10b2c6d72e29aef48", + "image_id": "sha256:466940ca873740202feb1ee727a2e0d0b2487ae8340df776639dd6f6381189fe", "state": "running", "health": "healthy", "memory_limit_bytes": 536870912, diff --git a/evidence/reconcile-benchmark.txt b/evidence/reconcile-benchmark.txt new file mode 100644 index 00000000..b88752a7 --- /dev/null +++ b/evidence/reconcile-benchmark.txt @@ -0,0 +1,2 @@ +{"method": "three dry-run inventories per controlled size", "results": [{"added_unreferenced_objects": 32, "median_seconds": 0.299804, "metadata_rows_scanned": 87, "runs": 3, "s3_list_pages": 1, "s3_objects_scanned": 119, "seconds": [0.299804, 0.20479, 0.321822]}, {"added_unreferenced_objects": 128, "median_seconds": 0.301204, "metadata_rows_scanned": 87, "runs": 3, "s3_list_pages": 1, "s3_objects_scanned": 215, "seconds": [0.311197, 0.301204, 0.220673]}]} +PASS: reconciler cost measured for 32 and 128 added S3 objects; fixtures removed diff --git a/evidence/reconcile.txt b/evidence/reconcile.txt index ca5fecd8..c84572b3 100644 --- a/evidence/reconcile.txt +++ b/evidence/reconcile.txt @@ -12,7 +12,7 @@ Container mtusi2026lab4-reconcile-run-cd1eb67e6a5f Created Container mtusi2026lab4-s3-init-run-a50b80f3ae78 Creating Container mtusi2026lab4-s3-init-run-a50b80f3ae78 Created -PASS: dry-run, grace period, orphan deletion and missing-object reporting +PASS: S3-side missing object, dry-run, grace period and idempotent orphan repair Container mtusi2026lab4-api-a-1 Recreate Container mtusi2026lab4-api-a-1 Recreated Container mtusi2026lab4-api-a-1 Starting @@ -24,7 +24,7 @@ PASS: dry-run, grace period, orphan deletion and missing-object reporting Container mtusi2026lab4-reconcile-run-1c72990b1ddc Created Container mtusi2026lab4-reconcile-run-2e902a56554d Creating Container mtusi2026lab4-reconcile-run-2e902a56554d Created -PASS: post-PUT/pre-DB injected failure leaves no permanent orphan +PASS: PostgreSQL-side post-PUT/pre-DB failure is repaired without deleting references Container mtusi2026lab4-api-a-1 Recreate Container mtusi2026lab4-api-a-1 Recreated Container mtusi2026lab4-api-a-1 Starting diff --git a/src/reconcile.py b/src/reconcile.py index a2016448..bc944b91 100644 --- a/src/reconcile.py +++ b/src/reconcile.py @@ -9,6 +9,7 @@ import argparse import asyncio from datetime import datetime, timedelta, timezone import json +from time import perf_counter from .config import load_settings from .storage.postgres import PostgresStore @@ -21,7 +22,11 @@ async def run(args) -> dict: s3 = S3Store(S3Settings.load()) await db.connect() try: - objects, metadata = await s3.list("originals/"), await db.attachment_keys() + started = perf_counter() + objects, s3_pages = await s3.list_with_pages("originals/") + listed_at = perf_counter() + metadata = await db.attachment_keys() + metadata_at = perf_counter() cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds) orphan = sorted(key for key, modified in objects.items() if key not in metadata and modified <= cutoff) @@ -34,6 +39,7 @@ async def run(args) -> dict: for key in orphan: await s3.delete(key) deleted.append(key) + finished = perf_counter() return { "mode": "apply" if args.apply else "dry-run", "grace_seconds": args.grace_seconds, @@ -43,6 +49,12 @@ async def run(args) -> dict: "fresh_unreferenced": fresh, "missing_objects": [{"attachment_id": item[0], "object_key": item[1]} for item in missing], "deleted": deleted, + "scan_metrics": { + "s3_list_pages": s3_pages, + "s3_list_seconds": round(listed_at - started, 6), + "postgres_metadata_seconds": round(metadata_at - listed_at, 6), + "total_seconds": round(finished - started, 6), + }, } finally: s3.client.close() diff --git a/src/storage/s3.py b/src/storage/s3.py index 0df4c498..bb6bd2e6 100644 --- a/src/storage/s3.py +++ b/src/storage/s3.py @@ -71,17 +71,24 @@ class S3Store: async def list(self, prefix: str) -> dict[str, object]: """Return every object under a controlled prefix, handling S3 pagination.""" + objects, _ = await self.list_with_pages(prefix) + return objects + + async def list_with_pages(self, prefix: str) -> tuple[dict[str, object], int]: + """Return inventory and number of S3 ListObjectsV2 pages consumed.""" result: dict[str, object] = {} token = None + pages = 0 while True: args = {"Bucket": self.settings.bucket, "Prefix": prefix} if token: args["ContinuationToken"] = token page = await self.call("list_objects_v2", **args) + pages += 1 for item in page.get("Contents", []): result[item["Key"]] = item["LastModified"] if not page.get("IsTruncated"): - return result + return result, pages token = page["NextContinuationToken"] async def delete(self, key: str) -> None: diff --git a/student-tests/reconcile.py b/student-tests/reconcile.py index 24782d53..e2e7e3b7 100644 --- a/student-tests/reconcile.py +++ b/student-tests/reconcile.py @@ -82,6 +82,9 @@ def main(): check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored") report = reconcile("--apply", "--grace-seconds", "0") check(report["deleted"] == [orphan], "aged orphan was not deleted safely") + report = reconcile("--apply", "--grace-seconds", "0") + check(orphan not in report["deleted"] and orphan not in report["orphan_candidates"], + "second repair run was not idempotent") check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image, "reconciler deleted a referenced object") @@ -96,7 +99,9 @@ def main(): s3_code("put", missing_key, image) check(client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", actor=bob)["bytes"] == image, "test object was not restored") - print("PASS: dry-run, grace period, orphan deletion and missing-object reporting", flush=True) + report = reconcile("--grace-seconds", "0") + check(expected not in report["missing_objects"], "restored object remained missing on second scan") + print("PASS: S3-side missing object, dry-run, grace period and idempotent orphan repair", flush=True) # Inject a process-equivalent failure after PUT directly into the configured # replica. The public load balancer may correctly select the healthy peer, @@ -127,7 +132,7 @@ else: check(injected, "injected post-PUT failure did not create a detectable orphan") report = reconcile("--apply", "--grace-seconds", "0") check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan") - print("PASS: post-PUT/pre-DB injected failure leaves no permanent orphan", flush=True) + print("PASS: PostgreSQL-side post-PUT/pre-DB failure is repaired without deleting references", flush=True) finally: environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0" subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"], diff --git a/student-tests/reconcile_benchmark.py b/student-tests/reconcile_benchmark.py new file mode 100644 index 00000000..358ba405 --- /dev/null +++ b/student-tests/reconcile_benchmark.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Measure repeatable reconciler inventory cost for two controlled S3 sizes.""" +import json +from pathlib import Path +import statistics +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import arguments, check, run + + +def compose(*args, input=None) -> str: + return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, input=input) + + +def reconcile() -> dict: + output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile", + "--grace-seconds", "3600") + return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{"))) + + +def mutate(action: str, keys: list[str]) -> None: + code = """from src.storage.s3 import S3Settings, S3Store +import json, sys +s3 = S3Store(S3Settings.load()) +try: + for key in json.load(sys.stdin): + if sys.argv[1] == 'put': + s3.client.put_object(Bucket=s3.settings.bucket, Key=key, Body=b'track-2-benchmark') + else: + s3.client.delete_object(Bucket=s3.settings.bucket, Key=key) +finally: + s3.client.close() +""" + compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action, + input=json.dumps(keys)) + + +def main() -> None: + arguments(__doc__) # Keeps the common --base-url/--ca-file command interface. + results = [] + for requested in (32, 128): + prefix = f"originals/track2-benchmark-{uuid.uuid4().hex}-" + keys = [prefix + str(index) for index in range(requested)] + try: + mutate("put", keys) + reports = [reconcile() for _ in range(3)] + for report in reports: + check(set(keys).issubset(report["fresh_unreferenced"]), + "benchmark objects were not included in the inventory") + check(not set(keys) & set(report["orphan_candidates"]), + "grace period classified fresh benchmark objects as deletable") + seconds = [report["scan_metrics"]["total_seconds"] for report in reports] + results.append({ + "added_unreferenced_objects": requested, + "runs": 3, + "s3_objects_scanned": reports[-1]["s3_objects"], + "metadata_rows_scanned": reports[-1]["metadata_rows"], + "s3_list_pages": reports[-1]["scan_metrics"]["s3_list_pages"], + "seconds": seconds, + "median_seconds": round(statistics.median(seconds), 6), + }) + finally: + mutate("delete", keys) + print(json.dumps({"method": "three dry-run inventories per controlled size", "results": results}, + sort_keys=True)) + print("PASS: reconciler cost measured for 32 and 128 added S3 objects; fixtures removed") + + +if __name__ == "__main__": + run(main)