fix: make lab2 setup and benchmark page selection reproducible

This commit is contained in:
2026-10-02 03:47:15 +03:00
parent 1602de539d
commit c7d36bcaa5
13 changed files with 364 additions and 63 deletions
+3
View File
@@ -49,6 +49,9 @@ API — `docker compose run` на свободных портах `127.0.0.1`;
OpenAPI, `test_cache.py` — что кэш не меняет ответы, `test_request_id.py`
— поведение слоя `X-Request-Id`, `test_failures.py` — проверки отказов
(маркер `fault` на весь модуль). Имя теста говорит, что проверяется.
- `test_bench.py` — регрессия выбора страниц EXPLAIN через реальный
HTTP-сервер: маленький чат, неполная последняя страница и прореженный
пул курсоров. Приложение и хранилище не подменяются.
- Хелперы — `helpers.py`: `register` (регистрация с паролем и вход —
«актёр» = поля `User` + `password` + `token`), `login`, `logout`,
`create_chat`, `send`, `read_history`, `chat_ids`, `public`,
+95
View File
@@ -0,0 +1,95 @@
"""Курсоры стенда: последняя страница не зависит от прореживания пула."""
import json
import subprocess
import sys
from pathlib import Path
import httpx
import pytest
from helpers import create_chat, headers, messages_path, register, send
ROOT = Path(__file__).resolve().parents[1]
@pytest.mark.parametrize(
("total", "pool_size", "partial", "expected_positions"),
[
(10, 1, True, {"first": 0}),
(205, 1, False, {"first": 0, "middle": 100, "last": 200}),
(1000, 2, False, {"first": 0, "middle": 500, "last": 950}),
],
ids=["one-partial-page", "partial-last-page", "thinned-pool"],
)
def test_explain_reads_exact_history_pages(
client: httpx.Client,
tmp_path: Path,
total: int,
pool_size: int,
partial: bool,
expected_positions: dict[str, int],
) -> None:
actor = register(client, "bench")
chat = create_chat(client, actor)
sent = []
for index in range(total):
response = send(client, actor, chat, f"bench regression {index}")
assert response.status_code == 201
sent.append(response.json()["id"])
fixture = tmp_path / "fixture.json"
fixture.write_text(
json.dumps({"token": actor["token"], "history_chat": chat["id"]})
)
cursors = tmp_path / "cursors.json"
def generate(*args: str) -> dict:
result = subprocess.run(
[
sys.executable,
str(ROOT / "bench" / "loadgen.py"),
"--base-url",
str(client.base_url),
*args,
],
capture_output=True,
text=True,
check=True,
timeout=30,
)
return json.loads(result.stdout)
options = ["--partial"] if partial else []
walked = generate(
"cursors",
"--fixture",
str(fixture),
"--out",
str(cursors),
"--pool",
str(pool_size),
*options,
)
assert walked["messages"] == total
saved = json.loads(cursors.read_text())
assert 0 < len(saved["read"]) <= pool_size
assert (
generate("explain", "--fixture", str(fixture), "--cursors-file", str(cursors))
== expected_positions
)
for name, start in expected_positions.items():
_, cursor, expected_count = saved["explain"][name]
params = {"limit": 50}
if cursor:
params["cursor"] = cursor
response = client.get(
messages_path(chat), params=params, headers=headers(actor)
)
assert response.status_code == 200
page = response.json()
assert [item["id"] for item in page["items"]] == sent[start : start + 50]
assert len(page["items"]) == expected_count
if name == "last" or total <= 50:
assert page["next_cursor"] is None