From b538b2db396f439f4436fc37a4dbfa7d172e2461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D1=82=D0=B2=D0=B5=D0=B9?= Date: Fri, 9 Oct 2026 21:06:31 +0300 Subject: [PATCH] fix cached history pagination and setup docs --- REPORT.md | 9 +++++---- evidence/cache-pagination-2026-10-09.txt | 1 + src/storage/history_cache.py | 12 +++++++++++- student-tests/lab4_checks.py | 16 ++++++++++++++++ 4 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 evidence/cache-pagination-2026-10-09.txt diff --git a/REPORT.md b/REPORT.md index 8673f3df..3f208451 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,7 +2,7 @@ - Автор, группа: Козырев Матвей БВТ2301 - Целевая оценка: 5; трек 1 — согласованность кэша -- Commit/PR: TODO после публикации +- PR: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/22 - Использованные библиотеки: FastAPI 0.141.1, Uvicorn 0.40.0, asyncpg 0.31.0, argon2-cffi 25.1.0, redis 5.0.8; зафиксированы в `pyproject.toml` и `uv.lock`. ## Запуск из чистого clone @@ -13,10 +13,11 @@ ```sh mkdir -p secrets openssl rand -hex 32 -out secrets/postgres_password -awk '{printf "postgresql://messenger:%s@postgres:5432/messenger\\n", $0}' \ +awk '{printf "postgresql://messenger:%s@postgres:5432/messenger\n", $0}' \ secrets/postgres_password > secrets/database_url +printf '%s\n' 'redis://redis:6379/0' > secrets/cache_url chmod 700 secrets -chmod 600 secrets/postgres_password secrets/database_url +chmod 600 secrets/postgres_password secrets/database_url secrets/cache_url docker compose --env-file .env.example config --quiet docker compose --env-file .env.example up -d --build ``` @@ -100,7 +101,7 @@ AOF и named volume `redis_data`. | Согласованность lock-файла | `uv lock --check` | PASS | выполнено | | Публичный smoke | `make test` | `PASS: lab2 public API scenario` | `evidence/smoke-2026-10-08.txt` | | Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` | `evidence/persistence-2026-10-08.txt` | -| Redis cache | `make test-grade4`; `redis-cli --scan` | read-after-write без stale read; создан ключ `history:first:…` | `evidence/redis-cache-2026-10-08.txt` | +| Redis cache и курсор | `make test-grade4`; `redis-cli --scan` | read-after-write без stale read; повторный GET кэшированной страницы и её continuation возвращают 200 | `evidence/cache-pagination-2026-10-09.txt` | | Гонка и rollback | `make test-grade4` | Ровно одна регистрация успешна; неуспешный чат не виден | `evidence/grade4-checks-2026-10-08.txt` | | TTL и зависимости | `make test-grade4`; TTL=2 | Expired session → 401; Redis fallback проходит smoke; DB readiness → 503 | `evidence/grade4-checks-2026-10-08.txt` | | Индекс истории | `./scripts/explain_history.sh` | Index Scan, 50 строк, shared hit=3 | `evidence/explain-history-2026-10-08.txt` | diff --git a/evidence/cache-pagination-2026-10-09.txt b/evidence/cache-pagination-2026-10-09.txt new file mode 100644 index 00000000..32957fb7 --- /dev/null +++ b/evidence/cache-pagination-2026-10-09.txt @@ -0,0 +1 @@ +PASS: registration race, chat rollback and cache read-after-write diff --git a/src/storage/history_cache.py b/src/storage/history_cache.py index 616444f0..de4f88fa 100644 --- a/src/storage/history_cache.py +++ b/src/storage/history_cache.py @@ -1,5 +1,6 @@ import json from asyncio import Lock, sleep +from datetime import UTC, datetime from time import monotonic from secrets import token_urlsafe from uuid import UUID @@ -73,13 +74,22 @@ class HistoryCache: def _lock_key(cls, chat_id: UUID, version: int, limit: int) -> str: return cls._key(chat_id, version, limit) + ":lock" + @staticmethod + def _decode_rows(value: str) -> list[dict]: + rows = json.loads(value) + for row in rows: + created_at = row.get("created_at") + if isinstance(created_at, str): + row["created_at"] = datetime.fromisoformat(created_at).astimezone(UTC) + return rows + async def get(self, chat_id: UUID, version: int, limit: int) -> list[dict] | None: client = await self._client_or_none() if client is None: return None try: value = await client.get(self._key(chat_id, version, limit)) - return json.loads(value) if value else None + return self._decode_rows(value) if value else None except RedisError: await self._mark_unavailable(client) return None diff --git a/student-tests/lab4_checks.py b/student-tests/lab4_checks.py index 0df37ed8..cf429a88 100644 --- a/student-tests/lab4_checks.py +++ b/student-tests/lab4_checks.py @@ -59,6 +59,22 @@ def main() -> None: {message["id"] for message in history} == {first["id"], second["id"]}, "history cache returned stale data after write", ) + + first_page_path = "/api/v1/chats/" + chat["id"] + "/messages?limit=1" + first_page = client.call( + "GET", first_page_path, actor=alice, schema="MessagePage" + )["json"] + cached_page = client.call( + "GET", first_page_path, actor=alice, schema="MessagePage" + )["json"] + check(first_page == cached_page, "cached page differs from the first response") + check(first_page["next_cursor"], "first page has no continuation cursor") + client.call( + "GET", + first_page_path + "&cursor=" + first_page["next_cursor"], + actor=alice, + schema="MessagePage", + ) print("PASS: registration race, chat rollback and cache read-after-write")