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
+45 -14
View File
@@ -280,6 +280,8 @@ async def cmd_cursors(args: argparse.Namespace) -> dict:
осталась полная страница: каждый запрос read отдаёт READ_LIMIT;
- с `--partial` (классы чатов): ещё первая страница (курсор `null`) и
неполные страницы — в маленьком чате полной страницы нет.
Курсоры EXPLAIN выбираются отдельно: прореживание пула read не
должно сдвигать последнюю страницу истории.
"""
fixture = load_json(args.fixture)
chat = read_chat(fixture, args.chat_class)
@@ -304,6 +306,7 @@ async def cmd_cursors(args: argparse.Namespace) -> dict:
if cursor is None:
break
positions.append((seen, cursor))
pages = await explain_pages(conn, host, chat, fixture["token"], seen, positions)
finally:
await conn.close()
@@ -319,7 +322,9 @@ async def cmd_cursors(args: argparse.Namespace) -> dict:
step = len(entries) / args.pool
entries = [entries[int(index * step)] for index in range(args.pool)]
# соединение уже закрыто, цикл больше ничего не обслуживает
Path(args.out).write_text(json.dumps(entries), encoding="ascii") # noqa: ASYNC240
Path(args.out).write_text( # noqa: ASYNC240
json.dumps({"read": entries, "explain": pages}), encoding="ascii"
)
return {"messages": seen, "cursors": len(entries), "file": args.out}
@@ -371,28 +376,54 @@ async def cmd_probe(args: argparse.Namespace) -> dict:
await conn.close()
def explain_pages(pool: list) -> dict[str, list]:
"""Первая, средняя и последняя страница пула; у маленького чата — меньше."""
first = [0, None, READ_LIMIT]
if pool and pool[0][1] is None:
first, pool = pool[0], pool[1:]
pages = {"first": first}
if len(pool) >= 2:
pages["middle"] = pool[len(pool) // 2]
if pool:
pages["last"] = pool[-1]
async def explain_pages(
conn: Conn,
host: str,
chat: str,
token: str,
total: int,
boundaries: list[tuple[int, str]],
) -> dict[str, list]:
"""Точные страницы limit=50; недостающий курсор выдаёт само API."""
targets = {"first": 0}
last = max(0, total - 1) // READ_LIMIT * READ_LIMIT
middle = total // (2 * READ_LIMIT) * READ_LIMIT
if 0 < middle < last:
targets["middle"] = middle
if last:
targets["last"] = last
pages = {}
for name, position in targets.items():
before, cursor = max(
[(0, None), *boundaries],
key=lambda entry: entry[0] if entry[0] <= position else -1,
)
if before < position:
path = f"{messages_path(chat)}?limit={position - before}"
if cursor:
path += f"&cursor={cursor}"
status, data = await conn.call(
build_request("GET", path, host, token=token)
)
if status != 200:
raise HttpError(f"prepare explain {name}: GET history -> {status}")
page = json.loads(data)
cursor = page["next_cursor"]
if len(page["items"]) != position - before or cursor is None:
raise HttpError(f"prepare explain {name}: history changed during walk")
pages[name] = [position, cursor, min(READ_LIMIT, total - position)]
return pages
async def cmd_explain(args: argparse.Namespace) -> dict:
"""Страницы истории по одному запросу, по порядку `explain_pages`.
"""Точные страницы истории по одному запросу, независимо от пула read.
Пока они идут, оркестратор держит включённым `auto_explain`: план
каждого запроса приложения попадает в журнал PostgreSQL.
"""
fixture = load_json(args.fixture)
chat = read_chat(fixture, args.chat_class)
pages = explain_pages(load_json(args.cursors_file))
pages = load_json(args.cursors_file)["explain"]
host, port = target(args.base_url)
conn = Conn(host, port)
await conn.open()
@@ -551,7 +582,7 @@ def build_requests(args: argparse.Namespace, host: str) -> tuple[list, int, bool
fixture = load_json(args.fixture)
token = fixture["token"]
if args.scenario == "read":
pool = load_json(args.cursors_file)
pool = load_json(args.cursors_file)["read"]
if not pool:
raise SystemExit("cursor pool is empty: history is too small")
chat = read_chat(fixture, args.chat_class)