diff --git a/REPORT.md b/REPORT.md index 812bbd99..0f363f9e 100644 --- a/REPORT.md +++ b/REPORT.md @@ -497,6 +497,9 @@ keep-alive, до 4 процессов; вход как в контракте — до матрицы записи при одинаковых 126 000 строках; общий PK учитывается во всех вариантах. Время восстановления оценивается по двум независимым восстановлениям с отдельными volumes, без параллельной нагрузки. +Расчёты воспроизводятся командой `uv run python bench/analyze_track2.py`: +она читает исходные CSV/JSON, проверяет полные матрицы и сравнимость, +считает шум CPU отдельно от RPS и не меняет файлы эксперимента. Полный профиль `full` завершён 2026-10-02: 00:47:30–01:03:21 UTC, 951 с (15 минут 51 секунда). Измеренный код — commit `c7d36bc`, diff --git a/bench/AGENTS.md b/bench/AGENTS.md index c92015a4..ac962be3 100644 --- a/bench/AGENTS.md +++ b/bench/AGENTS.md @@ -15,6 +15,7 @@ BUFFERS)` на ≥10 000 сообщениях (уровень «4») и изме | `run.py`, `bench.compose.yml`, `bench.env` | `make bench BENCH_LABEL=<метка> [BENCH_PROFILE=skew] [BENCH_VARIANT=...]`, `make bench-quick [QUICK_PROFILE=skew-quick]` | собирает образ, на каждый размер поднимает свежий стенд, применяет вариант индекса, наполняет историю, снимает планы и матрицу, пишет `evidence/bench/<метка>/` | | `loadgen.py` | — (его вызывает `run.py` через `docker exec`) | генератор: closed-loop, keep-alive, несколько процессов; вход по Basic, Bearer; один читаемый чат или классы чатов с наполнением по плану | | `compare.py` | `make bench-compare BEFORE= AFTER= [AA=]` | дельты двух меток, уровень шума, планы до/после, проверка методики по паспортам | +| `analyze_track2.py` | `uv run python bench/analyze_track2.py` | проверяет полные матрицы и сравнимость четырёх меток, считает отдельный шум CPU записи, выводит JSON в stdout; файлы стенда не меняет | | `restore.py` | `make bench-restore RESTORE_LABEL=<метка> [RESTORE_PROFILE=skew-quick]` | трек 2: стенд `skew`, `pg_dump`, записи после backup, восстановление в новый контейнер PostgreSQL, сверка, API на восстановленной базе, `FLUSHALL`; пишет `evidence/restore/<метка>/` | Профили (`PROFILES` в `run.py`): diff --git a/bench/RUNBOOK.md b/bench/RUNBOOK.md index 5b690416..370fb2d1 100644 --- a/bench/RUNBOOK.md +++ b/bench/RUNBOOK.md @@ -277,6 +277,16 @@ RESTORE_LABEL=restore-2`. В отчёт — оба, время этапов ка В `REPORT.md`, разделы «Эксперименты» и «Ограничения»: +После двух восстановлений расчёты всего трека можно воспроизвести: + +```sh +uv run python bench/analyze_track2.py > /tmp/t2-analysis.json +``` + +Скрипт проверяет 45 ячеек каждой метки, хост и методику, отдельный шум +CPU БД на запись и проверки восстановлений. Его JSON — производный +расчёт из исходных файлов, а не ещё одна метка нагрузки. + - [ ] процедура: команды, что сверяется и как (число строк, контрольная сумма по id, выборка по зерну, проверка через API); - [ ] время этапов из `restore.md`: backup, новый PostgreSQL, копия, diff --git a/bench/analyze_track2.py b/bench/analyze_track2.py new file mode 100644 index 00000000..d8b34a38 --- /dev/null +++ b/bench/analyze_track2.py @@ -0,0 +1,191 @@ +"""Расчёты трека 2 из неизменённых файлов стенда; результат — JSON в stdout. + + uv run python bench/analyze_track2.py + +Шум CPU оценивается в своей метрике, по протоколу REPORT.md, +зафиксированному до прогонов. Скрипт не меняет результаты и не запускает +нагрузку. Числа в отчёте можно проверить этой же командой. +""" + +import argparse +import csv +import json +import statistics +from pathlib import Path + +import compare + +ROOT = Path(__file__).resolve().parents[1] +METRICS = ( + "rps", + "p50_ms", + "p95_ms", + "p99_ms", + "cpu_us_per_req", + "db_cpu_us_per_req", + "app_cpu_cores", + "db_cpu_cores", +) + + +def stats(rows: list[dict]) -> dict: + grouped: dict[tuple, list] = {} + for row in rows: + key = (row["scenario"], row.get("chat_class", ""), int(row["clients"])) + grouped.setdefault(key, []).append(row) + return { + key: { + metric: ( + statistics.median(values), + min(values), + max(values), + ) + for metric in METRICS + if (values := [float(row[metric]) for row in group]) + } + for key, group in grouped.items() + } + + +def load(label: str) -> dict: + data = compare.load(label) + meta = data["meta"] + if ( + meta.get("aborted") + or meta.get("host_warnings") + or meta["code"].get("git_dirty") + or any(row["flags"] or int(row["errors"]) for row in data["rows"]) + ): + raise SystemExit(f"analyze: label {label} is not a clean completed run") + profile = meta["profile"] + if profile["name"] != "skew": + raise SystemExit(f"analyze: expected skew, got {profile['name']}") + expected = { + (scenario, chat_class, clients, repeat) + for scenario, chat_class in [ + *(("read", name) for name, _, _ in profile["classes"]), + ("write", ""), + ] + for clients in profile["clients"] + for repeat in range(1, profile["repeats"] + 1) + } + actual = { + (r["scenario"], r["chat_class"], int(r["clients"]), int(r["repeat"])) + for r in data["rows"] + } + if actual != expected or len(data["rows"]) != len(expected): + raise SystemExit(f"analyze: label {label} has an incomplete matrix") + data["stats"] = stats(data["rows"]) + return data + + +def restore(label: str) -> dict: + data = json.loads( + (ROOT / "evidence" / "restore" / label / "restore.json").read_text() + ) + if ( + data.get("aborted") + or not data["checks"] + or not all(row["ok"] for row in data["checks"]) + ): + raise SystemExit(f"analyze: restore {label} did not pass all checks") + return { + "label": label, + "counts": data["before"]["counts"], + "timings": data["timings"], + "dump_bytes": data["backup"]["dump_bytes"], + "lost_messages": data["after_backup"]["messages_in_source"] + - data["restored"]["counts"]["messages"], + "checks": data["checks"], + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + for option, default in ( + ("keyset", "t2-keyset"), + ("aa", "t2-keyset-2"), + ("chat-only", "t2-chat-only"), + ("no-index", "t2-no-index"), + ("restore", "restore"), + ("restore-repeat", "restore-2"), + ): + parser.add_argument(f"--{option}", default=default) + args = parser.parse_args() + labels = [args.keyset, args.aa, args.chat_only, args.no_index] + runs = [load(label) for label in labels] + base, aa, chat_only, no_index = runs + methodology = compare.methodology(base["meta"]) + for data in runs[1:]: + if compare.methodology(data["meta"]) != methodology: + raise SystemExit("analyze: experiment methodology differs") + for section, keys in ( + ("host", compare.HOST_KEYS), + ("docker", compare.DOCKER_KEYS), + ): + if any( + data["meta"][section].get(key) != base["meta"][section].get(key) + for key in keys + ): + raise SystemExit(f"analyze: {section} differs between labels") + if data["meta"]["code"]["src_sha256"] != base["meta"]["code"]["src_sha256"]: + raise SystemExit("analyze: application code differs") + if [data["meta"]["variant"] for data in runs] != [ + "keyset", + "keyset", + "chat-only", + "no-index", + ]: + raise SystemExit("analyze: unexpected index variants") + cpu_metric = "db_cpu_us_per_req" + cpu_noise = max( + abs(compare.delta(base["stats"][key][cpu_metric][0], value[cpu_metric][0])) + for key, value in aa["stats"].items() + if key[0] == "write" + ) + result = { + "rps_noise_percent": compare.noise_levels( + compare.cell_stats(base["rows"]), compare.cell_stats(aa["rows"]) + ), + "write_db_cpu_noise_percent": cpu_noise, + "variants": {}, + "write_db_cpu_comparisons": [], + "restores": [restore(args.restore), restore(args.restore_repeat)], + } + for data in runs: + memory = next(iter(data["memory"].values())) + result["variants"][data["label"]] = { + "duration_s": data["meta"]["duration_s"], + "cells": [ + {"scenario": key[0], "chat_class": key[1], "clients": key[2], **value} + for key, value in sorted(data["stats"].items()) + ], + "plans": data["meta"]["plans"], + "memory": memory, + "fill": list( + csv.DictReader( + (ROOT / "evidence" / "bench" / data["label"] / "fill.csv").open() + ) + ), + } + for before, after in ((base, chat_only), (chat_only, no_index), (base, no_index)): + for key in sorted(base["stats"]): + if key[0] != "write": + continue + b, a = before["stats"][key][cpu_metric], after["stats"][key][cpu_metric] + result["write_db_cpu_comparisons"].append( + { + "before": before["label"], + "after": after["label"], + "clients": key[2], + "before_us": b, + "after_us": a, + "delta_percent": compare.delta(b[0], a[0]), + "verdict": compare.verdict(b, a, cpu_noise), + } + ) + print(json.dumps(result, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/evidence/bench/t2-keyset/explain-big-60k.txt b/evidence/bench/t2-keyset/explain-big-60k.txt new file mode 100644 index 00000000..f838ae92 --- /dev/null +++ b/evidence/bench/t2-keyset/explain-big-60k.txt @@ -0,0 +1,100 @@ +# План запроса истории: класс big, чат 60k + +Код: src_sha256 8a7e256c540af433, commit 6d2240ce9fec; вариант индекса: keyset +Страница истории читаемого чата (limit 50); позиция — сколько +сообщений истории до страницы: +- first: после 0 +- middle: после 30000 +- last: после 59950 + +## Планы приложения + +auto_explain (ANALYZE, BUFFERS, TIMING): запрос, параметры и план, +с которыми его выполнило приложение (prepared statement asyncpg). + +### first + +duration: 0.049 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID ORDER BY messages.created_at, messages.id + LIMIT $2::INTEGER +Query Parameters: $1 = '713e41cf-931c-490c-930e-81da041d316a', $2 = '51' +Limit (cost=0.42..16.33 rows=51 width=204) (actual time=0.012..0.026 rows=51.00 loops=1) + Buffers: shared hit=31 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..18642.57 rows=59749 width=204) (actual time=0.012..0.024 rows=51.00 loops=1) + Index Cond: (chat_id = '713e41cf-931c-490c-930e-81da041d316a'::uuid) + Index Searches: 1 + Buffers: shared hit=31 + +### middle + +duration: 0.050 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID AND (messages.created_at, messages.id) > ($2::TIMESTAMP WITH TIME ZONE, $3::UUID) ORDER BY messages.created_at, messages.id + LIMIT $4::INTEGER +Query Parameters: $1 = '713e41cf-931c-490c-930e-81da041d316a', $2 = '2026-10-02 01:18:37.730273+00', $3 = 'e9d09e50-c4db-4bd9-8578-ace1129350a4', $4 = '51' +Limit (cost=0.42..24.20 rows=6 width=204) (actual time=0.011..0.029 rows=51.00 loops=1) + Buffers: shared hit=54 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..246.13 rows=62 width=204) (actual time=0.010..0.026 rows=51.00 loops=1) + Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3))) + Index Searches: 1 + Buffers: shared hit=54 + +### last + +duration: 0.057 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID AND (messages.created_at, messages.id) > ($2::TIMESTAMP WITH TIME ZONE, $3::UUID) ORDER BY messages.created_at, messages.id + LIMIT $4::INTEGER +Query Parameters: $1 = '713e41cf-931c-490c-930e-81da041d316a', $2 = '2026-10-02 01:19:34.10731+00', $3 = '89f52dfd-45fe-4dc1-852e-20e885ca3e40', $4 = '51' +Limit (cost=0.42..24.20 rows=6 width=204) (actual time=0.008..0.036 rows=50.00 loops=1) + Buffers: shared hit=53 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..246.13 rows=62 width=204) (actual time=0.007..0.033 rows=50.00 loops=1) + Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3))) + Index Searches: 1 + Buffers: shared hit=53 + +## Страница middle в psql: с индексом и без + +Тот же текст запроса и те же параметры, что у плана middle. +psql планирует их заново (custom plan). DROP INDEX — внутри +транзакции, затем ROLLBACK: индекс остаётся в базе. + +### С индексом ix_messages_chat_id_created_at_id + +Limit (cost=0.42..28.78 rows=51 width=204) (actual time=0.037..0.067 rows=51.00 loops=1) + Buffers: shared hit=54 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..16710.37 rows=30046 width=204) (actual time=0.036..0.063 rows=51.00 loops=1) + Index Cond: ((chat_id = '713e41cf-931c-490c-930e-81da041d316a'::uuid) AND (ROW(created_at, id) > ROW('2026-10-02 01:18:37.730273+00'::timestamp with time zone, 'e9d09e50-c4db-4bd9-8578-ace1129350a4'::uuid))) + Index Searches: 1 + Buffers: shared hit=54 +Planning: + Buffers: shared hit=141 +Planning Time: 0.274 ms +Execution Time: 0.092 ms + +### Без индекса ix_messages_chat_id_created_at_id + +Limit (cost=6103.43..6109.37 rows=51 width=204) (actual time=5.497..6.604 rows=51.00 loops=1) + Buffers: shared hit=3797 + -> Gather Merge (cost=6103.43..9602.79 rows=30046 width=204) (actual time=5.496..6.601 rows=51.00 loops=1) + Workers Planned: 2 + Workers Launched: 2 + Buffers: shared hit=3797 + -> Sort (cost=5103.41..5134.71 rows=12519 width=204) (actual time=4.204..4.206 rows=42.00 loops=3) + Sort Key: created_at, id + Sort Method: top-N heapsort Memory: 46kB + Buffers: shared hit=3797 + Worker 0: Sort Method: top-N heapsort Memory: 44kB + Worker 1: Sort Method: top-N heapsort Memory: 50kB + -> Parallel Seq Scan on messages (cost=0.00..4685.75 rows=12519 width=204) (actual time=0.885..3.596 rows=10000.00 loops=3) + Filter: ((chat_id = '713e41cf-931c-490c-930e-81da041d316a'::uuid) AND (ROW(created_at, id) > ROW('2026-10-02 01:18:37.730273+00'::timestamp with time zone, 'e9d09e50-c4db-4bd9-8578-ace1129350a4'::uuid))) + Rows Removed by Filter: 32000 + Buffers: shared hit=3767 +Planning: + Buffers: shared hit=17 +Planning Time: 0.092 ms +Execution Time: 6.628 ms diff --git a/evidence/bench/t2-keyset/explain-medium-6k.txt b/evidence/bench/t2-keyset/explain-medium-6k.txt new file mode 100644 index 00000000..e32dadf3 --- /dev/null +++ b/evidence/bench/t2-keyset/explain-medium-6k.txt @@ -0,0 +1,100 @@ +# План запроса истории: класс medium, чат 6k + +Код: src_sha256 8a7e256c540af433, commit 6d2240ce9fec; вариант индекса: keyset +Страница истории читаемого чата (limit 50); позиция — сколько +сообщений истории до страницы: +- first: после 0 +- middle: после 3000 +- last: после 5950 + +## Планы приложения + +auto_explain (ANALYZE, BUFFERS, TIMING): запрос, параметры и план, +с которыми его выполнило приложение (prepared statement asyncpg). + +### first + +duration: 0.057 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID ORDER BY messages.created_at, messages.id + LIMIT $2::INTEGER +Query Parameters: $1 = 'a77e2995-196e-4901-9238-c7a948bfcb16', $2 = '51' +Limit (cost=0.42..114.76 rows=51 width=204) (actual time=0.012..0.034 rows=51.00 loops=1) + Buffers: shared hit=47 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..13230.99 rows=5901 width=204) (actual time=0.012..0.031 rows=51.00 loops=1) + Index Cond: (chat_id = 'a77e2995-196e-4901-9238-c7a948bfcb16'::uuid) + Index Searches: 1 + Buffers: shared hit=47 + +### middle + +duration: 0.052 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID AND (messages.created_at, messages.id) > ($2::TIMESTAMP WITH TIME ZONE, $3::UUID) ORDER BY messages.created_at, messages.id + LIMIT $4::INTEGER +Query Parameters: $1 = 'a77e2995-196e-4901-9238-c7a948bfcb16', $2 = '2026-10-02 01:18:36.967812+00', $3 = '3f451920-4028-4279-afbf-1ceed233019e', $4 = '51' +Limit (cost=0.42..24.20 rows=6 width=204) (actual time=0.009..0.031 rows=51.00 loops=1) + Buffers: shared hit=50 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..246.13 rows=62 width=204) (actual time=0.008..0.028 rows=51.00 loops=1) + Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3))) + Index Searches: 1 + Buffers: shared hit=50 + +### last + +duration: 0.050 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID AND (messages.created_at, messages.id) > ($2::TIMESTAMP WITH TIME ZONE, $3::UUID) ORDER BY messages.created_at, messages.id + LIMIT $4::INTEGER +Query Parameters: $1 = 'a77e2995-196e-4901-9238-c7a948bfcb16', $2 = '2026-10-02 01:19:33.259754+00', $3 = 'b50d595c-c526-46e5-b538-ad0101f42ca0', $4 = '51' +Limit (cost=0.42..24.20 rows=6 width=204) (actual time=0.008..0.029 rows=50.00 loops=1) + Buffers: shared hit=52 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..246.13 rows=62 width=204) (actual time=0.007..0.026 rows=50.00 loops=1) + Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3))) + Index Searches: 1 + Buffers: shared hit=52 + +## Страница middle в psql: с индексом и без + +Тот же текст запроса и те же параметры, что у плана middle. +psql планирует их заново (custom plan). DROP INDEX — внутри +транзакции, затем ROLLBACK: индекс остаётся в базе. + +### С индексом ix_messages_chat_id_created_at_id + +Limit (cost=0.42..145.28 rows=51 width=204) (actual time=0.040..0.112 rows=51.00 loops=1) + Buffers: shared hit=50 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..8552.81 rows=3011 width=204) (actual time=0.038..0.105 rows=51.00 loops=1) + Index Cond: ((chat_id = 'a77e2995-196e-4901-9238-c7a948bfcb16'::uuid) AND (ROW(created_at, id) > ROW('2026-10-02 01:18:36.967812+00'::timestamp with time zone, '3f451920-4028-4279-afbf-1ceed233019e'::uuid))) + Index Searches: 1 + Buffers: shared hit=50 +Planning: + Buffers: shared hit=141 +Planning Time: 0.387 ms +Execution Time: 0.145 ms + +### Без индекса ix_messages_chat_id_created_at_id + +Limit (cost=5750.37..5756.31 rows=51 width=204) (actual time=4.821..6.011 rows=51.00 loops=1) + Buffers: shared hit=3797 + -> Gather Merge (cost=5750.37..6101.05 rows=3011 width=204) (actual time=4.820..6.004 rows=51.00 loops=1) + Workers Planned: 2 + Workers Launched: 2 + Buffers: shared hit=3797 + -> Sort (cost=4750.34..4753.48 rows=1255 width=204) (actual time=3.477..3.479 rows=40.33 loops=3) + Sort Key: created_at, id + Sort Method: top-N heapsort Memory: 50kB + Buffers: shared hit=3797 + Worker 0: Sort Method: top-N heapsort Memory: 48kB + Worker 1: Sort Method: top-N heapsort Memory: 47kB + -> Parallel Seq Scan on messages (cost=0.00..4685.75 rows=1255 width=204) (actual time=0.977..3.386 rows=1000.00 loops=3) + Filter: ((chat_id = 'a77e2995-196e-4901-9238-c7a948bfcb16'::uuid) AND (ROW(created_at, id) > ROW('2026-10-02 01:18:36.967812+00'::timestamp with time zone, '3f451920-4028-4279-afbf-1ceed233019e'::uuid))) + Rows Removed by Filter: 41000 + Buffers: shared hit=3767 +Planning: + Buffers: shared hit=17 +Planning Time: 0.083 ms +Execution Time: 6.032 ms diff --git a/evidence/bench/t2-keyset/explain-small-200.txt b/evidence/bench/t2-keyset/explain-small-200.txt new file mode 100644 index 00000000..8044f039 --- /dev/null +++ b/evidence/bench/t2-keyset/explain-small-200.txt @@ -0,0 +1,100 @@ +# План запроса истории: класс small, чат 200 + +Код: src_sha256 8a7e256c540af433, commit 6d2240ce9fec; вариант индекса: keyset +Страница истории читаемого чата (limit 50); позиция — сколько +сообщений истории до страницы: +- first: после 0 +- middle: после 100 +- last: после 150 + +## Планы приложения + +auto_explain (ANALYZE, BUFFERS, TIMING): запрос, параметры и план, +с которыми его выполнило приложение (prepared statement asyncpg). + +### first + +duration: 0.096 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID ORDER BY messages.created_at, messages.id + LIMIT $2::INTEGER +Query Parameters: $1 = '31d92451-4a01-41f6-89ce-cdeedc71f887', $2 = '51' +Limit (cost=0.42..197.30 rows=51 width=204) (actual time=0.014..0.070 rows=51.00 loops=1) + Buffers: shared hit=54 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..826.57 rows=214 width=204) (actual time=0.013..0.066 rows=51.00 loops=1) + Index Cond: (chat_id = '31d92451-4a01-41f6-89ce-cdeedc71f887'::uuid) + Index Searches: 1 + Buffers: shared hit=54 + +### middle + +duration: 0.079 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID AND (messages.created_at, messages.id) > ($2::TIMESTAMP WITH TIME ZONE, $3::UUID) ORDER BY messages.created_at, messages.id + LIMIT $4::INTEGER +Query Parameters: $1 = '31d92451-4a01-41f6-89ce-cdeedc71f887', $2 = '2026-10-02 01:18:47.043523+00', $3 = '83f8e35a-40fb-4624-9f15-e60f4b907f7b', $4 = '51' +Limit (cost=0.42..24.20 rows=6 width=204) (actual time=0.010..0.057 rows=51.00 loops=1) + Buffers: shared hit=54 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..246.13 rows=62 width=204) (actual time=0.009..0.054 rows=51.00 loops=1) + Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3))) + Index Searches: 1 + Buffers: shared hit=54 + +### last + +duration: 0.062 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID AND (messages.created_at, messages.id) > ($2::TIMESTAMP WITH TIME ZONE, $3::UUID) ORDER BY messages.created_at, messages.id + LIMIT $4::INTEGER +Query Parameters: $1 = '31d92451-4a01-41f6-89ce-cdeedc71f887', $2 = '2026-10-02 01:19:14.56679+00', $3 = '0d4d0ef8-1c06-4f4a-9543-2c299986bee7', $4 = '51' +Limit (cost=0.42..24.20 rows=6 width=204) (actual time=0.008..0.043 rows=50.00 loops=1) + Buffers: shared hit=52 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..246.13 rows=62 width=204) (actual time=0.007..0.040 rows=50.00 loops=1) + Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3))) + Index Searches: 1 + Buffers: shared hit=52 + +## Страница middle в psql: с индексом и без + +Тот же текст запроса и те же параметры, что у плана middle. +psql планирует их заново (custom plan). DROP INDEX — внутри +транзакции, затем ROLLBACK: индекс остаётся в базе. + +### С индексом ix_messages_chat_id_created_at_id + +Limit (cost=0.42..201.59 rows=51 width=204) (actual time=0.035..0.274 rows=51.00 loops=1) + Buffers: shared hit=54 + -> Index Scan using ix_messages_chat_id_created_at_id on messages (cost=0.42..351.48 rows=89 width=204) (actual time=0.034..0.269 rows=51.00 loops=1) + Index Cond: ((chat_id = '31d92451-4a01-41f6-89ce-cdeedc71f887'::uuid) AND (ROW(created_at, id) > ROW('2026-10-02 01:18:47.043523+00'::timestamp with time zone, '83f8e35a-40fb-4624-9f15-e60f4b907f7b'::uuid))) + Index Searches: 1 + Buffers: shared hit=54 +Planning: + Buffers: shared hit=141 +Planning Time: 0.375 ms +Execution Time: 0.307 ms + +### Без индекса ix_messages_chat_id_created_at_id + +Limit (cost=5686.74..5692.68 rows=51 width=204) (actual time=5.001..6.120 rows=51.00 loops=1) + Buffers: shared hit=3797 + -> Gather Merge (cost=5686.74..5697.10 rows=89 width=204) (actual time=5.000..6.114 rows=51.00 loops=1) + Workers Planned: 2 + Workers Launched: 2 + Buffers: shared hit=3797 + -> Sort (cost=4686.71..4686.81 rows=37 width=204) (actual time=3.568..3.570 rows=28.33 loops=3) + Sort Key: created_at, id + Sort Method: quicksort Memory: 34kB + Buffers: shared hit=3797 + Worker 0: Sort Method: quicksort Memory: 32kB + Worker 1: Sort Method: quicksort Memory: 33kB + -> Parallel Seq Scan on messages (cost=0.00..4685.75 rows=37 width=204) (actual time=1.232..3.547 rows=33.33 loops=3) + Filter: ((chat_id = '31d92451-4a01-41f6-89ce-cdeedc71f887'::uuid) AND (ROW(created_at, id) > ROW('2026-10-02 01:18:47.043523+00'::timestamp with time zone, '83f8e35a-40fb-4624-9f15-e60f4b907f7b'::uuid))) + Rows Removed by Filter: 41967 + Buffers: shared hit=3767 +Planning: + Buffers: shared hit=17 +Planning Time: 0.104 ms +Execution Time: 6.147 ms diff --git a/evidence/bench/t2-keyset/explain-tiny-10.txt b/evidence/bench/t2-keyset/explain-tiny-10.txt new file mode 100644 index 00000000..1d8dc10f --- /dev/null +++ b/evidence/bench/t2-keyset/explain-tiny-10.txt @@ -0,0 +1,78 @@ +# План запроса истории: класс tiny, чат 10 + +Код: src_sha256 8a7e256c540af433, commit 6d2240ce9fec; вариант индекса: keyset +Страница истории читаемого чата (limit 50); позиция — сколько +сообщений истории до страницы: +- first: после 0 + +## Планы приложения + +auto_explain (ANALYZE, BUFFERS, TIMING): запрос, параметры и план, +с которыми его выполнило приложение (prepared statement asyncpg). + +### first + +duration: 0.052 ms plan: +Query Text: SELECT messages.id, messages.chat_id, messages.sender_id, messages.text, messages.created_at +FROM messages +WHERE messages.chat_id = $1::UUID ORDER BY messages.created_at, messages.id + LIMIT $2::INTEGER +Query Parameters: $1 = '961fcc42-545b-4f88-bf41-c6bae3507eb7', $2 = '51' +Limit (cost=73.42..73.47 rows=18 width=204) (actual time=0.048..0.049 rows=10.00 loops=1) + Buffers: shared hit=19 + -> Sort (cost=73.42..73.47 rows=18 width=204) (actual time=0.048..0.048 rows=10.00 loops=1) + Sort Key: created_at, id + Sort Method: quicksort Memory: 27kB + Buffers: shared hit=19 + -> Bitmap Heap Scan on messages (cost=4.56..73.05 rows=18 width=204) (actual time=0.012..0.019 rows=10.00 loops=1) + Recheck Cond: (chat_id = '961fcc42-545b-4f88-bf41-c6bae3507eb7'::uuid) + Heap Blocks: exact=10 + Buffers: shared hit=13 + -> Bitmap Index Scan on ix_messages_chat_id_created_at_id (cost=0.00..4.55 rows=18 width=0) (actual time=0.006..0.006 rows=10.00 loops=1) + Index Cond: (chat_id = '961fcc42-545b-4f88-bf41-c6bae3507eb7'::uuid) + Index Searches: 1 + Buffers: shared hit=3 + +## Страница first в psql: с индексом и без + +Тот же текст запроса и те же параметры, что у плана first. +psql планирует их заново (custom plan). DROP INDEX — внутри +транзакции, затем ROLLBACK: индекс остаётся в базе. + +### С индексом ix_messages_chat_id_created_at_id + +Limit (cost=73.42..73.47 rows=18 width=204) (actual time=0.158..0.162 rows=10.00 loops=1) + Buffers: shared hit=19 + -> Sort (cost=73.42..73.47 rows=18 width=204) (actual time=0.156..0.157 rows=10.00 loops=1) + Sort Key: created_at, id + Sort Method: quicksort Memory: 27kB + Buffers: shared hit=19 + -> Bitmap Heap Scan on messages (cost=4.56..73.05 rows=18 width=204) (actual time=0.058..0.130 rows=10.00 loops=1) + Recheck Cond: (chat_id = '961fcc42-545b-4f88-bf41-c6bae3507eb7'::uuid) + Heap Blocks: exact=10 + Buffers: shared hit=13 + -> Bitmap Index Scan on ix_messages_chat_id_created_at_id (cost=0.00..4.55 rows=18 width=0) (actual time=0.034..0.034 rows=10.00 loops=1) + Index Cond: (chat_id = '961fcc42-545b-4f88-bf41-c6bae3507eb7'::uuid) + Index Searches: 1 + Buffers: shared hit=3 +Planning: + Buffers: shared hit=142 +Planning Time: 0.423 ms +Execution Time: 0.197 ms + +### Без индекса ix_messages_chat_id_created_at_id + +Limit (cost=5342.38..5342.42 rows=18 width=204) (actual time=20.430..20.432 rows=10.00 loops=1) + Buffers: shared hit=3767 + -> Sort (cost=5342.38..5342.42 rows=18 width=204) (actual time=20.429..20.430 rows=10.00 loops=1) + Sort Key: created_at, id + Sort Method: quicksort Memory: 27kB + Buffers: shared hit=3767 + -> Seq Scan on messages (cost=0.00..5342.00 rows=18 width=204) (actual time=2.625..20.418 rows=10.00 loops=1) + Filter: (chat_id = '961fcc42-545b-4f88-bf41-c6bae3507eb7'::uuid) + Rows Removed by Filter: 125990 + Buffers: shared hit=3767 +Planning: + Buffers: shared hit=17 +Planning Time: 0.118 ms +Execution Time: 20.451 ms diff --git a/evidence/bench/t2-keyset/fill.csv b/evidence/bench/t2-keyset/fill.csv new file mode 100644 index 00000000..9e84ae11 --- /dev/null +++ b/evidence/bench/t2-keyset/fill.csv @@ -0,0 +1,6 @@ +size,messages_total,rps,p50_ms,p99_ms,max_ms,rss_mib,app_cpu_cores,db_cpu_cores +126000,25200,1127.49,13.1728,30.5665,211.2425,91.6,0.997,0.274 +126000,50400,1110.39,13.536,27.7127,78.4609,98.4,0.992,0.271 +126000,75600,1141.39,13.0509,28.0257,79.8002,99.9,1.0,0.281 +126000,100800,1148.4,12.921,30.4885,92.0836,100.2,1.0,0.29 +126000,126000,1188.31,12.7997,24.8541,95.4848,100.8,1.0,0.289 diff --git a/evidence/bench/t2-keyset/memory.csv b/evidence/bench/t2-keyset/memory.csv new file mode 100644 index 00000000..484e94ba --- /dev/null +++ b/evidence/bench/t2-keyset/memory.csv @@ -0,0 +1,2 @@ +size,rss_empty_mib,rss_filled_mib,rss_peak_mib,oom_killed,messages_rows,table_bytes,indexes_bytes,db_bytes_per_message +126000,81.1,100.8,144.1,False,126000,30900224,17620992,385 diff --git a/evidence/bench/t2-keyset/meta.json b/evidence/bench/t2-keyset/meta.json new file mode 100644 index 00000000..4724afce --- /dev/null +++ b/evidence/bench/t2-keyset/meta.json @@ -0,0 +1,407 @@ +{ + "label": "t2-keyset", + "started_utc": "2026-10-02T01:17:32Z", + "profile": { + "name": "skew", + "sizes": [ + 126000 + ], + "clients": [ + 1, + 8, + 32 + ], + "repeats": 3, + "read_warmup_s": 2.0, + "read_duration_s": 6.0, + "write_warmup_requests": 300, + "write_requests": 3000, + "fill_clients": 16, + "fill_batch_max": 50000, + "fill_batches_min": 5, + "cursor_pool": 200, + "gen_procs": 4, + "seed": 20261002, + "app_cpus": "1", + "app_memory": "1g", + "db_cpus": "2", + "db_memory": "2g", + "cache_cpus": "1", + "cache_memory": "256m", + "session_ttl": 21600, + "gen_cpu_flag": 0.8, + "classes": [ + [ + "big", + 1, + 60000 + ], + [ + "medium", + 6, + 6000 + ], + [ + "small", + 120, + 200 + ], + [ + "tiny", + 600, + 10 + ] + ], + "explain_cursor_version": 2 + }, + "host": { + "platform": "macOS-26.6.2-arm64-arm-64bit-Mach-O", + "machine": "arm64", + "cpu_model": "Apple M4", + "cpu_count": 10, + "ram_gb": 16.0, + "swap_used_mib": 0.0, + "power": "AC Power", + "loadavg_1m": 1.72 + }, + "docker": { + "ServerVersion": "28.0.4", + "OperatingSystem": "Docker Desktop", + "KernelVersion": "6.10.14-linuxkit", + "Architecture": "aarch64", + "NCPU": 10, + "MemTotal": 8218034176, + "CgroupVersion": "2", + "LoggingDriver": "json-file", + "other_running_containers": 0 + }, + "image": { + "tag": "mtusi-messenger-vladimirceva:bench-t2-keyset", + "id": "sha256:e670ace82a784e82a5fe617e6c60e3a651cea6c446be8c42bc586d2f359881d0", + "created": "2026-10-02T00:39:00.104485709Z", + "versions": { + "python": "3.13.15", + "fastapi": "0.142.1", + "starlette": "1.7.0", + "uvicorn": "0.54.0", + "pydantic": "2.13.5", + "sqlalchemy": "2.1.1", + "asyncpg": "0.31.0", + "alembic": "1.20.0", + "redis": "8.1.0", + "argon2-cffi": "25.1.0" + }, + "src_sha256": "8a7e256c540af433de47704437294adafd98dcfecf2f3200354454ee717cd2a3" + }, + "image_reused": false, + "code": { + "src_sha256": "8a7e256c540af433de47704437294adafd98dcfecf2f3200354454ee717cd2a3", + "git_commit": "6d2240ce9fec2531f8141e1331db37d36388d082", + "git_dirty": false + }, + "generator_image": "python:3.13.15-slim-trixie@sha256:7c61056e61ac89e852de05f3dc6fa51a6dd2181797bceed46aa725dd7cb2cd3b", + "variant": "keyset", + "variant_sql": [], + "host_warnings": [], + "stand": { + "postgres": { + "image": "postgres:18.6-trixie@sha256:5a5a84b19854a9ffaa54082c166ff4ec27473a361e496e5ea167f298f2da9722", + "version": "18.6 (Debian 18.6-1.pgdg13+2)", + "settings": { + "autovacuum": "on", + "checkpoint_timeout": "5min", + "effective_cache_size": "4GB", + "fsync": "on", + "jit": "on", + "maintenance_work_mem": "64MB", + "max_connections": "100", + "max_wal_size": "1GB", + "plan_cache_mode": "auto", + "random_page_cost": "4", + "shared_buffers": "128MB", + "shared_preload_libraries": "auto_explain", + "synchronous_commit": "on", + "wal_level": "replica", + "work_mem": "4MB" + } + }, + "valkey": { + "image": "valkey/valkey:9.1.2-trixie@sha256:418652cfb58ef879d4978c33553735d7147016032d5aefaa14c828e611eb9dfd", + "version": "9.1.2", + "maxmemory": "67108864", + "maxmemory-clients": "0", + "maxmemory-eviction-tenacity": "10", + "maxmemory-policy": "allkeys-lru", + "maxmemory-samples": "5" + }, + "limits": { + "api": { + "nano_cpus": 1000000000, + "memory": 1073741824, + "memory_swap": 1073741824, + "published_ports": {} + }, + "postgres": { + "nano_cpus": 2000000000, + "memory": 2147483648, + "memory_swap": 2147483648, + "published_ports": {} + }, + "valkey": { + "nano_cpus": 1000000000, + "memory": 268435456, + "memory_swap": 268435456, + "published_ports": {} + } + }, + "app_env": { + "CACHE_HOST": "valkey", + "CACHE_PORT": "6379", + "DB_HOST": "postgres", + "DB_NAME": "bench", + "DB_PORT": "5432", + "DB_USER": "bench", + "LOG_LEVEL": "INFO", + "SESSION_TTL_SECONDS": "21600", + "SHUTDOWN_TIMEOUT": "5" + } + }, + "finished_utc": "2026-10-02T01:25:57Z", + "duration_s": 506, + "plans": [ + { + "size": 60000, + "chat_class": "big", + "page": "first", + "after": 0, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 31, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.049, + "kind": "custom" + }, + { + "size": 60000, + "chat_class": "big", + "page": "middle", + "after": 30000, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 54, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.05, + "kind": "generic" + }, + { + "size": 60000, + "chat_class": "big", + "page": "last", + "after": 59950, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 53, + "shared_read": 0, + "rows": 50.0, + "time_ms": 0.057, + "kind": "generic" + }, + { + "size": 60000, + "chat_class": "big", + "page": "middle", + "after": 30000, + "source": "psql", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 54, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.092, + "kind": "custom" + }, + { + "size": 60000, + "chat_class": "big", + "page": "middle", + "after": 30000, + "source": "psql, no index", + "node": "Parallel Seq Scan on messages", + "shared_hit": 3797, + "shared_read": 0, + "rows": 51.0, + "time_ms": 6.628, + "kind": "custom" + }, + { + "size": 6000, + "chat_class": "medium", + "page": "first", + "after": 0, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 47, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.057, + "kind": "custom" + }, + { + "size": 6000, + "chat_class": "medium", + "page": "middle", + "after": 3000, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 50, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.052, + "kind": "generic" + }, + { + "size": 6000, + "chat_class": "medium", + "page": "last", + "after": 5950, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 52, + "shared_read": 0, + "rows": 50.0, + "time_ms": 0.05, + "kind": "generic" + }, + { + "size": 6000, + "chat_class": "medium", + "page": "middle", + "after": 3000, + "source": "psql", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 50, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.145, + "kind": "custom" + }, + { + "size": 6000, + "chat_class": "medium", + "page": "middle", + "after": 3000, + "source": "psql, no index", + "node": "Parallel Seq Scan on messages", + "shared_hit": 3797, + "shared_read": 0, + "rows": 51.0, + "time_ms": 6.032, + "kind": "custom" + }, + { + "size": 200, + "chat_class": "small", + "page": "first", + "after": 0, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 54, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.096, + "kind": "custom" + }, + { + "size": 200, + "chat_class": "small", + "page": "middle", + "after": 100, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 54, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.079, + "kind": "generic" + }, + { + "size": 200, + "chat_class": "small", + "page": "last", + "after": 150, + "source": "app", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 52, + "shared_read": 0, + "rows": 50.0, + "time_ms": 0.062, + "kind": "generic" + }, + { + "size": 200, + "chat_class": "small", + "page": "middle", + "after": 100, + "source": "psql", + "node": "Index Scan using ix_messages_chat_id_created_at_id on messages", + "shared_hit": 54, + "shared_read": 0, + "rows": 51.0, + "time_ms": 0.307, + "kind": "custom" + }, + { + "size": 200, + "chat_class": "small", + "page": "middle", + "after": 100, + "source": "psql, no index", + "node": "Parallel Seq Scan on messages", + "shared_hit": 3797, + "shared_read": 0, + "rows": 51.0, + "time_ms": 6.147, + "kind": "custom" + }, + { + "size": 10, + "chat_class": "tiny", + "page": "first", + "after": 0, + "source": "app", + "node": "Bitmap Heap Scan on messages", + "shared_hit": 19, + "shared_read": 0, + "rows": 10.0, + "time_ms": 0.052, + "kind": "custom" + }, + { + "size": 10, + "chat_class": "tiny", + "page": "first", + "after": 0, + "source": "psql", + "node": "Bitmap Heap Scan on messages", + "shared_hit": 19, + "shared_read": 0, + "rows": 10.0, + "time_ms": 0.197, + "kind": "custom" + }, + { + "size": 10, + "chat_class": "tiny", + "page": "first", + "after": 0, + "source": "psql, no index", + "node": "Seq Scan on messages", + "shared_hit": 3767, + "shared_read": 0, + "rows": 10.0, + "time_ms": 20.451, + "kind": "custom" + } + ] +} diff --git a/evidence/bench/t2-keyset/runs.csv b/evidence/bench/t2-keyset/runs.csv new file mode 100644 index 00000000..ce55e546 --- /dev/null +++ b/evidence/bench/t2-keyset/runs.csv @@ -0,0 +1,46 @@ +scenario,size,clients,repeat,requests,errors,rps,p50_ms,p90_ms,p95_ms,p99_ms,max_ms,mean_ms,cpu_us_per_req,app_cpu_cores,rss_mib,store_messages_start,gen_cpu_cores,window_s,flags,db_cpu_cores,db_cpu_us_per_req,chat_class +read,60000,1,1,3635,0,605.92,1.6361,1.7363,1.7843,1.9998,8.7268,1.6489,1299.5,0.788,100.8,126000,0.022,5.9991,,0.146,240.4,big +read,60000,8,1,5491,0,914.41,8.6545,9.0965,9.322,10.4381,25.5825,8.7387,1095.6,1.0,100.9,126000,0.038,6.005,,0.213,233.2,big +read,60000,32,1,5388,0,895.0,33.4682,42.4072,47.8623,54.4352,65.955,35.5809,1121.4,1.001,102.2,126000,0.039,6.0201,,0.233,260.6,big +read,60000,1,2,3598,0,599.67,1.6623,1.7441,1.7679,1.9507,4.5463,1.6659,1317.9,0.789,102.2,126000,0.023,6.0,,0.144,239.9,big +read,60000,8,2,5590,0,930.85,8.5617,8.9,9.0564,9.711,24.842,8.5854,1081.1,1.0,102.2,126000,0.038,6.0052,,0.214,231.0,big +read,60000,32,2,5478,0,909.84,33.1334,40.7664,46.7033,54.1685,79.0027,35.0321,1116.1,1.0,102.3,126000,0.038,6.0208,,0.233,260.1,big +read,60000,1,3,3587,0,597.9,1.6653,1.7426,1.7669,1.9116,17.1414,1.6708,1330.7,0.79,102.3,126000,0.024,5.9994,,0.145,243.7,big +read,60000,8,3,5533,0,921.52,8.6293,9.004,9.1676,10.0715,23.8989,8.6709,1086.7,1.0,102.4,126000,0.038,6.0042,,0.209,227.7,big +read,60000,32,3,5347,0,888.18,33.471,43.4453,48.4996,60.7208,71.6312,35.8652,1128.9,1.001,102.4,126000,0.039,6.0201,,0.232,261.5,big +read,6000,1,1,3543,0,590.51,1.679,1.7757,1.8344,2.0006,7.9614,1.692,1336.7,0.788,102.4,126000,0.023,5.9999,,0.146,247.3,medium +read,6000,8,1,5492,0,914.77,8.6297,9.0775,9.3031,10.9082,25.0815,8.7388,1089.9,0.999,102.4,126000,0.038,6.0037,,0.215,234.6,medium +read,6000,32,1,5375,0,892.72,33.5095,42.186,48.2212,55.3109,76.1497,35.6391,1136.5,1.0,102.4,126000,0.04,6.0209,,0.243,276.0,medium +read,6000,1,2,3561,0,593.44,1.6733,1.7549,1.8032,2.0635,5.4067,1.6836,1333.2,0.787,102.4,126000,0.022,6.0006,,0.148,250.5,medium +read,6000,8,2,5520,0,919.19,8.6171,9.0319,9.19,10.4507,24.3938,8.6925,1090.1,1.0,102.4,126000,0.038,6.0053,,0.213,231.8,medium +read,6000,32,2,5404,0,897.37,33.303,42.6128,47.6653,55.9369,71.3768,35.5118,1121.1,1.0,102.4,126000,0.039,6.022,,0.242,271.7,medium +read,6000,1,3,3557,0,592.81,1.6806,1.762,1.7868,1.9435,6.5906,1.6853,1333.3,0.788,102.3,126000,0.023,6.0002,,0.147,248.1,medium +read,6000,8,3,5502,0,916.24,8.661,9.0479,9.2039,9.8083,25.5935,8.7188,1101.9,1.001,102.3,126000,0.038,6.005,,0.213,234.0,medium +read,6000,32,3,5346,0,885.5,33.4901,44.293,49.1993,56.967,69.1908,35.9932,1140.9,1.001,103.2,126000,0.038,6.0372,,0.245,279.5,medium +read,200,1,1,3580,0,596.67,1.673,1.7479,1.7779,1.965,2.7814,1.6746,1329.1,0.788,103.2,126000,0.022,6.0,,0.146,246.5,small +read,200,8,1,5602,0,933.02,8.4492,8.8281,9.0097,10.3097,29.1206,8.5634,1077.7,1.0,103.3,126000,0.038,6.0041,,0.211,227.5,small +read,200,32,1,5434,0,901.9,32.9664,42.5931,47.4153,55.3106,66.6295,35.3045,1110.8,0.998,103.3,126000,0.039,6.025,,0.233,258.8,small +read,200,1,2,3582,0,597.09,1.6621,1.7388,1.771,1.9914,17.0477,1.6733,1319.9,0.788,103.2,126000,0.023,5.999,,0.145,243.7,small +read,200,8,2,5564,0,926.67,8.532,8.9619,9.1762,10.3219,25.5297,8.6251,1077.3,1.0,103.2,126000,0.038,6.0043,,0.209,225.0,small +read,200,32,2,5408,0,898.13,33.0064,42.5259,48.3505,61.4885,85.139,35.471,1115.4,1.0,103.3,126000,0.039,6.0214,,0.234,260.6,small +read,200,1,3,3547,0,591.26,1.6776,1.7659,1.8252,2.1619,7.6421,1.69,1330.0,0.789,103.2,126000,0.022,5.9991,,0.146,246.2,small +read,200,8,3,5298,0,882.19,8.7048,9.9586,10.8163,14.3773,28.4992,9.0547,1121.2,0.999,103.2,126000,0.041,6.0055,,0.215,241.4,small +read,200,32,3,5497,0,910.38,32.7617,41.0072,46.7642,55.8624,75.0524,34.9195,1103.6,0.999,103.2,126000,0.039,6.0382,,0.232,256.1,small +read,10,1,1,4093,0,682.14,1.459,1.5303,1.5552,1.8517,6.5423,1.4652,1123.3,0.767,103.1,126000,0.024,6.0003,,0.155,226.8,tiny +read,10,8,1,7104,0,1184.38,6.7421,7.0288,7.118,7.3463,13.5083,6.7513,845.3,1.0,103.1,126000,0.043,5.9981,,0.244,206.5,tiny +read,10,32,1,7415,0,1232.38,25.0927,28.5423,28.9322,31.1779,46.4523,25.8858,821.6,1.001,103.1,126000,0.046,6.0168,,0.259,212.3,tiny +read,10,1,2,4113,0,685.53,1.458,1.5227,1.5384,1.6272,2.674,1.458,1118.9,0.763,103.1,126000,0.024,5.9998,,0.155,227.1,tiny +read,10,8,2,6949,0,1157.38,6.8804,7.2262,7.3426,7.8158,18.0649,6.9068,860.1,0.999,103.1,126000,0.042,6.0041,,0.238,205.0,tiny +read,10,32,2,7318,0,1216.66,25.4285,28.9237,29.3392,32.3738,47.2313,26.2236,829.8,1.001,103.1,126000,0.045,6.0148,,0.257,213.4,tiny +read,10,1,3,4105,0,684.12,1.4566,1.5256,1.5472,1.6646,5.9525,1.461,1123.3,0.765,103.1,126000,0.024,6.0004,,0.153,224.8,tiny +read,10,8,3,6955,0,1158.48,6.8585,7.1662,7.2853,8.2755,18.3891,6.9007,867.1,0.995,103.1,126000,0.041,6.0036,,0.238,207.4,tiny +read,10,32,3,7291,0,1211.86,25.395,28.9254,29.3766,40.8452,50.1053,26.3121,832.1,1.0,103.2,126000,0.045,6.0164,,0.255,212.2,tiny +write,126000,1,1,3000,0,790.7,1.2438,1.3527,1.4076,1.5697,4.2474,1.2637,957.6,0.747,103.2,126000,0.028,3.7941,,0.168,215.6, +write,126000,8,1,3000,0,1275.73,6.198,6.5754,6.7297,7.9128,15.5132,6.2572,793.9,1.002,103.1,129300,0.049,2.3516,,0.296,234.7, +write,126000,32,1,3000,0,1276.08,24.2559,28.6143,29.3222,33.9861,53.534,24.8426,803.0,1.001,103.2,132600,0.046,2.351,,0.298,238.8, +write,126000,1,2,3000,0,799.71,1.2302,1.2861,1.3147,1.5598,12.8742,1.2496,951.5,0.755,103.2,135900,0.027,3.7514,,0.171,215.5, +write,126000,8,2,3000,0,1319.02,6.0438,6.312,6.3975,6.5724,6.8692,6.0493,769.7,1.004,103.2,139200,0.048,2.2744,,0.296,227.1, +write,126000,32,2,3000,0,1256.94,24.4551,29.0806,31.466,41.1547,49.7541,25.2442,812.1,1.0,103.2,142500,0.046,2.3868,,0.303,246.4, +write,126000,1,3,3000,0,805.91,1.2248,1.2715,1.29,1.4855,8.4905,1.24,951.5,0.76,103.2,145800,0.027,3.7225,,0.168,210.9, +write,126000,8,3,3000,0,1304.95,6.0904,6.3867,6.4953,7.2692,9.2892,6.1156,772.7,0.997,103.2,149100,0.048,2.2989,,0.294,227.5, +write,126000,32,3,3000,0,1238.32,24.8169,29.5286,30.533,39.2773,66.1514,25.5341,830.3,1.006,103.2,152400,0.047,2.4226,,0.301,248.6, diff --git a/evidence/bench/t2-keyset/summary.md b/evidence/bench/t2-keyset/summary.md new file mode 100644 index 00000000..b68a982a --- /dev/null +++ b/evidence/bench/t2-keyset/summary.md @@ -0,0 +1,83 @@ +# Стенд: метка `t2-keyset` + +- Снято: 2026-10-02T01:17:32Z — 2026-10-02T01:25:57Z (506 с), профиль `skew`, вариант индекса `keyset` +- Хост: Apple M4, 10 CPU, 16.0 ГБ, macOS-26.6.2-arm64-arm-64bit-Mach-O; питание: AC Power, swap: 0.0 МиБ +- Docker: 28.0.4 (Docker Desktop), 10 CPU, 7.7 ГБ, cgroup v2; посторонних контейнеров: 0 +- Образ: `mtusi-messenger-vladimirceva:bench-t2-keyset` (e670ace82a78), python 3.13.15, fastapi 0.142.1, starlette 1.7.0, uvicorn 0.54.0, pydantic 2.13.5, sqlalchemy 2.1.1, asyncpg 0.31.0, alembic 1.20.0, redis 8.1.0, argon2-cffi 25.1.0 +- Код: src_sha256 `8a7e256c540af433`, commit `6d2240ce9fec` +- Лимиты: API `--cpus=1 --memory=1g`, PostgreSQL `2 CPU / 2g`, Valkey `1 CPU / 256m`, без swap; API без healthcheck, порты не публикуются +- PostgreSQL: 18.6 (Debian 18.6-1.pgdg13+2), shared_buffers 128MB, настройки образа + auto_explain (выключен вне этапа плана); свежий volume на каждый размер; после наполнения VACUUM (ANALYZE) и CHECKPOINT +- Генератор: `bench/loadgen.py` в той же docker-сети, образ `python:3.13.15-slim-trixie`, до 4 процессов; вход по Basic, запросы с Bearer +- Чтение: 6.0 с после 2.0 с прогрева, страница limit=50 со случайным курсором пула; запись: 3000 запросов после 300 прогрева в отдельный чат; повторов: 3 +- Чаты: big — 1 × 60k, medium — 6 × 6k, small — 120 × 200, tiny — 600 × 10; наполнение по перемешанному плану (сообщения чатов чередуются), читается первый чат класса, страницы — все, включая неполные + + +Значения — медиана повторов, в скобках min–max. + +## Чтение: `GET .../messages?limit=50&cursor=...` + +| История | Клиенты | RPS | p50, мс | p95, мс | p99, мс | CPU API, мкс/запрос | CPU API, ядер | CPU БД, ядер | CPU БД, мкс/запрос | Пометки | +|---|---|---|---|---|---|---|---|---|---|---| +| 10 (tiny) | 1 | 684 (682–686) | 1.46 (1.46–1.46) | 1.55 (1.54–1.56) | 1.66 (1.63–1.85) | 1123 (1119–1123) | 0.77 (0.76–0.77) | 0.15 (0.15–0.15) | 227 (225–227) | — | +| 10 (tiny) | 8 | 1158 (1157–1184) | 6.86 (6.74–6.88) | 7.29 (7.12–7.34) | 7.82 (7.35–8.28) | 860 (845–867) | 1.00 (0.99–1.00) | 0.24 (0.24–0.24) | 206 (205–207) | — | +| 10 (tiny) | 32 | 1217 (1212–1232) | 25.39 (25.09–25.43) | 29.34 (28.93–29.38) | 32.37 (31.18–40.85) | 830 (822–832) | 1.00 (1.00–1.00) | 0.26 (0.26–0.26) | 212 (212–213) | — | +| 200 (small) | 1 | 597 (591–597) | 1.67 (1.66–1.68) | 1.78 (1.77–1.83) | 1.99 (1.97–2.16) | 1329 (1320–1330) | 0.79 (0.79–0.79) | 0.15 (0.14–0.15) | 246 (244–246) | — | +| 200 (small) | 8 | 927 (882–933) | 8.53 (8.45–8.70) | 9.18 (9.01–10.82) | 10.32 (10.31–14.38) | 1078 (1077–1121) | 1.00 (1.00–1.00) | 0.21 (0.21–0.21) | 228 (225–241) | — | +| 200 (small) | 32 | 902 (898–910) | 32.97 (32.76–33.01) | 47.42 (46.76–48.35) | 55.86 (55.31–61.49) | 1111 (1104–1115) | 1.00 (1.00–1.00) | 0.23 (0.23–0.23) | 259 (256–261) | — | +| 6k (medium) | 1 | 593 (591–593) | 1.68 (1.67–1.68) | 1.80 (1.79–1.83) | 2.00 (1.94–2.06) | 1333 (1333–1337) | 0.79 (0.79–0.79) | 0.15 (0.15–0.15) | 248 (247–250) | — | +| 6k (medium) | 8 | 916 (915–919) | 8.63 (8.62–8.66) | 9.20 (9.19–9.30) | 10.45 (9.81–10.91) | 1090 (1090–1102) | 1.00 (1.00–1.00) | 0.21 (0.21–0.21) | 234 (232–235) | — | +| 6k (medium) | 32 | 893 (886–897) | 33.49 (33.30–33.51) | 48.22 (47.67–49.20) | 55.94 (55.31–56.97) | 1136 (1121–1141) | 1.00 (1.00–1.00) | 0.24 (0.24–0.24) | 276 (272–280) | — | +| 60k (big) | 1 | 600 (598–606) | 1.66 (1.64–1.67) | 1.77 (1.77–1.78) | 1.95 (1.91–2.00) | 1318 (1300–1331) | 0.79 (0.79–0.79) | 0.14 (0.14–0.15) | 240 (240–244) | — | +| 60k (big) | 8 | 922 (914–931) | 8.63 (8.56–8.65) | 9.17 (9.06–9.32) | 10.07 (9.71–10.44) | 1087 (1081–1096) | 1.00 (1.00–1.00) | 0.21 (0.21–0.21) | 231 (228–233) | — | +| 60k (big) | 32 | 895 (888–910) | 33.47 (33.13–33.47) | 47.86 (46.70–48.50) | 54.44 (54.17–60.72) | 1121 (1116–1129) | 1.00 (1.00–1.00) | 0.23 (0.23–0.23) | 261 (260–262) | — | + +## Запись: `POST .../messages` в отдельный чат + +| История | Клиенты | RPS | p50, мс | p95, мс | p99, мс | CPU API, мкс/запрос | CPU API, ядер | CPU БД, ядер | CPU БД, мкс/запрос | Пометки | +|---|---|---|---|---|---|---|---|---|---|---| +| 126k | 1 | 800 (791–806) | 1.23 (1.22–1.24) | 1.31 (1.29–1.41) | 1.56 (1.49–1.57) | 952 (952–958) | 0.76 (0.75–0.76) | 0.17 (0.17–0.17) | 216 (211–216) | — | +| 126k | 8 | 1305 (1276–1319) | 6.09 (6.04–6.20) | 6.50 (6.40–6.73) | 7.27 (6.57–7.91) | 773 (770–794) | 1.00 (1.00–1.00) | 0.30 (0.29–0.30) | 228 (227–235) | — | +| 126k | 32 | 1257 (1238–1276) | 24.46 (24.26–24.82) | 30.53 (29.32–31.47) | 39.28 (33.99–41.15) | 812 (803–830) | 1.00 (1.00–1.01) | 0.30 (0.30–0.30) | 246 (239–249) | — | + +## Планы запроса истории + +Страница истории читаемого чата (limit 50). `app` — план, с которым запрос выполнило приложение (auto_explain); `psql` — тот же текст и параметры средней (у маленького чата — первой) страницы, с индексом и без него (DROP INDEX в откатываемой транзакции). Полностью — `explain-*.txt`. + +| История | Страница | После | Источник | Узел | shared hit | read | Строк | Время, мс | План | +|---|---|---|---|---|---|---|---|---|---| +| 60k (big) | first | 0 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 31 | 0 | 51.0 | 0.049 | custom | +| 60k (big) | middle | 30000 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 54 | 0 | 51.0 | 0.05 | generic | +| 60k (big) | last | 59950 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 53 | 0 | 50.0 | 0.057 | generic | +| 60k (big) | middle | 30000 | psql | Index Scan using ix_messages_chat_id_created_at_id on messages | 54 | 0 | 51.0 | 0.092 | custom | +| 60k (big) | middle | 30000 | psql, no index | Parallel Seq Scan on messages | 3797 | 0 | 51.0 | 6.628 | custom | +| 6k (medium) | first | 0 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 47 | 0 | 51.0 | 0.057 | custom | +| 6k (medium) | middle | 3000 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 50 | 0 | 51.0 | 0.052 | generic | +| 6k (medium) | last | 5950 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 52 | 0 | 50.0 | 0.05 | generic | +| 6k (medium) | middle | 3000 | psql | Index Scan using ix_messages_chat_id_created_at_id on messages | 50 | 0 | 51.0 | 0.145 | custom | +| 6k (medium) | middle | 3000 | psql, no index | Parallel Seq Scan on messages | 3797 | 0 | 51.0 | 6.032 | custom | +| 200 (small) | first | 0 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 54 | 0 | 51.0 | 0.096 | custom | +| 200 (small) | middle | 100 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 54 | 0 | 51.0 | 0.079 | generic | +| 200 (small) | last | 150 | app | Index Scan using ix_messages_chat_id_created_at_id on messages | 52 | 0 | 50.0 | 0.062 | generic | +| 200 (small) | middle | 100 | psql | Index Scan using ix_messages_chat_id_created_at_id on messages | 54 | 0 | 51.0 | 0.307 | custom | +| 200 (small) | middle | 100 | psql, no index | Parallel Seq Scan on messages | 3797 | 0 | 51.0 | 6.147 | custom | +| 10 (tiny) | first | 0 | app | Bitmap Heap Scan on messages | 19 | 0 | 10.0 | 0.052 | custom | +| 10 (tiny) | first | 0 | psql | Bitmap Heap Scan on messages | 19 | 0 | 10.0 | 0.197 | custom | +| 10 (tiny) | first | 0 | psql, no index | Seq Scan on messages | 3767 | 0 | 10.0 | 20.451 | custom | + +## Память и объём + +| История | RSS API пустой, МиБ | RSS API после наполнения, МиБ | Пик RSS, МиБ | OOM | Строк messages | Таблица, МиБ | Индексы, МиБ | Байт на сообщение в БД | +|---|---|---|---|---|---|---|---|---| +| 126k | 81.1 | 100.8 | 144.1 | нет | 126000 | 29.5 | 16.8 | 385 | + +## Наполнение истории (запись при росте таблицы) + +| Цель | Сообщений | RPS | p50, мс | p99, мс | max, мс | RSS, МиБ | CPU API | CPU БД | +|---|---|---|---|---|---|---|---|---| +| 126k | 25200 | 1127 | 13.17 | 30.57 | 211.2 | 91.6 | 0.997 | 0.274 | +| 126k | 50400 | 1110 | 13.54 | 27.71 | 78.5 | 98.4 | 0.992 | 0.271 | +| 126k | 75600 | 1141 | 13.05 | 28.03 | 79.8 | 99.9 | 1.0 | 0.281 | +| 126k | 100800 | 1148 | 12.92 | 30.49 | 92.1 | 100.2 | 1.0 | 0.29 | +| 126k | 126000 | 1188 | 12.80 | 24.85 | 95.5 | 100.8 | 1.0 | 0.289 | + +Пометки: `errors` — были неуспешные запросы; `generator` — генератор занял больше порога CPU на процесс, предел мог быть в нём; `short` — измерено меньше запросов, чем задано; `stand_down` — PostgreSQL или Valkey упали или перезапускались.