Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
config.local.json
|
||||
output/
|
||||
*.secret
|
||||
@@ -0,0 +1,230 @@
|
||||
# Проверки lab2 и заготовки исследований на 5
|
||||
|
||||
Для завершённого трека 2 используется отдельный воспроизводимый запуск:
|
||||
|
||||
```sh
|
||||
.venv/bin/python student-tests/lab2/research.py --output evidence/grade5-sql-NEW
|
||||
```
|
||||
|
||||
Из корня репозитория он сам собирает sqlprobe, создаёт два изолированных
|
||||
PostgreSQL/volumes с синтетическими credentials, выполняет сравнение AB/BA на
|
||||
100k сообщений, backup/restore и restart новой цели, затем удаляет свои ресурсы.
|
||||
Образ postgres:18 должен присутствовать локально. Требуются Docker, Go из
|
||||
go.mod и Python-окружение scripts/setup-tests.sh. Output должен быть новым.
|
||||
CSV и агрегаты таблиц из сохранённого indexes.json пересчитываются без нового
|
||||
измерения: `python3 student-tests/lab2/summarize_research.py <output-directory>`.
|
||||
Точный метод и проверенные результаты —
|
||||
[исследовательский отчёт](../../evidence/grade5-sql-2026-10-28-verified/REPORT.md).
|
||||
Общая регрессия API по-прежнему запускается через student-tests/stack.py verify.
|
||||
Режим sqlprobe compare и приведённые ниже отдельные hooks остаются прототипами
|
||||
и точками расширения, а не подменой полного исследовательского запуска.
|
||||
|
||||
Ниже — тесты и тестовые адаптеры. Код приложения, обязательный контракт,
|
||||
публичные tests/ и основной Compose не меняются. Переносимый runner и активный
|
||||
workflow Gitea описаны в [RUNNING.md](../RUNNING.md).
|
||||
Основание: [требования лабораторной](../../README.md), README/COURSE,
|
||||
contracts/README и OpenAPI преподавателя. Ожидаемые API-статусы и границы
|
||||
не подгоняются под текущие ответы сервера.
|
||||
|
||||
## Что уже можно запускать
|
||||
|
||||
Python 3.9+, стандартная библиотека. Для SQL-адаптера нужен Go с зависимостями
|
||||
проекта и доступ к явно выбранному тестовому PostgreSQL. Новых Go/Python
|
||||
зависимостей этот набор не добавляет.
|
||||
|
||||
~~~sh
|
||||
python3 student-tests/lab2/run.py --list
|
||||
python3 -m unittest discover -s student-tests/lab2 -p test_harness.py -v
|
||||
go test ./student-tests/lab2/sqlprobe -count=1
|
||||
|
||||
export LAB2_BASE_URL=http://127.0.0.1:8080
|
||||
python3 student-tests/lab2/run.py \
|
||||
--suite business-boundaries --suite business-cursors --suite read-after-write
|
||||
~~~
|
||||
|
||||
Команды HTTP создают синтетических пользователей, чаты и сообщения. Удаления
|
||||
через API нет, поэтому нужен отдельный учебный стенд. Бенчмарки не следует
|
||||
проводить на общей/production БД. Этот runner сам Docker-стенд не поднимает.
|
||||
|
||||
`business-cursors` проверяет отдельно историю сообщений и список чатов:
|
||||
обход GET /chats с limit=2, точный порядок/состав, отсутствие дублей и чужих
|
||||
объектов, чужой cursor, смену limit 1 → 100 и завершение списка.
|
||||
`business-boundaries` включает совместимые JSON/UTF-8 cases из
|
||||
validation_edges.py с регистрационным password и Bearer; тела запросов с
|
||||
паролем в отчёт не сохраняются. `read-after-write` проверяет 100 сообщений от
|
||||
10 участников с config.concurrency одновременными запросами (по умолчанию 4).
|
||||
|
||||
`PASS` означает прохождение выбранного сценария, `FAIL` — наблюдаемое нарушение,
|
||||
`BLOCKED` — нет конфигурации/адаптера/выбранного трека. Exit: 0/1/2 соответственно;
|
||||
FAIL имеет приоритет над BLOCKED. Без --suite ничего не запускается. Пустой
|
||||
config.example.json не выдаёт зелёный результат. Отсутствующие Redis и hooks
|
||||
также не засчитываются как успешная проверка.
|
||||
|
||||
## Матрица покрытия
|
||||
|
||||
| Блок чек-листа | Автоматические проверки | Где потребуется адаптация/ручное подтверждение |
|
||||
| --- | --- | --- |
|
||||
| 1. Auth и ошибки | auth, postgres-failure; существующие Go/auth_tests | Исправления приложения делает автор |
|
||||
| 2. Воспроизводимость | persistence, compose_action, пример CI | Реальный restart.sh, чистый clone, площадка CI |
|
||||
| 3. Реальный Redis/Valkey | cache-usage, cache-failure, cache-restart | Роль, адрес, namespace и metrics adapter |
|
||||
| 4. Бюджеты | query-timeout, pool-timeout | Настоящий SQL lock и насыщение APPLICATION pool |
|
||||
| 5. SQL ≥10k | sql-plan: реальный repository SQL, первая/глубокая страницы | Обоснование плана и бюджета чтения |
|
||||
| 6. Регрессия | business-*, read-after-write, auth/expiry/persistence/dependency | Политика конкурентных вставок и дополнительные крайние случаи |
|
||||
| 7A. Трек cache | cache-experiment + restart/read-after-write | Детерминированный baseline/protected, счётчики, повторы |
|
||||
| 7B. Трек SQL | sql-experiment, backup-restore, sqlprobe seed | Backup/restore adapters, ресурсы, интерпретация результатов |
|
||||
| 8. Сдача | Публичные make check/validate/test, образец application CI | REPORT/PR, источники/ИИ, commit, secrets, защита |
|
||||
|
||||
В отчёте, корректности экспериментального вывода и объяснении на защите
|
||||
нет достоверной автоматической замены. Заготовки не выставляют оценку 5.
|
||||
Это также не полный fuzz всех UUID/HTTP framing/JSON и вариантов 100 участников.
|
||||
Зелёные офлайн self-tests проверяют инструментарий, а не приложение.
|
||||
|
||||
## Конфигурация
|
||||
|
||||
Скопируй config.example.json в config.local.json (он игнорируется Git).
|
||||
Укажи base_url, expiry_base_url отдельного API с фактическим TTL=2,
|
||||
cache_policy (`critical`/`fallback`), cache_target (`history`/`chat`/`me`),
|
||||
track (`cache`/`sql`) и выбранные hooks. LAB2_BASE_URL/LAB2_EXPIRY_BASE_URL
|
||||
могут переопределять адреса. Пути команд hooks разрешаются относительно
|
||||
директории config-файла. Формат hook — массив argv, **shell не вызывается**.
|
||||
Не клади пароли/токены в argv или JSON: строки подключения передаются через env.
|
||||
|
||||
~~~sh
|
||||
python3 student-tests/lab2/run.py --config student-tests/lab2/config.local.json \
|
||||
--suite all --allow-hooks --output student-tests/lab2/output/full.json
|
||||
~~~
|
||||
|
||||
`all` выбирает общий уровень 3/4 и один указанный трек. При track=null он
|
||||
добавляет BLOCKED research-track; два исследовательских трека одновременно
|
||||
для оценки не требуются. Тяжёлые SQL-операции запускаются только выбранной
|
||||
suite и с явно переданной тестовой БД. Порог данных 10k/100k не уменьшается
|
||||
автоматически ради прохождения. Размер пула/таймаут в секундах и scan budget —
|
||||
выбранные инженерные параметры, а не магические числа из задания.
|
||||
|
||||
Существующие проверки не дублируются: auth, expiry, persistence и dependency
|
||||
используют student-tests/auth_contract.py и неизменённый teacher client.
|
||||
Публичный make test и Go tests остаются отдельными обязательными шагами.
|
||||
|
||||
## Договорённости hooks
|
||||
|
||||
Все hooks запускаются только с --allow-hooks и только после явной настройки.
|
||||
Обычный успешный hook возвращает 0; ещё не реализованный — 2 (BLOCKED).
|
||||
Остальные ошибки — FAIL. stdout/stderr инфраструктуры не копируются в отчёт.
|
||||
Recovery вызывается даже при частично неудавшемся failure hook; сам hook
|
||||
должен корректно завершаться и при повторном вызове. Восстановление и готовность
|
||||
обязательны. Уменьшение срока жизни сессии рестартом недопустимо.
|
||||
|
||||
- restart_stack: перезапустить API и ВСЕ используемые stores, сохранить volumes;
|
||||
прикладывать реальные started_at/volume до и после, а не no-op.
|
||||
- stop/start_postgres и stop/start/restart_cache: управлять только своим тестовым
|
||||
проектом. [compose_action.py](adapters/compose_action.py) — рабочий пример для
|
||||
именованных disposable проектов; параметры сервисов/Compose-файлов явные.
|
||||
Он не создаёт стенд и никогда не выполняет down -v или flush.
|
||||
- block_query/unblock_query: держать/снимать блокировку SQL, действительно
|
||||
мешающую запросу API. Например ACCESS EXCLUSIVE на нужной таблице в отдельной
|
||||
управляемой транзакции. Не блокировать готовую БД навсегда; иметь cleanup.
|
||||
- exhaust_pool/release_pool: занять ВСЕ соединения именно пула приложения.
|
||||
Несколько независимых psql-соединений не исчерпывают pgxpool приложения!
|
||||
- evict_cache: удалить только ключи своего синтетического namespace/fixture,
|
||||
не FLUSHALL. Должен гарантированно охлаждать выбранную cached operation.
|
||||
- metrics: один JSON stdout с **настоящими накопительными целочисленными**
|
||||
sql_queries/cache_hits. Runner измеряет delta; сброс счётчика — ошибка.
|
||||
Определи область счётчиков и исключи постороннюю нагрузку. Не выводи ключи,
|
||||
URL с credentials, username/password, токены или данные сообщений.
|
||||
- prepare_cache_baseline/protected: переключить реальное поведение baseline/
|
||||
защиты на том же workload и ресурсах, дождаться готовности. Одного вывода
|
||||
«защита включена» недостаточно.
|
||||
- backup_database/restore_database: настоящий backup и restore в явно указанный
|
||||
пустой целевой storage. Никакого восстановления поверх источника.
|
||||
|
||||
Заготовка собственного hook: [custom.example.py](adapters/custom.example.py).
|
||||
Она намеренно возвращает BLOCKED, пока ты не привяжешь её к реализации.
|
||||
Пример массива для Compose (пути относительно config.local.json):
|
||||
|
||||
~~~json
|
||||
["python3", "adapters/compose_action.py", "--project", "lab2-test-dev", "--file", "../../compose.yaml", "--file", "/path/to/test.override.yaml", "--evidence", "output/restarts.jsonl", "restart-stack"]
|
||||
~~~
|
||||
|
||||
В override должны быть собственные порты, secrets и volume тестового проекта.
|
||||
Остановка реальных рабочих сервисов не нужна для этих тестов.
|
||||
|
||||
## SQL-план и трек 2
|
||||
|
||||
LAB2_TEST_DATABASE_URL содержит DSN отдельной тестовой БД. В argv DSN не передаётся.
|
||||
Примеры ниже предполагают, что оператор уже безопасно задал эту env-переменную.
|
||||
|
||||
~~~sh
|
||||
python3 student-tests/lab2/run.py --suite sql-plan --output student-tests/lab2/output/plan.json
|
||||
python3 student-tests/lab2/run.py --suite sql-experiment --output student-tests/lab2/output/indexes.json
|
||||
~~~
|
||||
|
||||
SQL-адаптер создаёт свежую lab2_test_* схему, применяет реальные embedded Goose
|
||||
миграции, генерирует 10k/100k сообщений с распределением чатов 70/20/6/3/1%.
|
||||
Вызов существующего MessageRepository фиксирует реальный sqlc SQL и параметры;
|
||||
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) выполняется для первой и глубокой страниц.
|
||||
OFFSET используется только при выборе fixture cursor, не в измеряемом запросе.
|
||||
Бюджет учитывает строки, отфильтрованные под LIMIT, и Actual Loops; это эвристика
|
||||
настройки теста, а не замена прочтению самого плана. Generic prepared plans и
|
||||
другие распределения/состояния cache надо исследовать отдельно при необходимости.
|
||||
|
||||
compare меняет индексы ТОЛЬКО внутри своей свежей схемы: chat_id против
|
||||
(chat_id,created_at,id), фиксирует планы/размер индекса и p50/p95/p99 чтения и
|
||||
вставки 200 сообщений с COMMIT. Есть 3 warmup-запроса и заданное число повторов.
|
||||
Очистка вставок может оставить bloat; порядок вариантов и прогретость влияют
|
||||
на результат. Это исходная методика, которую нужно обосновать/повторить,
|
||||
а не гарантированное доказательство превосходства индекса. При обычном
|
||||
завершении схема удаляется; при SIGKILL может потребоваться ручная очистка
|
||||
только созданного тестового namespace. Сбой cleanup не считается PASS.
|
||||
|
||||
Для backup/restore нужен сохраняемый источник с 100k сообщений. Команда seed
|
||||
**явно оставляет** новую тестовую схему и сообщает её имя без DSN:
|
||||
|
||||
~~~sh
|
||||
# LAB2_SQL_DATABASE_URL — env выбранной тестовой БД, не строка в аргументах.
|
||||
go run ./student-tests/lab2/sqlprobe -mode seed -rows 100000 -schema lab2_test_backup_fixture
|
||||
~~~
|
||||
|
||||
Задай sql.source_schema/restore_schema этим именем, LAB2_TEST_DATABASE_URL
|
||||
источником, LAB2_RESTORED_DATABASE_URL новым целевым storage, подключи backup/
|
||||
restore hooks и запусти --suite backup-restore --allow-hooks. Перед тестом
|
||||
целевые application tables должны отсутствовать. Источник на время проверки
|
||||
должен быть без посторонних записей. Бэкап-файл не добавляется в Git/evidence.
|
||||
|
||||
snapshot использует read-only repeatable-read транзакцию и сравнивает количества
|
||||
и SHA-256 упорядоченного содержимого четырёх PostgreSQL-таблиц: users, chats,
|
||||
chat_members, messages. Сессии теперь в Redis; этот SQL backup не обещает их
|
||||
восстановления. Пароли/hash не печатаются: только агрегаты/digest. Состояние источника проверяется повторно;
|
||||
источник и цель должны иметь разные database identity. Это предохранители,
|
||||
но они не доказывают новый volume: приложи создание целевого storage и его scope.
|
||||
В отчёте отдельно объясни время восстановления и возможную потерю данных.
|
||||
|
||||
## Кэш и трек 1
|
||||
|
||||
Выбери cache_experiment.scenario = stale_read или stampede. Для stampede задай
|
||||
обоснованный max_protected_sql_queries с учётом auth и области метрик.
|
||||
Runner синхронизирует конкурентные чтения, измеряет SQL/cache-hit delta и
|
||||
latency до/после; для stale read требуется действительно увидеть отсутствие
|
||||
подтверждённого сообщения. Произвольная ошибка сети не засчитывается как stale read.
|
||||
Защита должна пройти read-after-write и restart cache. Переключение вариантов,
|
||||
scope метрик, размер/прогрев набора данных и повторы остаются частью методики.
|
||||
Под свою выбранную cached operation адаптируй cache_read/fixtures в одном месте.
|
||||
|
||||
## CI и ручная приёмка
|
||||
|
||||
[ci.application.example.yml](ci.application.example.yml) — неактивированный
|
||||
пример job: настоящая PostgreSQL, Go storage/migration tests без пропусков,
|
||||
сборка, миграции, HTTP smoke/business/auth и sql-plan. Redis и исследовательские
|
||||
hooks туда подключаются после выбора реализации. Файл размещён среди тестов;
|
||||
основной workflow не менялся. Для Gitea/GitLab используй эквивалент своей площадки.
|
||||
|
||||
Отдельно нужны REPORT.md/описание архитектуры и источников/ИИ, переносимый
|
||||
scripts/restart.sh, чистый clone, версии/ресурсы/commit, реальные доказательства
|
||||
действий hooks, отсутствие secrets в Git и объяснение результатов на защите.
|
||||
Рекомендации production (разделение ролей, secret manager и т.п.) не превращены
|
||||
здесь в новые обязательные критерии lab2. Результат тестов не заменяет эти пункты.
|
||||
# Переносимый запуск
|
||||
|
||||
Для текущего PostgreSQL/Redis/auth-набора есть готовый локальный и Gitea сценарий:
|
||||
[RUNNING.md](../RUNNING.md). Он поднимает отдельный стенд, выполняет проверки
|
||||
и очищает свои ресурсы. Заготовки исследования на 5 подключаются отдельно.
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit test-project restart/outage adapter. Never removes volumes/data."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--project", required=True)
|
||||
p.add_argument("--file", action="append", type=Path, required=True)
|
||||
p.add_argument("--api-service", default="api")
|
||||
p.add_argument("--database-service", default="postgres")
|
||||
p.add_argument("--cache-service", default="redis")
|
||||
p.add_argument("--evidence", type=Path)
|
||||
p.add_argument("action", choices=("restart-stack", "stop-db", "start-db", "stop-cache", "start-cache", "restart-cache"))
|
||||
args = p.parse_args()
|
||||
if not args.project.startswith(("lab2-test-", "highload-auth-retest-", "highload-lab2-test-")):
|
||||
print("Use an explicitly named disposable test project (lab2-test-*).", file=sys.stderr)
|
||||
return 2
|
||||
base = ["docker", "compose", "--project-name", args.project]
|
||||
for file in args.file:
|
||||
base.extend(("--file", str(file.resolve())))
|
||||
|
||||
def call(argv):
|
||||
result = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=70)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Docker action failed; output suppressed")
|
||||
return result.stdout
|
||||
|
||||
config = json.loads(call(base + ["config", "--format", "json"]))
|
||||
services = config["services"]
|
||||
stores = [args.database_service]
|
||||
if args.cache_service in services:
|
||||
stores.append(args.cache_service)
|
||||
elif "cache" in args.action:
|
||||
print("Cache service is not configured; adapt --cache-service.", file=sys.stderr)
|
||||
return 2
|
||||
targets = [args.api_service] + stores if args.action == "restart-stack" else [
|
||||
args.database_service if args.action.endswith("db") else args.cache_service]
|
||||
if any(name not in services for name in targets):
|
||||
return 2
|
||||
|
||||
def snapshot():
|
||||
result = {}
|
||||
for service in targets:
|
||||
ident = call(base + ["ps", "--all", "--quiet", service]).strip()
|
||||
if not ident or "\n" in ident:
|
||||
raise RuntimeError("expected one existing container per test service")
|
||||
raw = json.loads(call(["docker", "inspect", ident]))[0]
|
||||
if raw["Config"]["Labels"].get("com.docker.compose.project") != args.project:
|
||||
raise RuntimeError("container project mismatch")
|
||||
result[service] = {"id": ident, "started_at": raw["State"]["StartedAt"],
|
||||
"running": raw["State"]["Running"],
|
||||
"volumes": [mount["Name"] for mount in raw["Mounts"] if mount["Type"] == "volume"]}
|
||||
return result
|
||||
|
||||
before = snapshot()
|
||||
operation = "restart" if args.action.startswith("restart") else args.action.split("-")[0]
|
||||
call(base + [operation] + targets)
|
||||
proof = {"action": args.action, "project": args.project, "before": before, "after": snapshot()}
|
||||
if args.evidence:
|
||||
args.evidence.parent.mkdir(parents=True, exist_ok=True)
|
||||
with args.evidence.open("a") as output:
|
||||
output.write(json.dumps(proof) + "\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError):
|
||||
print("Test infrastructure action failed; private details suppressed.", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Copy and implement one explicit test adapter; never prints credentials."""
|
||||
import sys
|
||||
|
||||
# Expected metrics stdout: {"sql_queries": 1234, "cache_hits": 56}.
|
||||
# Counts must come from the real observed implementation, not constants here.
|
||||
# Other hooks: evict only this test namespace; hold/release a real SQL lock or
|
||||
# all APPLICATION pool connections; switch baseline/protected implementation;
|
||||
# back up the source and restore only to the explicitly empty test target.
|
||||
# See README.md for contracts and cleanup obligations. No destructive defaults.
|
||||
print("BLOCKED: implement the selected adapter for the chosen application/storage.", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded closed-loop HTTP latency matrix. Tokens stay only in memory."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
sys.path[:0]=[str(ROOT/'tests'),str(ROOT/'student-tests'),str(ROOT/'student-tests/lab2')]
|
||||
from client import Client,Failure
|
||||
from auth_contract import basic
|
||||
from resources import Sampler
|
||||
spec=importlib.util.spec_from_file_location('budget_harness',ROOT/'student-tests/lab2/run.py')
|
||||
harness=importlib.util.module_from_spec(spec);spec.loader.exec_module(harness)
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--base-url',required=True);p.add_argument('--output',type=Path,required=True)
|
||||
p.add_argument('--repeats',type=int,default=2);p.add_argument('--per-worker',type=int,default=3)
|
||||
p.add_argument('--history',type=int,default=1000);p.add_argument('--client-timeout',type=float,default=15)
|
||||
a=p.parse_args()
|
||||
if not 2<=a.repeats<=3 or not 2<=a.per_worker<=10 or not 1000<=a.history<=10000:p.error('bounded profile: repeats 2..3, per-worker 2..10, history 1000..10000')
|
||||
a.output.mkdir(parents=True,exist_ok=False)
|
||||
factory=lambda:Client(a.base_url,timeout=a.client_timeout)
|
||||
c=factory();actors=[c.user('bud'+uuid.uuid4().hex[:4]) for _ in range(10)]
|
||||
chat=c.call('POST','/api/v1/chats',201,actor=actors[0],body={'title':'Budget history','member_ids':[x['id'] for x in actors]},schema='Chat')['json']
|
||||
for index in range(a.history):c.message(actors[0],chat,'history fixture '+str(index)+' '+('x'*100))
|
||||
cursor=None
|
||||
traversed=set()
|
||||
for _ in range((a.history*8//10)//100):
|
||||
path='/api/v1/chats/'+chat['id']+'/messages?limit=100'+('&cursor='+cursor if cursor else '')
|
||||
page=c.call('GET',path,actor=actors[0],schema='MessagePage')['json']
|
||||
ids={m['id'] for m in page['items']}
|
||||
if traversed & ids:raise RuntimeError('deep fixture repeated a page')
|
||||
traversed.update(ids);cursor=page['next_cursor']
|
||||
if not cursor or len(traversed)!=((a.history*8//10)//100)*100:raise RuntimeError('deep-page fixture lacks correct cursor position')
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
names=['registration','login','me','create_chat','send_message','history_first','history_deep','logout']
|
||||
samples=[];phases=[];resource_errors={};resources={}
|
||||
samplers={}
|
||||
config=json.loads(os.environ.get('LAB2_RESOURCE_CONTAINERS','{}'))
|
||||
for role,entry in config.items():
|
||||
sampler=Sampler(entry['name'],1.0);samplers[role]=(sampler,entry['cpus']);sampler.thread.start()
|
||||
began=time.monotonic()
|
||||
try:
|
||||
for concurrency in [1,5,10]:
|
||||
# Logout credentials are prepared before measuring the logout phase;
|
||||
# preparation latency is not misreported as logout throughput.
|
||||
logout_tokens=[[] for _ in range(concurrency)]
|
||||
for worker in range(concurrency):
|
||||
actor=actors[worker]
|
||||
for _ in range(1+a.repeats*a.per_worker):
|
||||
session=c.call('POST','/api/v1/auth/sessions',201,headers=basic(actor['registration']['username'],actor['registration']['password']),schema='Session')['json']
|
||||
logout_tokens[worker].append(session['token'])
|
||||
for operation in names:
|
||||
for repeat in range(0,a.repeats+1):
|
||||
count=1 if repeat==0 else a.per_worker
|
||||
barrier=threading.Barrier(concurrency)
|
||||
phase_clients=[factory() for _ in range(concurrency)]
|
||||
def worker(number):
|
||||
local=phase_clients[number];actor=actors[number];records=[];barrier.wait(timeout=30)
|
||||
for request in range(count):
|
||||
start=time.monotonic();status=None;kind=None
|
||||
try:
|
||||
if operation=='registration':result=local.call('POST','/api/v1/users',201,body={'username':'budget_'+uuid.uuid4().hex[:20],'display_name':'Budget fixture','password':'Synthetic:password-for-measurement'},schema='User')
|
||||
elif operation=='login':result=local.call('POST','/api/v1/auth/sessions',201,headers=basic(actor['registration']['username'],actor['registration']['password']),schema='Session')
|
||||
elif operation=='me':result=local.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
elif operation=='create_chat':result=local.call('POST','/api/v1/chats',201,actor=actor,body={'title':'Unique '+uuid.uuid4().hex,'member_ids':[actor['id']]},schema='Chat')
|
||||
elif operation=='send_message':result=local.message(actor,chat,'Synthetic '+uuid.uuid4().hex+' '+('x'*80))
|
||||
elif operation=='history_first':result=local.call('GET',path+'?limit=50',actor=actor,schema='MessagePage')
|
||||
elif operation=='history_deep':result=local.call('GET',path+'?limit=50&cursor='+cursor,actor=actor,schema='MessagePage')
|
||||
else:result=local.call('DELETE','/api/v1/auth/sessions/current',204,actor=dict(actor,token=logout_tokens[number].pop()))
|
||||
status=result['status']
|
||||
except TimeoutError:kind='client_timeout'
|
||||
except Failure as exc:
|
||||
message=str(exc);match=re.search(r'received (\d+)',message)
|
||||
if match:status=int(match.group(1));kind='http_'+str(status)
|
||||
else:kind='client_timeout' if 'Timeout' in message else ('transport' if 'connection/TLS' in message else 'contract')
|
||||
except OSError:kind='transport'
|
||||
records.append({'operation':operation,'clients':concurrency,'repeat':repeat,'warmup':repeat==0,'worker':number,'request':request,'elapsed_ms':1000*(time.monotonic()-start),'status':status,'error':kind,'success':kind is None})
|
||||
return records
|
||||
start=time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
records=[row for group in pool.map(worker,range(concurrency)) for row in group]
|
||||
elapsed=time.monotonic()-start;samples.extend(records)
|
||||
phases.append({'operation':operation,'clients':concurrency,'repeat':repeat,'warmup':repeat==0,'requests':len(records),'elapsed_seconds':elapsed,'successful_rps':sum(r['success'] for r in records)/elapsed,'errors':dict(Counter(r['error'] for r in records if r['error']))})
|
||||
print(operation,'clients='+str(concurrency),'complete',flush=True)
|
||||
finally:
|
||||
ended=time.monotonic()
|
||||
for role,(sampler,cpus) in samplers.items():
|
||||
try:resources[role]=sampler.finish(began,ended,cpus)
|
||||
except RuntimeError as exc:resource_errors[role]=str(exc)
|
||||
measured=[r for r in samples if not r['warmup']];table=[]
|
||||
for concurrency in [1,5,10]:
|
||||
for operation in names:
|
||||
rows=[r for r in measured if r['operation']==operation and r['clients']==concurrency];ok=[r for r in rows if r['success']]
|
||||
elapsed=sum(p['elapsed_seconds'] for p in phases if not p['warmup'] and p['operation']==operation and p['clients']==concurrency)
|
||||
table.append({'operation':operation,'clients':concurrency,'requests':len(rows),'successes':len(ok),'errors':dict(Counter(r['error'] for r in rows if r['error'])),'elapsed_seconds':elapsed,'successful_rps':len(ok)/elapsed,'success_latency_ms':harness.percentiles([r['elapsed_ms']/1000 for r in ok]) if ok else None,'all_request_latency_ms':harness.percentiles([r['elapsed_ms']/1000 for r in rows])})
|
||||
report={'generator':'Python urllib public Client; closed loop, no retries, concurrency is clients not arrival rate','method':{'concurrency':[1,5,10],'repeats':a.repeats,'requests_per_worker_per_repeat':a.per_worker,'warmup_requests_per_worker_per_operation':1,'initial_history_messages':a.history,'deep_cursor_after_messages':((a.history*8//10)//100)*100,'message_payload_codepoints':123,'message_payload_padding_chars':80,'seed_payload_padding_chars':100,'client_timeout_seconds':a.client_timeout,'limits':config},'elapsed_seconds':ended-began,'table':table,'phases':phases,'samples':samples,'resources':resources,'resource_errors':resource_errors,'internal_sql_or_pool_times':'not instrumented: HTTP latency is not storage latency','limitations':['Small sample, p99 often equals observed maximum; no p99.9 or SLO claims.','Closed loop has coordinated omission and does not measure maximum capacity.','HTTP elapsed includes client validation and connection/scheduling overhead.','Resource sampler executes inside cgroups; sampled peaks include sampling overhead.','History and database grow during create/write operations; only seeded cursor position is fixed.']}
|
||||
(a.output/'results.json').write_text(json.dumps(report,indent=2))
|
||||
lines=['# HTTP latency matrix','','Preliminary closed-loop measurements, not selected application budgets.','','| Operation | Clients | n | Errors | Successful RPS | p50 ms | p95 ms | p99 ms |','|---|---:|---:|---:|---:|---:|---:|---:|']
|
||||
for row in table:
|
||||
t=row['success_latency_ms'] or dict(p50=0,p95=0,p99=0);lines.append('| %s | %d | %d | %d | %.2f | %.2f | %.2f | %.2f |'%(row['operation'],row['clients'],row['requests'],row['requests']-row['successes'],row['successful_rps'],t['p50'],t['p95'],t['p99']))
|
||||
lines+=['','Full conditions, warmup/error timings and CPU/RAM samples: results.json. HTTP times are not SQL times. Small n does not support stable tail estimates.']
|
||||
(a.output/'TABLE.md').write_text('\n'.join(lines)+'\n')
|
||||
failures=any(not r['success'] for r in samples) or bool(resource_errors) or any(v.get('oom_kill_count',0)>0 for v in resources.values())
|
||||
print('FAIL' if failures else 'COMPLETE',flush=True)
|
||||
return 1 if failures else 0
|
||||
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Additional lab2 API cases, using the unchanged teacher client."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import LAB, check, timestamp
|
||||
from validation_edges import acceptance as json_acceptance
|
||||
|
||||
|
||||
def message_headers():
|
||||
return {"Idempotency-Key": uuid.uuid4().hex} if LAB >= 3 else {}
|
||||
|
||||
|
||||
def room(c, actor, members=None, title="Lab2 business fixture"):
|
||||
return c.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": title, "member_ids": members or [actor["id"]]}, schema="Chat")["json"]
|
||||
|
||||
|
||||
def history(c, actor, chat, limit=100):
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=" + str(limit)
|
||||
items, cursors = [], set()
|
||||
for _ in range(2000):
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
check(len({x["id"] for x in items}) == len(items), "history duplicates message IDs")
|
||||
return items
|
||||
check(cursor not in cursors, "cursor cycle")
|
||||
cursors.add(cursor)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=" + str(limit) + "&cursor=" + quote(cursor, safe="")
|
||||
raise AssertionError("history traversal exceeded test bound")
|
||||
|
||||
|
||||
def boundaries(c):
|
||||
actor, other = c.user("bounds"), c.user("other")
|
||||
for title in ("", " \t\n", "😀" * 101):
|
||||
c.call("POST", "/api/v1/chats", 400, actor=actor,
|
||||
body={"title": title, "member_ids": [actor["id"]]})
|
||||
for members in ([], [other["id"]], [actor["id"], actor["id"]],
|
||||
[actor["id"], str(uuid.uuid4())], [actor["id"], "invalid"]):
|
||||
c.call("POST", "/api/v1/chats", 400, actor=actor,
|
||||
body={"title": "Invalid members", "member_ids": members})
|
||||
chat = room(c, actor, title="😀" * 100)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
for text in ("", " \t\n", "😀" * 4001):
|
||||
c.call("POST", path, 400, actor=actor, body={"text": text}, headers=message_headers())
|
||||
message = c.message(actor, chat, "😀" * 4000)["json"]
|
||||
check(message["text"] == "😀" * 4000, "Unicode message boundary changed")
|
||||
c.call("POST", path, 400, actor=actor, body={"text": "forged", "sender_id": other["id"]}, headers=message_headers())
|
||||
for limit in ("0", "101", "-1", "abc", ""):
|
||||
c.call("GET", path + "?limit=" + limit, 400, actor=actor)
|
||||
for raw in (b'{"text":"x","extra":1}', b'{"Text":"x"}', b'{"text":null}',
|
||||
b'{"text":1}', b'{"text":"x"} {}', b'{"text":"\xff"}'):
|
||||
c.call("POST", path, 400, actor=actor, raw=raw,
|
||||
headers={"Content-Type": "application/json", **message_headers()})
|
||||
for target, body in (("/api/v1/chats", {"title": "Media", "member_ids": [actor["id"]]}),
|
||||
(path, {"text": "Media"})):
|
||||
c.call("POST", target, 415, actor=actor, body=body,
|
||||
headers={"Content-Type": "text/plain", **(message_headers() if target == path else {})})
|
||||
c.call("GET", "/api/v1/does-not-exist", 404, actor=actor)
|
||||
return json_acceptance(c)
|
||||
|
||||
|
||||
def chat_pagination(c):
|
||||
owner, outsider = c.user("chatpages"), c.user("chatother")
|
||||
empty = c.call("GET", "/api/v1/chats", actor=owner, schema="ChatPage")["json"]
|
||||
check(empty == {"items": [], "next_cursor": None}, "empty chat list is not a finished empty page")
|
||||
expected = [room(c, owner, title="Chat page " + str(i)) for i in range(7)]
|
||||
room(c, outsider, title="Must not appear in owner's list")
|
||||
ordered = sorted(expected, key=lambda x: (timestamp(x["created_at"]), uuid.UUID(x["id"]).int))
|
||||
seen, cursors, cursor = [], set(), None
|
||||
for _ in range(len(expected) + 1):
|
||||
path = "/api/v1/chats?limit=2"
|
||||
if cursor is not None:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = c.call("GET", path, actor=owner, schema="ChatPage")["json"]
|
||||
check(0 < len(page["items"]) <= 2, "invalid chat page size")
|
||||
seen.extend(page["items"])
|
||||
check(len(seen) <= len(expected), "chat pagination repeated or leaked items")
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
check(cursor not in cursors, "chat cursor cycle")
|
||||
cursors.add(cursor)
|
||||
rejected = c.call("GET", "/api/v1/chats?cursor=" + quote(cursor, safe=""),
|
||||
400, actor=outsider)
|
||||
check(rejected["json"]["error"]["code"] == "invalid_request", "foreign chat-list cursor returned wrong error")
|
||||
else:
|
||||
check(False, "chat pagination exceeded fixture bound")
|
||||
check(len({item["id"] for item in seen}) == len(expected), "chat list omitted or repeated IDs")
|
||||
check(seen == ordered, "chat pagination lost, repeated, changed or reordered items")
|
||||
|
||||
first = c.call("GET", "/api/v1/chats?limit=1", actor=owner, schema="ChatPage")["json"]
|
||||
check(first["next_cursor"] is not None, "chat cursor ended before remaining items")
|
||||
rest = c.call("GET", "/api/v1/chats?limit=100&cursor=" + quote(first["next_cursor"], safe=""),
|
||||
actor=owner, schema="ChatPage")["json"]
|
||||
check(first["items"] + rest["items"] == ordered and rest["next_cursor"] is None,
|
||||
"changing chat-list limit lost, repeated or reordered items")
|
||||
for query in ("limit=0", "limit=101", "limit=-1", "limit=abc", "limit=", "cursor=", "cursor=invalid"):
|
||||
rejected = c.call("GET", "/api/v1/chats?" + query, 400, actor=owner)
|
||||
check(rejected["json"]["error"]["code"] == "invalid_request", "invalid chat-list query returned wrong error")
|
||||
return {"items": len(seen), "page_limit": 2, "foreign_cursors_rejected": len(cursors),
|
||||
"changed_limit": [1, 100]}
|
||||
|
||||
|
||||
def cursors(c):
|
||||
actor, outsider = c.user("cursor"), c.user("outside")
|
||||
first, second = room(c, actor), room(c, actor)
|
||||
empty = c.call("GET", "/api/v1/chats/" + second["id"] + "/messages", actor=actor, schema="MessagePage")["json"]
|
||||
check(empty == {"items": [], "next_cursor": None}, "empty history is not an empty finished page")
|
||||
sent = [c.message(actor, first, "Page " + str(i))["json"] for i in range(7)]
|
||||
path = "/api/v1/chats/" + first["id"] + "/messages"
|
||||
page = c.call("GET", path + "?limit=1", actor=actor, schema="MessagePage")["json"]
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
rest = c.call("GET", path + "?limit=100&cursor=" + cursor, actor=actor, schema="MessagePage")["json"]
|
||||
ordered = sorted(sent, key=lambda x: (timestamp(x["created_at"]), uuid.UUID(x["id"]).int))
|
||||
check(page["items"] + rest["items"] == ordered and rest["next_cursor"] is None,
|
||||
"changing limit lost/repeated/reordered messages")
|
||||
c.call("GET", "/api/v1/chats/" + second["id"] + "/messages?cursor=" + cursor, 400, actor=actor)
|
||||
for value in ("", "not-a-cursor"):
|
||||
c.call("GET", path + "?cursor=" + value, 400, actor=actor)
|
||||
c.call("GET", path, 404, actor=outsider)
|
||||
c.call("POST", path, 404, actor=outsider, body={"text": "hidden"}, headers=message_headers())
|
||||
check(history(c, actor, first, limit=2) == ordered, "complete keyset traversal differs")
|
||||
return {"message_items": len(sent), "chat_list": chat_pagination(c)}
|
||||
|
||||
|
||||
def read_after_write(c, client_factory, concurrency=4):
|
||||
members = [c.user("writer") for _ in range(10)]
|
||||
actor = members[0]
|
||||
chat = room(c, actor, members=[m["id"] for m in members])
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
# Warm the empty-history cache before starting concurrent writes.
|
||||
c.call("GET", path, actor=actor, schema="MessagePage")
|
||||
|
||||
def write_then_read(index):
|
||||
local = client_factory()
|
||||
writer = members[index % len(members)]
|
||||
confirmed = local.message(writer, chat, "Read-after-write " + str(index))["json"]
|
||||
check(confirmed["sender_id"] == writer["id"], "message sender differs from authenticated writer")
|
||||
page = local.call("GET", path, actor=writer, schema="MessagePage")["json"]
|
||||
check(any(m == confirmed for m in page["items"]), "confirmed message absent from next read")
|
||||
return confirmed
|
||||
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
messages = list(pool.map(write_then_read, range(100)))
|
||||
stored = history(c, actor, chat, limit=37)
|
||||
check(len({m["id"] for m in messages}) == 100, "concurrent writes reused message IDs")
|
||||
check(stored == sorted(messages, key=lambda m: (timestamp(m["created_at"]), uuid.UUID(m["id"]).int)),
|
||||
"concurrent writes lost, duplicated, changed or reordered confirmations")
|
||||
check({m["sender_id"] for m in stored} == {m["id"] for m in members}, "not all writers contributed")
|
||||
return {"writers": len(members), "messages": len(stored), "concurrency": concurrency}
|
||||
@@ -0,0 +1,62 @@
|
||||
# Example only. This is NOT installed into .github/workflows by the test task.
|
||||
# PostgreSQL acceptance job; add the chosen cache service/adapters for grade 4/5.
|
||||
name: Lab2 application example
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
postgres-acceptance:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18
|
||||
env:
|
||||
POSTGRES_USER: lab2_ci
|
||||
POSTGRES_DB: lab2_ci
|
||||
# Public synthetic fixture credential for this disposable CI service.
|
||||
POSTGRES_PASSWORD: ci-fixture-only
|
||||
ports: ["5432:5432"]
|
||||
options: >-
|
||||
--health-cmd="pg_isready -U lab2_ci -d lab2_ci"
|
||||
--health-interval=5s --health-timeout=3s --health-retries=10
|
||||
env:
|
||||
AUTH_TEST_DATABASE_URL: postgres://lab2_ci:ci-fixture-only@127.0.0.1:5432/lab2_ci?sslmode=disable
|
||||
MIGRATE_TEST_DATABASE_URL: postgres://lab2_ci:ci-fixture-only@127.0.0.1:5432/lab2_ci?sslmode=disable
|
||||
LAB2_TEST_DATABASE_URL: postgres://lab2_ci:ci-fixture-only@127.0.0.1:5432/lab2_ci?sslmode=disable
|
||||
LAB2_BASE_URL: http://127.0.0.1:8080
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
SESSION_TTL_SECONDS: "3600"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.27.1"
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python -m pip install -r requirements-dev.txt
|
||||
- run: make check validate PYTHON=python
|
||||
- run: python -m unittest discover -s student-tests/lab2 -p test_harness.py -v
|
||||
- run: go test -race ./... -count=1
|
||||
- name: Build, migrate, run actual HTTP checks
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
go build -o "$RUNNER_TEMP/lab2-api" ./cmd/api
|
||||
go build -o "$RUNNER_TEMP/lab2-migrate" ./cmd/migrate
|
||||
export DATABASE_URL_FILE="$RUNNER_TEMP/lab2-database-url"
|
||||
umask 077
|
||||
printf '%s' "$LAB2_TEST_DATABASE_URL" > "$DATABASE_URL_FILE"
|
||||
"$RUNNER_TEMP/lab2-migrate"
|
||||
"$RUNNER_TEMP/lab2-api" > "$RUNNER_TEMP/lab2-api.log" 2>&1 &
|
||||
api_pid=$!
|
||||
trap 'kill "$api_pid" 2>/dev/null || true' EXIT
|
||||
ready=0
|
||||
for attempt in {1..60}; do
|
||||
if curl -fsS "$LAB2_BASE_URL/health/ready" >/dev/null; then ready=1; break; fi
|
||||
sleep 0.5
|
||||
done
|
||||
test "$ready" -eq 1
|
||||
make test BASE_URL="$LAB2_BASE_URL"
|
||||
python student-tests/lab2/run.py --suite auth --suite business-boundaries --suite business-cursors --suite read-after-write --suite sql-plan --output student-tests/lab2/output/ci.json
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"base_url": null,
|
||||
"expiry_base_url": null,
|
||||
"ca_file": null,
|
||||
"ttl_seconds": 3600,
|
||||
"request_timeout_seconds": 10,
|
||||
"hook_timeout_seconds": 90,
|
||||
"operation_budget_seconds": 3,
|
||||
"cache_policy": null,
|
||||
"cache_target": "history",
|
||||
"track": null,
|
||||
"concurrency": 4,
|
||||
"read_repetitions": 20,
|
||||
"cache_experiment": {
|
||||
"scenario": null,
|
||||
"max_protected_sql_queries": null
|
||||
},
|
||||
"sql": {
|
||||
"database_url_env": "LAB2_TEST_DATABASE_URL",
|
||||
"restore_database_url_env": "LAB2_RESTORED_DATABASE_URL",
|
||||
"source_schema": "public",
|
||||
"restore_schema": "public",
|
||||
"plan_rows": 10000,
|
||||
"research_rows": 100000,
|
||||
"scan_budget_rows": 1000,
|
||||
"repetitions": 5
|
||||
},
|
||||
"hooks": {
|
||||
"restart_stack": null,
|
||||
"stop_postgres": null,
|
||||
"start_postgres": null,
|
||||
"stop_cache": null,
|
||||
"start_cache": null,
|
||||
"restart_cache": null,
|
||||
"block_query": null,
|
||||
"unblock_query": null,
|
||||
"exhaust_pool": null,
|
||||
"release_pool": null,
|
||||
"evict_cache": null,
|
||||
"metrics": null,
|
||||
"prepare_cache_baseline": null,
|
||||
"prepare_cache_protected": null,
|
||||
"backup_database": null,
|
||||
"restore_database": null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 2: disposable PostgreSQL A/B experiment and verified backup/restore.
|
||||
|
||||
Uses sqlprobe and the existing snapshot comparator. Credentials and the actual
|
||||
dump remain in an automatically removed private temporary directory. Only the
|
||||
two containers and volumes created by this invocation can be removed.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from resources import Sampler
|
||||
from run import compare_snapshots
|
||||
|
||||
|
||||
def command(argv, *, env=None, stdin=None, stdout=None, timeout=180):
|
||||
try:
|
||||
result = subprocess.run(argv, cwd=ROOT, env=env, stdin=stdin,
|
||||
stdout=stdout or subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, timeout=timeout)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
raise RuntimeError('Command unavailable or timed out: ' + argv[0]) from exc
|
||||
if result.returncode:
|
||||
# Process arguments/output may contain connection details. Do not print them.
|
||||
safe = [s for s in result.stderr.decode(errors='replace').splitlines()
|
||||
if s.startswith(('research:', 'sqlstate:'))]
|
||||
raise RuntimeError('Command failed: ' + Path(argv[0]).name + ' (exit ' + str(result.returncode) + ')' + ('; ' + '; '.join(safe) if safe else ''))
|
||||
return result.stdout.decode() if stdout is None else ''
|
||||
|
||||
|
||||
def save(path, value):
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
|
||||
def wait_postgres(name):
|
||||
deadline = time.monotonic() + 75
|
||||
while time.monotonic() < deadline:
|
||||
result = subprocess.run(['docker', 'exec', name, 'pg_isready', '-U', 'messenger', '-d', 'messenger'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
time.sleep(.3)
|
||||
raise RuntimeError('PostgreSQL did not become ready')
|
||||
|
||||
|
||||
def container_state(name):
|
||||
fields = '{{json .State}}\n{{json .Mounts}}\n{{.Id}}'
|
||||
state, mounts, identifier = command(['docker', 'inspect', '--format', fields, name]).splitlines()
|
||||
state, mounts = json.loads(state), json.loads(mounts)
|
||||
return {'id': identifier, 'started_at': state['StartedAt'], 'running': state['Running'],
|
||||
'oom_killed': state['OOMKilled'],
|
||||
'volumes': [m['Name'] for m in mounts if m['Type'] == 'volume']}
|
||||
|
||||
|
||||
def selected_messages(name, schema):
|
||||
if not schema.startswith('lab2_test_') or not schema.replace('_', '').isalnum():
|
||||
raise RuntimeError('Unexpected fixture schema')
|
||||
# Values stay in process memory. Evidence retains IDs and content fingerprints.
|
||||
sql = f'''SELECT row_to_json(chosen)::text FROM (
|
||||
SELECT id,chat_id,sender_id,text,created_at,rn,total FROM (
|
||||
SELECT m.*,row_number() OVER (PARTITION BY chat_id ORDER BY created_at,id) rn,
|
||||
count(*) OVER (PARTITION BY chat_id) total FROM "{schema}".messages m
|
||||
) ranked WHERE rn IN (1,(total+1)/2,total) ORDER BY chat_id,rn
|
||||
) chosen'''
|
||||
raw = command(['docker', 'exec', name, 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-c', sql])
|
||||
result = []
|
||||
for line in raw.splitlines():
|
||||
row = json.loads(line)
|
||||
result.append({'id': row['id'], 'chat_id': row['chat_id'], 'position': row['rn'],
|
||||
'chat_rows': row['total'], 'sha256': hashlib.sha256(
|
||||
json.dumps(row, sort_keys=True, ensure_ascii=False).encode()).hexdigest()})
|
||||
if len(result) != 15:
|
||||
raise RuntimeError('Expected first/middle/last samples from all five chats')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--output', type=Path, required=True)
|
||||
p.add_argument('--postgres-image', default='postgres:18')
|
||||
p.add_argument('--rows', type=int, default=100000)
|
||||
p.add_argument('--repetitions', type=int, default=60)
|
||||
p.add_argument('--series', type=int, default=4)
|
||||
p.add_argument('--write-batches', type=int, default=20)
|
||||
args = p.parse_args()
|
||||
if args.rows < 100000 or args.rows % 100 or args.repetitions < 30 or args.series < 4 or args.series % 2 or args.write_batches < 10:
|
||||
p.error('need >=100k rows divisible by 100, >=30 reads, even >=4 series and >=10 write batches')
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
run_id = 'lab2-research-' + secrets.token_hex(6)
|
||||
names = [run_id + '-source', run_id + '-target']
|
||||
volumes = [run_id + '-source-data', run_id + '-target-data']
|
||||
owned_containers, owned_volumes = [], []
|
||||
summary = {'status': 'FAIL', 'run_id': run_id, 'rows': args.rows,
|
||||
'started_at': datetime.now(timezone.utc).isoformat(), 'stages': []}
|
||||
sampler = None
|
||||
try:
|
||||
image_info = json.loads(command(['docker', 'image', 'inspect', args.postgres_image]))[0]
|
||||
# Run the immutable locally resolved image ID; the chosen digest is in evidence.
|
||||
image_id = image_info['Id']
|
||||
hardware = {}
|
||||
if sys.platform == 'darwin':
|
||||
for key in ('hw.model', 'hw.ncpu', 'hw.memsize', 'machdep.cpu.brand_string'):
|
||||
hardware[key] = command(['sysctl', '-n', key]).strip()
|
||||
environment = {'platform': platform.platform(), 'hardware': hardware,
|
||||
'go': command(['go', 'version']).strip(),
|
||||
'docker': command(['docker', 'version', '--format', '{{.Server.Version}}']).strip(),
|
||||
'image': {'id': image_id, 'digests': image_info.get('RepoDigests', []),
|
||||
'architecture': image_info['Architecture']},
|
||||
'limits_per_postgres': {'cpus': 1, 'memory_mib': 512},
|
||||
'other_running_containers_at_start': command(['docker', 'ps', '--format', '{{.Names}}']).splitlines()}
|
||||
save(output / 'environment.json', environment)
|
||||
with tempfile.TemporaryDirectory(prefix=run_id + '-') as directory:
|
||||
tmp = Path(directory)
|
||||
env_file = tmp / 'postgres.env'
|
||||
password = secrets.token_hex(24)
|
||||
env_file.write_text('POSTGRES_USER=messenger\nPOSTGRES_DB=messenger\nPOSTGRES_PASSWORD=' + password + '\n')
|
||||
env_file.chmod(0o600)
|
||||
probe = tmp / 'sqlprobe'
|
||||
build_env = dict(os.environ, GOCACHE=os.environ.get('GOCACHE', '/tmp/highload-research-go-cache'))
|
||||
command(['go', 'build', '-mod=readonly', '-o', str(probe), './student-tests/lab2/sqlprobe'], env=build_env)
|
||||
|
||||
def start(index):
|
||||
name, volume = names[index], volumes[index]
|
||||
command(['docker', 'volume', 'create', '--label', 'highload.research=' + run_id, volume])
|
||||
owned_volumes.append(volume)
|
||||
command(['docker', 'run', '-d', '--name', name, '--label', 'highload.research=' + run_id,
|
||||
'--cpus', '1', '--memory', '512m', '--memory-swap', '512m',
|
||||
'--env-file', str(env_file), '-p', '127.0.0.1::5432',
|
||||
'-v', volume + ':/var/lib/postgresql', image_id])
|
||||
owned_containers.append(name)
|
||||
wait_postgres(name)
|
||||
return connection_url(name)
|
||||
|
||||
def connection_url(name):
|
||||
port = command(['docker', 'port', name, '5432/tcp']).strip().rsplit(':', 1)[1]
|
||||
return f'postgres://messenger:{password}@127.0.0.1:{port}/messenger?sslmode=disable'
|
||||
|
||||
source_url = start(0)
|
||||
|
||||
def sqlprobe(mode, url, extra=()):
|
||||
argv = [str(probe), '-mode', mode, '-rows', str(args.rows),
|
||||
'-repetitions', str(args.repetitions), '-series', str(args.series),
|
||||
'-write-batches', str(args.write_batches), '-timeout', '12m', *extra]
|
||||
env = dict(os.environ, LAB2_SQL_DATABASE_URL=url)
|
||||
started = time.monotonic()
|
||||
result = json.loads(command(argv, env=env, timeout=750))
|
||||
summary['stages'].append({'stage': mode, 'status': 'PASS', 'seconds': time.monotonic() - started})
|
||||
return result
|
||||
|
||||
print('PostgreSQL source ready; preparing and comparing >=100k rows', flush=True)
|
||||
sampler = Sampler(names[0], .5)
|
||||
began = time.monotonic()
|
||||
sampler.thread.start()
|
||||
comparison = sqlprobe('research', source_url)
|
||||
ended = time.monotonic()
|
||||
comparison['resources'] = sampler.finish(began, ended, 1)
|
||||
sampler = None
|
||||
save(output / 'indexes.json', comparison)
|
||||
print('Index comparison PASS; preparing persistent backup fixture', flush=True)
|
||||
schema = 'lab2_test_backup_' + secrets.token_hex(5)
|
||||
seed = sqlprobe('seed', source_url, ('-schema', schema))
|
||||
save(output / 'dataset.json', seed)
|
||||
before = sqlprobe('snapshot', source_url, ('-schema', schema))
|
||||
selected_before = selected_messages(names[0], schema)
|
||||
save(output / 'source-snapshot.json', before)
|
||||
save(output / 'source-selected.json', selected_before)
|
||||
target_url = start(1)
|
||||
empty = sqlprobe('snapshot', target_url, ('-schema', schema))
|
||||
if not empty['empty'] or before['identity_sha256'] == empty['identity_sha256']:
|
||||
raise RuntimeError('Restore target must be a distinct empty PostgreSQL instance')
|
||||
before_states = {n: container_state(n) for n in names}
|
||||
if set(before_states[names[0]]['volumes']) & set(before_states[names[1]]['volumes']):
|
||||
raise RuntimeError('Source and target share a volume')
|
||||
save(output / 'storage-before-restore.json', before_states)
|
||||
dump = tmp / 'backup.dump'
|
||||
began = time.monotonic()
|
||||
with dump.open('wb') as stream:
|
||||
dump.chmod(0o600)
|
||||
command(['docker', 'exec', names[0], 'pg_dump', '-U', 'messenger', '-d', 'messenger',
|
||||
'-n', schema, '-Fc', '--no-owner', '--no-acl'], stdout=stream)
|
||||
backup_seconds = time.monotonic() - began
|
||||
dump_hash = hashlib.sha256(dump.read_bytes()).hexdigest()
|
||||
began = time.monotonic()
|
||||
with dump.open('rb') as stream:
|
||||
command(['docker', 'exec', '-i', names[1], 'pg_restore', '-U', 'messenger', '-d', 'messenger',
|
||||
'--exit-on-error', '--no-owner', '--no-acl'], stdin=stream)
|
||||
restore_seconds = time.monotonic() - began
|
||||
restored = sqlprobe('snapshot', target_url, ('-schema', schema))
|
||||
compare_snapshots(before, restored)
|
||||
selected_after = selected_messages(names[1], schema)
|
||||
if selected_before != selected_after or before != sqlprobe('snapshot', source_url, ('-schema', schema)):
|
||||
raise RuntimeError('Selected messages differ or source changed during backup/restore')
|
||||
save(output / 'restored-snapshot.json', restored)
|
||||
save(output / 'restored-selected.json', selected_after)
|
||||
# Start from disk again, retaining only the new target's own volume.
|
||||
began = time.monotonic()
|
||||
command(['docker', 'restart', '--time', '20', names[1]])
|
||||
wait_postgres(names[1])
|
||||
# Docker can allocate a different ephemeral host port after restart.
|
||||
target_url = connection_url(names[1])
|
||||
restarted = sqlprobe('snapshot', target_url, ('-schema', schema))
|
||||
compare_snapshots(before, restarted)
|
||||
restart_seconds = time.monotonic() - began
|
||||
save(output / 'storage-after-restart.json', {n: container_state(n) for n in names})
|
||||
restore = {'status': 'PASS', 'backup_seconds': backup_seconds, 'restore_seconds': restore_seconds,
|
||||
'target_restart_and_verification_seconds': restart_seconds,
|
||||
'archive_bytes': dump.stat().st_size, 'archive_sha256': dump_hash,
|
||||
'source_unchanged': True, 'selected_messages_equal': len(selected_before),
|
||||
'all_four_table_counts_and_digests_equal': True, 'target_restart_pass': True,
|
||||
'archive_retained': False, 'scope': 'quiescent synthetic PostgreSQL schema; Redis sessions and post-snapshot writes not included'}
|
||||
save(output / 'backup-restore.json', restore)
|
||||
summary['status'] = 'PASS'
|
||||
print('Backup/restore and target restart PASS', flush=True)
|
||||
except Exception as exc:
|
||||
summary['failure'] = str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__
|
||||
print('FAIL: ' + summary['failure'], flush=True)
|
||||
finally:
|
||||
if sampler is not None:
|
||||
sampler.stop_event.set()
|
||||
sampler.thread.join(timeout=5)
|
||||
cleanup_errors = []
|
||||
for name in reversed(owned_containers):
|
||||
try:
|
||||
command(['docker', 'rm', '-f', name], timeout=45)
|
||||
except RuntimeError:
|
||||
cleanup_errors.append('container ' + name)
|
||||
for name in reversed(owned_volumes):
|
||||
try:
|
||||
command(['docker', 'volume', 'rm', name], timeout=30)
|
||||
except RuntimeError:
|
||||
cleanup_errors.append('volume ' + name)
|
||||
summary['cleanup_errors'] = cleanup_errors
|
||||
if cleanup_errors:
|
||||
summary['status'] = 'FAIL'
|
||||
summary['finished_at'] = datetime.now(timezone.utc).isoformat()
|
||||
save(output / 'summary.json', summary)
|
||||
return 0 if summary['status'] == 'PASS' else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Container resource sampling shared by the lab2 HTTP measurements."""
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class Sampler:
|
||||
"""PID 1 RSS and cgroup-v2 CPU/memory. Only samples inside the phase are used."""
|
||||
|
||||
files = ("/proc/1/status", "/sys/fs/cgroup/cpu.stat",
|
||||
"/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory.events")
|
||||
|
||||
def __init__(self, name, interval):
|
||||
self.name, self.interval = name, interval
|
||||
self.stop_event = threading.Event()
|
||||
self.samples, self.errors = [], []
|
||||
self.thread = threading.Thread(target=self.loop, daemon=True)
|
||||
|
||||
def loop(self):
|
||||
while not self.stop_event.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = subprocess.run(["docker", "exec", self.name, "awk",
|
||||
'FNR == 1 {print "FILE " FILENAME} {print}', *self.files],
|
||||
timeout=4, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError("resource sampling failed (container stopped or cgroup v2 unavailable)")
|
||||
sections, current = {}, None
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith("FILE "):
|
||||
current = line[5:]
|
||||
sections[current] = []
|
||||
elif current:
|
||||
sections[current].append(line)
|
||||
status = dict(line.split(":", 1) for line in sections[self.files[0]] if ":" in line)
|
||||
cpu = dict(line.split() for line in sections[self.files[1]])
|
||||
events = dict(line.split() for line in sections[self.files[3]])
|
||||
self.samples.append({"started": started, "finished": time.monotonic(),
|
||||
"rss_bytes": int(status["VmRSS"].split()[0]) * 1024,
|
||||
"cgroup_memory_bytes": int(sections[self.files[2]][0]),
|
||||
"cpu_usage_usec": int(cpu["usage_usec"]),
|
||||
"oom_kill_count": int(events.get("oom_kill", 0))})
|
||||
except (RuntimeError, ValueError, KeyError, subprocess.SubprocessError) as exc:
|
||||
self.errors.append(str(exc))
|
||||
self.stop_event.wait(max(0, self.interval - (time.monotonic() - started)))
|
||||
|
||||
def finish(self, started, ended, cpus):
|
||||
self.stop_event.set()
|
||||
self.thread.join(timeout=5)
|
||||
samples = [s for s in self.samples if s["started"] >= started and s["finished"] <= ended]
|
||||
if self.errors or len(samples) < 2:
|
||||
raise RuntimeError(self.errors[0] if self.errors else "fewer than two resource samples; increase duration")
|
||||
first, last = samples[0], samples[-1]
|
||||
window = last["finished"] - first["finished"]
|
||||
cores = (last["cpu_usage_usec"] - first["cpu_usage_usec"]) / 1e6 / window
|
||||
rows = [{"seconds": round(s["finished"] - started, 4),
|
||||
"rss_bytes": s["rss_bytes"], "cgroup_memory_bytes": s["cgroup_memory_bytes"],
|
||||
"cpu_usage_usec": s["cpu_usage_usec"], "oom_kill_count": s["oom_kill_count"]}
|
||||
for s in samples]
|
||||
return {"sample_interval_seconds": self.interval, "sample_count": len(rows),
|
||||
"sample_window_seconds": window, "mean_cpu_cores": cores,
|
||||
"mean_cpu_percent_of_limit": 100 * cores / cpus,
|
||||
"rss_first_bytes": first["rss_bytes"],
|
||||
"rss_peak_observed_bytes": max(s["rss_bytes"] for s in samples),
|
||||
"cgroup_memory_peak_observed_bytes": max(s["cgroup_memory_bytes"] for s in samples),
|
||||
"oom_kill_count": max(s["oom_kill_count"] for s in samples), "samples": rows,
|
||||
"method": "RSS: /proc/1/status VmRSS. CPU: delta cgroup-v2 usage_usec / sample window. cgroup memory includes cache and sampling processes; it is not RSS. Peaks are sampled, not exact maxima."}
|
||||
@@ -0,0 +1,449 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Opt-in lab2 test/experiment runner. No application or teacher-contract edits."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
import business # noqa: E402
|
||||
|
||||
|
||||
class Blocked(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def bounded_command(argv, cwd, timeout, env=None):
|
||||
"""Never invoke a shell or include command output/credentials in exceptions."""
|
||||
try:
|
||||
p = subprocess.Popen(argv, cwd=cwd, env=env, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, start_new_session=True)
|
||||
except OSError:
|
||||
raise Blocked("command unavailable; check local tools/adapter") from None
|
||||
try:
|
||||
out, _ = p.communicate(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(p.pid, signal.SIGTERM)
|
||||
try:
|
||||
p.communicate(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(p.pid, signal.SIGKILL)
|
||||
p.communicate()
|
||||
raise Failure("command/adapter exceeded its execution budget") from None
|
||||
if p.returncode == 2:
|
||||
raise Blocked("adapter reports missing implementation/configuration")
|
||||
if p.returncode:
|
||||
raise Failure("command/adapter failed (exit %d); output suppressed" % p.returncode)
|
||||
return out
|
||||
|
||||
|
||||
def percentiles(values):
|
||||
check(bool(values), "no successful latency samples")
|
||||
values = sorted(values)
|
||||
return {"p" + str(p): round(1000 * values[max(0, math.ceil(len(values) * p / 100) - 1)], 3)
|
||||
for p in (50, 95, 99)}
|
||||
|
||||
|
||||
def counter_delta(before, after, key):
|
||||
a, b = before.get(key), after.get(key)
|
||||
check(isinstance(a, int) and not isinstance(a, bool) and a >= 0 and
|
||||
isinstance(b, int) and not isinstance(b, bool) and b >= a,
|
||||
"metrics adapter must return nondecreasing integer counter " + key)
|
||||
return b - a
|
||||
|
||||
|
||||
def compare_snapshots(source, restored):
|
||||
for snapshot in (source, restored):
|
||||
tables = snapshot.get("tables", {})
|
||||
check(set(tables) == {"users", "chats", "chat_members", "messages"},
|
||||
"snapshot must cover all four PostgreSQL application tables")
|
||||
for value in tables.values():
|
||||
check(isinstance(value.get("rows"), int) and not isinstance(value["rows"], bool) and value["rows"] >= 0 and
|
||||
isinstance(value.get("sha256"), str) and len(value["sha256"]) == 64,
|
||||
"snapshot has invalid counts/content digest")
|
||||
check(source.get("identity_sha256") != restored.get("identity_sha256"),
|
||||
"restore target must be a different database/storage endpoint")
|
||||
check(not source.get("empty") and not restored.get("empty"), "restore contains no application tables")
|
||||
check(source.get("tables") == restored.get("tables"), "restored table counts or ordered content digests differ")
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, config, config_path, allow_hooks=False):
|
||||
self.c = config
|
||||
self.directory = config_path.resolve().parent
|
||||
self.allow_hooks = allow_hooks
|
||||
|
||||
def client(self, expiry=False, timeout=None):
|
||||
key, env = ("expiry_base_url", "LAB2_EXPIRY_BASE_URL") if expiry else ("base_url", "LAB2_BASE_URL")
|
||||
url = os.environ.get(env) or self.c.get(key)
|
||||
if not url:
|
||||
raise Blocked("configure " + key + " for a dedicated synthetic test API")
|
||||
return Client(url, self.c.get("ca_file"), timeout=timeout or self.c["request_timeout_seconds"])
|
||||
|
||||
def require_hooks(self, *names):
|
||||
if not self.allow_hooks:
|
||||
raise Blocked("infrastructure adapters require explicit --allow-hooks")
|
||||
for name in names:
|
||||
argv = self.c.get("hooks", {}).get(name)
|
||||
if not isinstance(argv, list) or not argv or not all(isinstance(x, str) and x for x in argv):
|
||||
raise Blocked("configure executable argv array for hook " + name)
|
||||
|
||||
def hook(self, name, metrics=False):
|
||||
self.require_hooks(name)
|
||||
out = bounded_command(self.c["hooks"][name], self.directory, self.c["hook_timeout_seconds"])
|
||||
if metrics:
|
||||
check(len(out) <= 65536, "metrics adapter output exceeds limit")
|
||||
try:
|
||||
value = json.loads(out)
|
||||
except ValueError:
|
||||
raise Failure("metrics adapter must output one JSON object") from None
|
||||
check(isinstance(value, dict), "metrics adapter must output a JSON object")
|
||||
# Only these numeric counters may enter evidence, never raw adapter output.
|
||||
return {key: value.get(key) for key in ("sql_queries", "cache_hits")}
|
||||
|
||||
@contextlib.contextmanager
|
||||
def disruption(self, failure, recovery):
|
||||
self.require_hooks(failure, recovery)
|
||||
try:
|
||||
self.hook(failure)
|
||||
yield
|
||||
finally:
|
||||
self.hook(recovery)
|
||||
|
||||
def wait_ready(self):
|
||||
deadline = time.monotonic() + self.c["hook_timeout_seconds"]
|
||||
while True:
|
||||
try:
|
||||
self.client(timeout=2).call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "API did not recover readiness")
|
||||
time.sleep(.2)
|
||||
|
||||
def auth_module(self, expiry=False):
|
||||
spec = importlib.util.spec_from_file_location("lab2_auth_existing", ROOT / "student-tests/auth_contract.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.ARGS = types.SimpleNamespace(
|
||||
base_url=self.client(expiry=expiry).base, ca_file=self.c.get("ca_file"),
|
||||
timeout=self.c["request_timeout_seconds"], ttl=self.c["ttl_seconds"],
|
||||
hook_timeout=self.c["hook_timeout_seconds"], restart_hook="restart_stack",
|
||||
failure_hook=None, recovery_hook=None, dependency=None, cache_policy=self.c.get("cache_policy"), session_store="redis")
|
||||
module.hook = self.hook
|
||||
return module
|
||||
|
||||
def auth(self, suite):
|
||||
if suite == "persistence":
|
||||
self.require_hooks("restart_stack")
|
||||
module = self.auth_module(expiry=suite == "expiry")
|
||||
if suite == "auth":
|
||||
result = unittest.TextTestRunner(stream=io.StringIO()).run(
|
||||
unittest.defaultTestLoader.loadTestsFromTestCase(module.AuthContract))
|
||||
check(result.wasSuccessful(), "auth tests failed: " + ", ".join(t._testMethodName for t, _ in result.failures + result.errors))
|
||||
return {"tests": result.testsRun}
|
||||
if suite == "expiry":
|
||||
module.ARGS.base_url = self.client(expiry=True).base
|
||||
module.ARGS.ttl = 2
|
||||
module.expiry()
|
||||
else:
|
||||
module.persistence()
|
||||
|
||||
def dependency(self, name):
|
||||
failure, recovery = ("stop_postgres", "start_postgres") if name == "postgres" else ("stop_cache", "start_cache")
|
||||
self.require_hooks(failure, recovery)
|
||||
if name == "redis" and self.c.get("cache_policy") not in ("critical", "fallback"):
|
||||
raise Blocked("declare cache_policy critical or fallback")
|
||||
module = self.auth_module()
|
||||
module.ARGS.dependency = name
|
||||
module.ARGS.failure_hook, module.ARGS.recovery_hook = failure, recovery
|
||||
module.dependency()
|
||||
|
||||
def timeout(self, mode):
|
||||
failure, recovery = ("block_query", "unblock_query") if mode == "query" else ("exhaust_pool", "release_pool")
|
||||
self.require_hooks(failure, recovery)
|
||||
budget = self.c["operation_budget_seconds"]
|
||||
client = self.client(timeout=budget + 1)
|
||||
actor = client.user("budget")
|
||||
with self.disruption(failure, recovery):
|
||||
client.call("GET", "/health/live", schema="Health")
|
||||
client.call("GET", "/api/v1/users/me", 401)
|
||||
started = time.monotonic()
|
||||
response = client.call("GET", "/api/v1/users/me", 503, actor=actor)
|
||||
elapsed = time.monotonic() - started
|
||||
check(elapsed <= budget, "API exceeded configured test operation budget")
|
||||
check(response["json"]["error"]["code"] == "unavailable", "blocked operation returned wrong error")
|
||||
self.wait_ready()
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
return {"elapsed_seconds": round(elapsed, 4), "budget_seconds": budget, "mode": mode}
|
||||
|
||||
def cache_read(self, client, actor, chat):
|
||||
target = self.c.get("cache_target")
|
||||
if target == "history":
|
||||
return client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=actor, schema="MessagePage")
|
||||
if target == "chat":
|
||||
return client.call("GET", "/api/v1/chats/" + chat["id"], actor=actor, schema="Chat")
|
||||
if target == "me":
|
||||
return client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
raise Blocked("adapt cache_target to the actually cached operation")
|
||||
|
||||
def cache_usage(self):
|
||||
self.require_hooks("metrics", "evict_cache")
|
||||
client = self.client()
|
||||
actor = client.user("cache_use")
|
||||
chat = business.room(client, actor)
|
||||
self.hook("evict_cache")
|
||||
self.cache_read(client, actor, chat)
|
||||
before = self.hook("metrics", metrics=True)
|
||||
for _ in range(self.c["read_repetitions"]):
|
||||
self.cache_read(client, actor, chat)
|
||||
after = self.hook("metrics", metrics=True)
|
||||
hits = counter_delta(before, after, "cache_hits")
|
||||
check(hits > 0, "no actual cache hit observed on the selected API operation")
|
||||
return {"cache_hits": hits, "sql_queries": counter_delta(before, after, "sql_queries")}
|
||||
|
||||
def cache_restart(self):
|
||||
self.require_hooks("restart_cache")
|
||||
client = self.client()
|
||||
actor, revoked = client.user("cache_restart"), client.user("revoked")
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=revoked)
|
||||
chat = business.room(client, actor)
|
||||
original = client.message(actor, chat, "Before cache restart")["json"]
|
||||
self.cache_read(client, actor, chat)
|
||||
self.hook("restart_cache")
|
||||
self.wait_ready()
|
||||
check(client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["json"] == actor["user"], "cache restart lost session")
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=revoked)
|
||||
check(original in business.history(client, actor, chat), "cache restart lost confirmed message")
|
||||
|
||||
def cache_experiment(self):
|
||||
self.require_hooks("metrics", "evict_cache", "prepare_cache_baseline", "prepare_cache_protected", "restart_cache")
|
||||
scenario = self.c["cache_experiment"].get("scenario")
|
||||
if scenario not in ("stale_read", "stampede"):
|
||||
raise Blocked("choose cache_experiment.scenario stale_read or stampede")
|
||||
limit = self.c["cache_experiment"].get("max_protected_sql_queries")
|
||||
if scenario == "stampede" and (not isinstance(limit, int) or isinstance(limit, bool) or limit < 0):
|
||||
raise Blocked("declare a justified SQL-query budget for the protected stampede workload")
|
||||
variants = []
|
||||
for variant in ("baseline", "protected"):
|
||||
self.hook("prepare_cache_" + variant)
|
||||
self.wait_ready()
|
||||
client = self.client()
|
||||
actor = client.user("experiment")
|
||||
chat = business.room(client, actor)
|
||||
self.hook("evict_cache")
|
||||
before = self.hook("metrics", metrics=True)
|
||||
timings, lock = [], threading.Lock()
|
||||
|
||||
class TimedClient(Client):
|
||||
def call(inner, *args, **kwargs):
|
||||
result = super().call(*args, **kwargs)
|
||||
if args[0] == "GET":
|
||||
with lock:
|
||||
timings.append(result["elapsed"])
|
||||
return result
|
||||
|
||||
def factory():
|
||||
return TimedClient(client.base, self.c.get("ca_file"), timeout=self.c["request_timeout_seconds"])
|
||||
|
||||
consistent = True
|
||||
if scenario == "stale_read":
|
||||
try:
|
||||
business.read_after_write(client, factory, self.c["concurrency"])
|
||||
except Failure as exc:
|
||||
if variant == "protected" or str(exc) != "confirmed message absent from next read":
|
||||
raise
|
||||
consistent = False
|
||||
else:
|
||||
barrier = threading.Barrier(self.c["concurrency"])
|
||||
|
||||
def read(_):
|
||||
local = factory()
|
||||
barrier.wait(timeout=self.c["request_timeout_seconds"])
|
||||
for _ in range(self.c["read_repetitions"]):
|
||||
self.cache_read(local, actor, chat)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=self.c["concurrency"]) as pool:
|
||||
list(pool.map(read, range(self.c["concurrency"])))
|
||||
after = self.hook("metrics", metrics=True)
|
||||
variants.append({"variant": variant, "consistent": consistent,
|
||||
"sql_queries": counter_delta(before, after, "sql_queries"),
|
||||
"cache_hits": counter_delta(before, after, "cache_hits"),
|
||||
"read_latency_ms": percentiles(timings)})
|
||||
if scenario == "stale_read":
|
||||
check(not variants[0]["consistent"] and variants[1]["consistent"], "baseline did not reproduce stale read or protection failed")
|
||||
else:
|
||||
check(variants[1]["sql_queries"] <= limit and variants[1]["sql_queries"] < variants[0]["sql_queries"],
|
||||
"SQL reduction/budget not demonstrated; adapt deterministic stampede adapter")
|
||||
business.read_after_write(self.client(), self.client, self.c["concurrency"])
|
||||
self.cache_restart()
|
||||
return {"scenario": scenario, "variants": variants,
|
||||
"review": "Repeat under fixed resources; review counter scope and experimental limits."}
|
||||
|
||||
def probe(self, mode, restore=False):
|
||||
if not shutil.which("go"):
|
||||
raise Blocked("Go toolchain is required for SQL experiments")
|
||||
sql = self.c["sql"]
|
||||
variable = sql["restore_database_url_env" if restore else "database_url_env"]
|
||||
if not os.environ.get(variable):
|
||||
raise Blocked("set " + variable + " for an explicitly selected test database")
|
||||
env = dict(os.environ, LAB2_SQL_DATABASE_URL=os.environ[variable])
|
||||
args = ["go", "run", "./student-tests/lab2/sqlprobe", "-mode", mode,
|
||||
"-schema", sql["restore_schema" if restore else "source_schema"],
|
||||
"-rows", str(sql["research_rows"] if mode in ("compare", "seed") else sql["plan_rows"]),
|
||||
"-scan-budget", str(sql["scan_budget_rows"]), "-repetitions", str(sql["repetitions"])]
|
||||
out = bounded_command(args, ROOT, 300, env)
|
||||
try:
|
||||
return json.loads(out)
|
||||
except ValueError:
|
||||
raise Failure("SQL probe did not return valid JSON") from None
|
||||
|
||||
def restore(self):
|
||||
self.require_hooks("backup_database", "restore_database")
|
||||
source, empty_target = self.probe("snapshot"), self.probe("snapshot", restore=True)
|
||||
check(source["identity_sha256"] != empty_target["identity_sha256"], "source and restore target are the same database")
|
||||
check(empty_target["empty"], "restore target must contain no application tables")
|
||||
check(source["tables"].get("messages", {}).get("rows", 0) >= 100000, "track 2 needs at least 100000 source messages")
|
||||
started = time.monotonic()
|
||||
self.hook("backup_database")
|
||||
backup_seconds = time.monotonic() - started
|
||||
started = time.monotonic()
|
||||
self.hook("restore_database")
|
||||
restore_seconds = time.monotonic() - started
|
||||
restored = self.probe("snapshot", restore=True)
|
||||
compare_snapshots(source, restored)
|
||||
check(source == self.probe("snapshot"), "source changed during backup/restore; quiesce the fixture")
|
||||
return {"backup_seconds": round(backup_seconds, 4), "restore_seconds": round(restore_seconds, 4),
|
||||
"tables": restored["tables"], "review": "Document recovery/loss boundaries and verify fresh storage scope."}
|
||||
|
||||
|
||||
SUITES = {
|
||||
"auth": "Existing normal auth cases",
|
||||
"business-boundaries": "Title/text/member validation and strict lab2 JSON/UTF-8 cases",
|
||||
"business-cursors": "Both chat-list and message-history pagination, bound cursors, changing limit and ACL",
|
||||
"read-after-write": "100 concurrent confirmations from 10 members are visible immediately",
|
||||
"persistence": "Full restart with original/revoked sessions",
|
||||
"expiry": "Separate API with actual TTL=2",
|
||||
"postgres-failure": "Real PostgreSQL outage and recovery",
|
||||
"cache-usage": "Actual cache hits through an observable API operation",
|
||||
"cache-failure": "Declared critical/fallback cache outage",
|
||||
"cache-restart": "Cache restart preserves confirmations and logout",
|
||||
"query-timeout": "Blocked SQL must produce bounded HTTP 503",
|
||||
"pool-timeout": "Exhausted application pool must produce bounded HTTP 503",
|
||||
"sql-plan": "Actual repository SQL on >=10000 rows, including deep pages",
|
||||
"cache-experiment": "Track 1: reproducible baseline/protection and counters",
|
||||
"sql-experiment": "Track 2: >=100000 skewed rows, two indexes, read/write costs",
|
||||
"backup-restore": "Track 2: fresh target, counts and full ordered digests"
|
||||
}
|
||||
|
||||
|
||||
def execute(h, name):
|
||||
if name in ("auth", "expiry", "persistence"):
|
||||
return h.auth(name)
|
||||
if name == "business-boundaries":
|
||||
return business.boundaries(h.client())
|
||||
if name == "business-cursors":
|
||||
return business.cursors(h.client())
|
||||
if name == "read-after-write":
|
||||
return business.read_after_write(h.client(), h.client, h.c["concurrency"])
|
||||
if name in ("postgres-failure", "cache-failure"):
|
||||
return h.dependency("postgres" if name == "postgres-failure" else "redis")
|
||||
if name in ("query-timeout", "pool-timeout"):
|
||||
return h.timeout("query" if name == "query-timeout" else "pool")
|
||||
if name == "sql-plan":
|
||||
return h.probe("plan")
|
||||
if name == "sql-experiment":
|
||||
return h.probe("compare")
|
||||
if name == "backup-restore":
|
||||
return h.restore()
|
||||
return getattr(h, name.replace("-", "_"))()
|
||||
|
||||
|
||||
def validate_config(config):
|
||||
for key in ("request_timeout_seconds", "hook_timeout_seconds", "operation_budget_seconds"):
|
||||
check(isinstance(config.get(key), (int, float)) and not isinstance(config[key], bool) and config[key] > 0,
|
||||
"positive numeric config value required: " + key)
|
||||
for key, low, high in (("concurrency", 1, 32), ("read_repetitions", 1, 1000)):
|
||||
value = config.get(key)
|
||||
check(isinstance(value, int) and not isinstance(value, bool) and low <= value <= high, "invalid config value: " + key)
|
||||
ttl = config.get("ttl_seconds")
|
||||
check(isinstance(ttl, int) and not isinstance(ttl, bool) and ttl >= 300, "normal suites need ttl_seconds >= 300")
|
||||
check(config.get("track") in (None, "cache", "sql"), "track must be cache, sql or null")
|
||||
sql = config["sql"]
|
||||
for key, minimum in (("plan_rows", 10000), ("research_rows", 100000), ("scan_budget_rows", 1), ("repetitions", 2)):
|
||||
check(isinstance(sql.get(key), int) and not isinstance(sql[key], bool) and sql[key] >= minimum, "invalid SQL parameter: " + key)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, default=Path(__file__).with_name("config.example.json"))
|
||||
parser.add_argument("--suite", action="append", choices=["all"] + list(SUITES))
|
||||
parser.add_argument("--list", action="store_true")
|
||||
parser.add_argument("--allow-hooks", action="store_true")
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.list:
|
||||
for name, purpose in SUITES.items():
|
||||
print(name + ": " + purpose)
|
||||
return 0
|
||||
if not args.suite:
|
||||
parser.error("choose --suite or --list; no infrastructure actions run by default")
|
||||
try:
|
||||
config = json.loads(args.config.read_text())
|
||||
validate_config(config)
|
||||
except (OSError, ValueError, KeyError, Failure):
|
||||
print("BLOCKED: invalid/missing test configuration; credentials suppressed")
|
||||
return 2
|
||||
names = list(args.suite)
|
||||
missing_track = False
|
||||
if "all" in names:
|
||||
names = [name for name in SUITES if name not in ("cache-experiment", "sql-experiment", "backup-restore")]
|
||||
if config["track"] == "cache":
|
||||
names.append("cache-experiment")
|
||||
elif config["track"] == "sql":
|
||||
names.extend(("sql-experiment", "backup-restore"))
|
||||
else:
|
||||
missing_track = True
|
||||
harness, results = Harness(config, args.config, args.allow_hooks), []
|
||||
for name in names:
|
||||
started = time.monotonic()
|
||||
item = {"suite": name}
|
||||
try:
|
||||
item.update(status="PASS", observation=execute(harness, name))
|
||||
except Blocked as exc:
|
||||
item.update(status="BLOCKED", reason=str(exc))
|
||||
except Failure as exc:
|
||||
item.update(status="FAIL", reason=str(exc))
|
||||
except Exception as exc:
|
||||
item.update(status="FAIL", reason="test adapter/runtime error (" + type(exc).__name__ + "); details suppressed")
|
||||
item["duration_seconds"] = round(time.monotonic() - started, 4)
|
||||
results.append(item)
|
||||
print(name + ": " + item["status"] + (" — " + item["reason"] if "reason" in item else ""), flush=True)
|
||||
if missing_track:
|
||||
results.append({"suite": "research-track", "status": "BLOCKED", "reason": "select exactly one track: cache or sql"})
|
||||
report = {"scope": "observed automated scenarios, not an automatic grade or manual report/CI review", "results": results}
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
if any(item["status"] == "FAIL" for item in results):
|
||||
return 1
|
||||
return 2 if any(item["status"] == "BLOCKED" for item in results) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,499 @@
|
||||
// SQL experiment adapter. Mutating modes create only fresh lab2_test_* schemas.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
repository2 "highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"highload/db/migrations"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
type recorder struct {
|
||||
mu sync.Mutex
|
||||
active bool
|
||||
SQL string
|
||||
args []any
|
||||
}
|
||||
|
||||
func (r *recorder) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.active {
|
||||
r.SQL, r.args = data.SQL, append([]any(nil), data.Args...)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
func (*recorder) TraceQueryEnd(context.Context, *pgx.Conn, pgx.TraceQueryEndData) {}
|
||||
|
||||
type fixture struct {
|
||||
admin *pgx.Conn
|
||||
pool *pgxpool.Pool
|
||||
schema string
|
||||
owns bool
|
||||
user string
|
||||
chats []string
|
||||
record recorder
|
||||
researchBudget time.Duration
|
||||
}
|
||||
|
||||
func (f *fixture) cleanup() error {
|
||||
if f.pool != nil {
|
||||
f.pool.Close()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
var cleanupErr error
|
||||
if f.admin != nil {
|
||||
if f.owns {
|
||||
_, cleanupErr = f.admin.Exec(ctx, "DROP SCHEMA "+pgx.Identifier{f.schema}.Sanitize()+" CASCADE")
|
||||
}
|
||||
_ = f.admin.Close(ctx)
|
||||
}
|
||||
return cleanupErr
|
||||
}
|
||||
|
||||
func createFixture(ctx context.Context, url, schema string, rows int) (_ *fixture, err error) {
|
||||
f := &fixture{schema: schema}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
f.cleanup()
|
||||
}
|
||||
}()
|
||||
f.admin, err = pgx.Connect(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = f.admin.Exec(ctx, "CREATE SCHEMA "+pgx.Identifier{schema}.Sanitize())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.owns = true // Never drop a schema unless this invocation created it.
|
||||
cfg, err := pgx.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.RuntimeParams["search_path"] = schema
|
||||
cfg.RuntimeParams["timezone"] = "UTC"
|
||||
cfg.ConnectTimeout = 5 * time.Second
|
||||
db := stdlib.OpenDB(*cfg)
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.Files,
|
||||
goose.WithVerbose(false), goose.WithDisableGlobalRegistry(true),
|
||||
goose.WithSlog(slog.New(slog.NewJSONHandler(io.Discard, nil))))
|
||||
if err == nil {
|
||||
_, err = provider.Up(ctx)
|
||||
}
|
||||
db.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg.MaxConns = 2
|
||||
poolCfg.ConnConfig = cfg
|
||||
poolCfg.ConnConfig.Tracer = &f.record
|
||||
f.pool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.user = uuid.NewString()
|
||||
_, err = f.pool.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)",
|
||||
f.user, "sql_fixture", "Synthetic SQL fixture", "not-a-login-credential")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
id := uuid.NewString()
|
||||
f.chats = append(f.chats, id)
|
||||
if _, err = f.pool.Exec(ctx, "INSERT INTO chats(id,title) VALUES($1,$2)", id, fmt.Sprintf("SQL chat %d", i)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = f.pool.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", id, f.user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
_, err = f.pool.Exec(ctx, `INSERT INTO messages(chat_id,sender_id,text,created_at)
|
||||
SELECT CASE WHEN n%100<70 THEN $1::uuid WHEN n%100<90 THEN $2::uuid
|
||||
WHEN n%100<96 THEN $3::uuid WHEN n%100<99 THEN $4::uuid ELSE $5::uuid END,
|
||||
$6::uuid, 'sql-fixture-'||n, timestamptz '2026-01-01 00:00:00+00'+n*interval '1 millisecond'
|
||||
FROM generate_series(1,$7::integer) n`, f.chats[0], f.chats[1], f.chats[2], f.chats[3], f.chats[4], f.user, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = f.pool.Exec(ctx, "ANALYZE messages")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (f *fixture) position(ctx context.Context) (*repository2.MessagePosition, error) {
|
||||
var p repository2.MessagePosition
|
||||
err := f.pool.QueryRow(ctx, `SELECT id::text,created_at FROM messages WHERE chat_id=$1
|
||||
ORDER BY created_at,id OFFSET (SELECT count(*)*8/10 FROM messages WHERE chat_id=$1) LIMIT 1`, f.chats[0]).Scan(&p.ID, &p.CreatedAt)
|
||||
// OFFSET is used only to select a fixture cursor, never in the measured query.
|
||||
return &p, err
|
||||
}
|
||||
|
||||
func (f *fixture) read(ctx context.Context, after *repository2.MessagePosition) (time.Duration, error) {
|
||||
return f.readChat(ctx, f.chats[0], after)
|
||||
}
|
||||
|
||||
func (f *fixture) readChat(ctx context.Context, chatID string, after *repository2.MessagePosition) (time.Duration, error) {
|
||||
repo := postgres.NewMessageRepository(sqlc.New(f.pool), f.pool)
|
||||
f.record.mu.Lock()
|
||||
f.record.active = true
|
||||
f.record.mu.Unlock()
|
||||
started := time.Now()
|
||||
var items []*model.Message
|
||||
var err error
|
||||
if f.researchBudget > 0 {
|
||||
items, err = f.researchRead(ctx, chatID, after)
|
||||
} else {
|
||||
items, err = repo.GetMessagesByChatID(ctx, chatID, 51, after)
|
||||
}
|
||||
elapsed := time.Since(started)
|
||||
f.record.mu.Lock()
|
||||
f.record.active = false
|
||||
f.record.mu.Unlock()
|
||||
if err == nil && len(items) != 51 {
|
||||
err = fmt.Errorf("fixture history returned %d rows instead of 51", len(items))
|
||||
}
|
||||
for i := 1; err == nil && i < len(items); i++ {
|
||||
if items[i].CreatedAt.Before(items[i-1].CreatedAt) {
|
||||
err = errors.New("history out of order")
|
||||
}
|
||||
}
|
||||
return elapsed, err
|
||||
}
|
||||
|
||||
func maxVisited(node map[string]any) float64 {
|
||||
number := func(key string) float64 { value, _ := node[key].(float64); return value }
|
||||
visited := (number("Actual Rows") + number("Rows Removed by Filter") + number("Rows Removed by Index Recheck")) * number("Actual Loops")
|
||||
children, _ := node["Plans"].([]any)
|
||||
for _, child := range children {
|
||||
if child, ok := child.(map[string]any); ok {
|
||||
visited = max(visited, maxVisited(child))
|
||||
}
|
||||
}
|
||||
return visited
|
||||
}
|
||||
|
||||
func (f *fixture) plan(ctx context.Context, after *repository2.MessagePosition) (map[string]any, error) {
|
||||
return f.planChat(ctx, f.chats[0], after)
|
||||
}
|
||||
|
||||
func (f *fixture) planChat(ctx context.Context, chatID string, after *repository2.MessagePosition) (map[string]any, error) {
|
||||
if _, err := f.readChat(ctx, chatID, after); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.record.mu.Lock()
|
||||
query, args := f.record.SQL, append([]any(nil), f.record.args...)
|
||||
f.record.mu.Unlock()
|
||||
if !strings.Contains(query, "GetMessagesByChatID") {
|
||||
return nil, errors.New("adapt query recorder to repository SQL")
|
||||
}
|
||||
var raw []byte
|
||||
err := f.pool.QueryRow(ctx, "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) "+query, args...).Scan(&raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var plan []map[string]any
|
||||
if err = json.Unmarshal(raw, &plan); err != nil || len(plan) != 1 {
|
||||
return nil, errors.New("invalid EXPLAIN output")
|
||||
}
|
||||
node, ok := plan[0]["Plan"].(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("missing EXPLAIN plan")
|
||||
}
|
||||
return map[string]any{"explain": plan[0], "max_visited_rows": maxVisited(node)}, nil
|
||||
}
|
||||
|
||||
func latency(values []time.Duration) map[string]float64 {
|
||||
sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
|
||||
result := map[string]float64{}
|
||||
for _, p := range []int{50, 95, 99} {
|
||||
i := (len(values)*p+99)/100 - 1
|
||||
result[fmt.Sprintf("p%d", p)] = float64(values[i].Microseconds()) / 1000
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (f *fixture) compare(ctx context.Context, repetitions int) ([]map[string]any, error) {
|
||||
position, err := f.position(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Only this fresh fixture schema is changed; application migrations stay intact.
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX idx_messages_chat_created_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var results []map[string]any
|
||||
for _, columns := range []string{"chat_id", "chat_id,created_at,id"} {
|
||||
if _, err = f.pool.Exec(ctx, "CREATE INDEX lab2_history_variant ON messages("+columns+")"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = f.pool.Exec(ctx, "ANALYZE messages"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err = f.read(ctx, position); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var reads, writes []time.Duration
|
||||
for i := 0; i < repetitions; i++ {
|
||||
duration, err := f.read(ctx, position)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reads = append(reads, duration)
|
||||
prefix := "write-fixture-" + uuid.NewString() + "-"
|
||||
started := time.Now()
|
||||
tx, err := f.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO messages(chat_id,sender_id,text)
|
||||
SELECT $1::uuid,$2::uuid,$3::text||n FROM generate_series(1,200) n`, f.chats[0], f.user, prefix)
|
||||
if err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
writes = append(writes, time.Since(started))
|
||||
if _, err = f.pool.Exec(ctx, "DELETE FROM messages WHERE text LIKE $1", prefix+"%"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
first, err := f.plan(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deep, err := f.plan(ctx, position)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var size int64
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_relation_size('lab2_history_variant')").Scan(&size); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results = append(results, map[string]any{"columns": columns, "read_ms": latency(reads), "insert_200_with_commit_ms": latency(writes), "index_bytes": size, "first_page": first, "deep_page": deep})
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX lab2_history_variant"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func snapshot(ctx context.Context, url, schema string) (map[string]any, error) {
|
||||
cfg, err := pgx.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.RuntimeParams["timezone"] = "UTC"
|
||||
cfg.RuntimeParams["datestyle"] = "ISO, YMD"
|
||||
cfg.ConnectTimeout = 5 * time.Second
|
||||
conn, err := pgx.ConnectConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close(context.Background())
|
||||
tx, err := conn.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
identity := sha256.Sum256([]byte(fmt.Sprintf("%s:%d/%s", cfg.Host, cfg.Port, cfg.Database)))
|
||||
tables := map[string]any{}
|
||||
missing := 0
|
||||
for _, table := range []struct{ name, order string }{{"users", "id"}, {"chats", "id"}, {"chat_members", "chat_id,user_id"}, {"messages", "id"}} {
|
||||
qualified := pgx.Identifier{schema, table.name}.Sanitize()
|
||||
var exists bool
|
||||
if err = tx.QueryRow(ctx, "SELECT to_regclass($1) IS NOT NULL", qualified).Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
missing++
|
||||
continue
|
||||
}
|
||||
rows, err := tx.Query(ctx, "SELECT row_to_json(t)::text FROM "+qualified+" t ORDER BY "+table.order)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
digest := sha256.New()
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
var row string
|
||||
if err = rows.Scan(&row); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
_, _ = io.WriteString(digest, row+"\n")
|
||||
count++
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tables[table.name] = map[string]any{"rows": count, "sha256": hex.EncodeToString(digest.Sum(nil))}
|
||||
}
|
||||
if missing != 0 && missing != 4 {
|
||||
return nil, errors.New("snapshot schema contains only part of the application tables")
|
||||
}
|
||||
return map[string]any{"identity_sha256": hex.EncodeToString(identity[:]), "empty": missing == 4, "tables": tables}, nil
|
||||
}
|
||||
|
||||
func execute(ctx context.Context, mode, url, schema string, rows, budget, repetitions int) (result map[string]any, err error) {
|
||||
if mode == "snapshot" {
|
||||
return snapshot(ctx, url, schema)
|
||||
}
|
||||
if rows < 10000 || ((mode == "compare" || mode == "seed") && rows < 100000) || repetitions < 2 || budget < 1 {
|
||||
return nil, errors.New("invalid experiment limits")
|
||||
}
|
||||
if schema == "public" || mode != "seed" {
|
||||
schema = "lab2_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
}
|
||||
if !strings.HasPrefix(schema, "lab2_test_") {
|
||||
return nil, errors.New("fixture schema must start with lab2_test_")
|
||||
}
|
||||
f, err := createFixture(ctx, url, schema, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if cleanupErr := f.cleanup(); err == nil {
|
||||
err = cleanupErr
|
||||
}
|
||||
}()
|
||||
result = map[string]any{"mode": mode, "rows": rows, "schema": schema, "chat_distribution_percent": []int{70, 20, 6, 3, 1}}
|
||||
var actualRows int
|
||||
var postgresVersion string
|
||||
if err = f.pool.QueryRow(ctx, "SELECT count(*) FROM messages").Scan(&actualRows); err != nil || actualRows != rows {
|
||||
return nil, errors.New("fixture row count differs from the requested dataset")
|
||||
}
|
||||
if err = f.pool.QueryRow(ctx, "SHOW server_version").Scan(&postgresVersion); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
distribution, queryErr := f.pool.Query(ctx, "SELECT count(*) FROM messages GROUP BY chat_id ORDER BY count(*) DESC")
|
||||
if queryErr != nil {
|
||||
return nil, queryErr
|
||||
}
|
||||
var chatCounts []int
|
||||
for distribution.Next() {
|
||||
var count int
|
||||
if err = distribution.Scan(&count); err != nil {
|
||||
distribution.Close()
|
||||
return nil, err
|
||||
}
|
||||
chatCounts = append(chatCounts, count)
|
||||
}
|
||||
err = distribution.Err()
|
||||
distribution.Close()
|
||||
if err != nil || len(chatCounts) != 5 || chatCounts[0] <= chatCounts[4] {
|
||||
return nil, errors.New("fixture does not demonstrate skewed chat sizes")
|
||||
}
|
||||
result["actual_rows"], result["chat_message_counts"] = actualRows, chatCounts
|
||||
result["postgres_version"], result["go_version"] = postgresVersion, runtime.Version()
|
||||
if mode == "seed" {
|
||||
f.owns = false
|
||||
result["kept_fixture"] = true
|
||||
return result, nil
|
||||
}
|
||||
if mode == "compare" {
|
||||
variants, err := f.compare(ctx, repetitions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result["variants"] = variants
|
||||
result["limitations"] = "Warm single-host prototype; write cleanup can leave bloat. Repeat under fixed resources and review plans, cold/generic plans and loss boundaries."
|
||||
return result, nil
|
||||
}
|
||||
if mode != "plan" {
|
||||
return nil, errors.New("unknown mode")
|
||||
}
|
||||
position, err := f.position(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
first, err := f.plan(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deep, err := f.plan(ctx, position)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if first["max_visited_rows"].(float64) > float64(budget) || deep["max_visited_rows"].(float64) > float64(budget) {
|
||||
return nil, errors.New("history exceeds chosen scan budget")
|
||||
}
|
||||
result["first_page"], result["deep_page"], result["scan_budget_rows"] = first, deep, budget
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
mode := flag.String("mode", "snapshot", "snapshot, plan, compare or seed")
|
||||
schema := flag.String("schema", "public", "snapshot schema or fresh lab2_test_* seed schema")
|
||||
rows := flag.Int("rows", 10000, "fixture message count")
|
||||
budget := flag.Int("scan-budget", 1000, "engineering threshold, not a teacher-mandated constant")
|
||||
repetitions := flag.Int("repetitions", 5, "measurement samples per variant")
|
||||
series := flag.Int("series", 4, "independent AB/BA research rounds (even, >= 4)")
|
||||
writeBatches := flag.Int("write-batches", 20, "committed batches of 200 rows per research trial")
|
||||
timeout := flag.Duration("timeout", 3*time.Minute, "total SQL probe execution budget")
|
||||
flag.Parse()
|
||||
url := os.Getenv("LAB2_SQL_DATABASE_URL")
|
||||
if url == "" {
|
||||
fmt.Fprintln(os.Stderr, "set LAB2_SQL_DATABASE_URL for a dedicated test database")
|
||||
os.Exit(2)
|
||||
}
|
||||
if *mode != "snapshot" && *mode != "plan" && *mode != "compare" && *mode != "seed" && *mode != "research" {
|
||||
os.Exit(2)
|
||||
}
|
||||
signals, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
ctx, cancel := context.WithTimeout(signals, *timeout)
|
||||
defer cancel()
|
||||
var result map[string]any
|
||||
var err error
|
||||
if *mode == "research" {
|
||||
result, err = research(ctx, url, *rows, *repetitions, *series, *writeBatches)
|
||||
} else {
|
||||
result, err = execute(ctx, *mode, url, *schema, *rows, *budget, *repetitions)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "SQL probe failed; private error details suppressed")
|
||||
os.Exit(1)
|
||||
}
|
||||
if err = json.NewEncoder(os.Stdout).Encode(result); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPlanBudgetIncludesFilteredRowsAndLoops(t *testing.T) {
|
||||
plan := map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(1),
|
||||
"Plans": []any{map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(2),
|
||||
"Rows Removed by Filter": float64(8000)}}}
|
||||
if maxVisited(plan) != 16102 {
|
||||
t.Fatal("deep scan hidden by LIMIT or ignored loop count")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanBudgetDoesNotDoubleCountParentAndChild(t *testing.T) {
|
||||
plan := map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(1),
|
||||
"Plans": []any{map[string]any{"Actual Rows": float64(51), "Actual Loops": float64(1)}}}
|
||||
if maxVisited(plan) != 51 {
|
||||
t.Fatal("same tuples double-counted through the plan hierarchy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
repository2 "highload/internal/repository"
|
||||
)
|
||||
|
||||
// Research reuses the actual repository SQL. No application index is changed:
|
||||
// the fixture owns a fresh schema and removes it when the experiment finishes.
|
||||
func research(ctx context.Context, url string, rows, repetitions, series, batches int) (result map[string]any, err error) {
|
||||
stage := "validate"
|
||||
defer func() {
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "research: failed at "+stage)
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
fmt.Fprintln(os.Stderr, "sqlstate: "+pgErr.Code)
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
fmt.Fprintln(os.Stderr, "research: deadline exceeded")
|
||||
}
|
||||
if errors.Is(err, repository2.ErrServiceUnavailable) {
|
||||
fmt.Fprintln(os.Stderr, "research: repository unavailable")
|
||||
}
|
||||
for _, text := range []string{"timeout", "context deadline exceeded", "invalid input", "unexpected page", "history out of order"} {
|
||||
if strings.Contains(err.Error(), text) {
|
||||
fmt.Fprintln(os.Stderr, "research: "+text)
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(err.Error(), "fixture history returned ") {
|
||||
fmt.Fprintln(os.Stderr, "research: "+err.Error())
|
||||
}
|
||||
}
|
||||
}()
|
||||
if rows < 100000 || rows%100 != 0 || repetitions < 30 || series < 4 || series%2 != 0 || batches < 10 {
|
||||
return nil, errors.New("research needs >=100k rows, >=30 reads, even >=4 series, >=10 write batches")
|
||||
}
|
||||
schema := "lab2_test_" + uuid.NewString()[:8] + "_research"
|
||||
stage = "create-fixture"
|
||||
f, err := createFixture(ctx, url, schema, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Preserve the API's one-second policy. Only the offline SQL experiment uses
|
||||
// a larger, identical budget for both indexes, so slow baselines are measurable.
|
||||
f.researchBudget = 10 * time.Second
|
||||
defer func() {
|
||||
if cleanupErr := f.cleanup(); err == nil {
|
||||
err = cleanupErr
|
||||
}
|
||||
}()
|
||||
stage = "drop-original-index"
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX idx_messages_chat_created_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Disable autovacuum only for the disposable table to control trial cleanup.
|
||||
if _, err = f.pool.Exec(ctx, "ALTER TABLE messages SET (autovacuum_enabled=false)"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Fixed message body size; index keys and logical rows remain identical in A/B.
|
||||
stage = "payload"
|
||||
if _, err = f.pool.Exec(ctx, "UPDATE messages SET text=rpad(text,256,'x')"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var version string
|
||||
if err = f.pool.QueryRow(ctx, "SHOW server_version").Scan(&version); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type readCase struct {
|
||||
name, chat string
|
||||
after *repository2.MessagePosition
|
||||
}
|
||||
var cases []readCase
|
||||
for _, item := range []struct {
|
||||
name string
|
||||
index int
|
||||
}{{"large", 0}, {"medium", 2}, {"small", 4}} {
|
||||
stage = "cursor-" + item.name
|
||||
chatID := f.chats[item.index]
|
||||
position := &repository2.MessagePosition{}
|
||||
if err = f.pool.QueryRow(ctx, `SELECT id::text,created_at FROM messages WHERE chat_id=$1
|
||||
ORDER BY created_at,id OFFSET (SELECT count(*)*8/10 FROM messages WHERE chat_id=$1) LIMIT 1`, chatID).Scan(&position.ID, &position.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cases = append(cases, readCase{item.name + "_first", chatID, nil}, readCase{item.name + "_deep", chatID, position})
|
||||
}
|
||||
stage = "initial-digest"
|
||||
before, err := f.messageDigest(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var trials []map[string]any
|
||||
for round := 0; round < series; round++ {
|
||||
order := []string{"A", "B"}
|
||||
if round%2 == 1 {
|
||||
order = []string{"B", "A"}
|
||||
}
|
||||
for ordinal, variant := range order {
|
||||
stage = "vacuum-" + variant
|
||||
// Remove dead tuples and reset physical bloat between trials, outside timing.
|
||||
if _, err = f.pool.Exec(ctx, "VACUUM (FULL, ANALYZE) messages"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
columns := "chat_id"
|
||||
if variant == "B" {
|
||||
columns = "chat_id,created_at,id"
|
||||
}
|
||||
buildStart := time.Now()
|
||||
stage = "build-index-" + variant
|
||||
if _, err = f.pool.Exec(ctx, "CREATE INDEX lab2_history_variant ON messages("+columns+")"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buildMS := float64(time.Since(buildStart).Microseconds()) / 1000
|
||||
if _, err = f.pool.Exec(ctx, "ANALYZE messages"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var indexBytes, tableBytes int64
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_relation_size('lab2_history_variant'),pg_relation_size('messages')").Scan(&indexBytes, &tableBytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
readResults := map[string]any{}
|
||||
for _, c := range cases {
|
||||
stage = "warmup-" + variant + "-" + c.name
|
||||
for warmup := 0; warmup < 5; warmup++ {
|
||||
if _, err = f.readChat(ctx, c.chat, c.after); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var timings []time.Duration
|
||||
var raw []float64
|
||||
started := time.Now()
|
||||
stage = "read-" + variant + "-" + c.name
|
||||
for n := 0; n < repetitions; n++ {
|
||||
d, readErr := f.readChat(ctx, c.chat, c.after)
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
timings = append(timings, d)
|
||||
raw = append(raw, float64(d.Microseconds())/1000)
|
||||
}
|
||||
elapsed := time.Since(started).Seconds()
|
||||
stage = "plan-" + variant + "-" + c.name
|
||||
plan, planErr := f.planChat(ctx, c.chat, c.after)
|
||||
if planErr != nil {
|
||||
return nil, planErr
|
||||
}
|
||||
readResults[c.name] = map[string]any{"samples_ms": raw, "latency_ms": latency(timings), "successful_rps": float64(repetitions) / elapsed, "elapsed_seconds": elapsed, "plan": plan}
|
||||
}
|
||||
var writes []time.Duration
|
||||
var writeMS []float64
|
||||
var walBytes []int64
|
||||
for n := 0; n < batches; n++ {
|
||||
stage = "write-" + variant
|
||||
var lsn string
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_current_wal_insert_lsn()::text").Scan(&lsn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
started := time.Now()
|
||||
tx, txErr := f.pool.Begin(ctx)
|
||||
if txErr != nil {
|
||||
return nil, txErr
|
||||
}
|
||||
_, txErr = tx.Exec(ctx, `INSERT INTO messages(chat_id,sender_id,text)
|
||||
SELECT $1::uuid,$2::uuid,rpad('research-write-'||n,256,'x') FROM generate_series(1,200) n`, f.chats[0], f.user)
|
||||
if txErr == nil {
|
||||
txErr = tx.Commit(ctx)
|
||||
} else {
|
||||
_ = tx.Rollback(context.Background())
|
||||
}
|
||||
if txErr != nil {
|
||||
return nil, txErr
|
||||
}
|
||||
d := time.Since(started)
|
||||
writes = append(writes, d)
|
||||
writeMS = append(writeMS, float64(d.Microseconds())/1000)
|
||||
var delta int64
|
||||
if err = f.pool.QueryRow(ctx, "SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),$1::pg_lsn)::bigint", lsn).Scan(&delta); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
walBytes = append(walBytes, delta)
|
||||
}
|
||||
stage = "delete-fixture-writes-" + variant
|
||||
if _, err = f.pool.Exec(ctx, "DELETE FROM messages WHERE text LIKE 'research-write-%'"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stage = "verify-dataset-" + variant
|
||||
after, digestErr := f.messageDigest(ctx)
|
||||
if digestErr != nil || after != before {
|
||||
return nil, errors.New("logical dataset changed between trials")
|
||||
}
|
||||
trials = append(trials, map[string]any{"series": round + 1, "order": ordinal + 1, "variant": variant, "columns": columns, "read_cases": readResults, "index_bytes": indexBytes, "table_bytes": tableBytes, "build_ms": buildMS, "insert_200_with_commit_ms": latency(writes), "write_samples_ms": writeMS, "write_wal_bytes": walBytes, "dataset_sha256": before})
|
||||
fmt.Fprintf(os.Stderr, "series %d variant %s complete\n", round+1, variant)
|
||||
stage = "drop-index-" + variant
|
||||
if _, err = f.pool.Exec(ctx, "DROP INDEX lab2_history_variant"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return map[string]any{"mode": "research", "rows": rows, "chat_counts": []int{rows * 70 / 100, rows * 20 / 100, rows * 6 / 100, rows * 3 / 100, rows / 100}, "payload_bytes": 256, "postgres_version": version, "series": series, "reads_per_case": repetitions, "write_batches_per_trial": batches, "rows_per_write_batch": 200, "warmup_per_case": 5, "concurrent_clients": 1, "sql_experiment_timeout_seconds": 10, "application_repository_timeout_seconds": 1, "dataset_sha256": before, "trials": trials, "limitations": "Warm sequential closed-loop SQL through the same generated sqlc query; no HTTP/KDF. Offline query budget 10s, application repository unchanged at 1s. Same logical rows, VACUUM FULL and rebuild before trials. pgx prepared-plan behavior is retained. WAL is cluster-wide on a dedicated quiet instance; sampled CPU includes administration. No cold-cache or sustained-capacity claim."}, nil
|
||||
}
|
||||
|
||||
func (f *fixture) researchRead(ctx context.Context, chatID string, after *repository2.MessagePosition) ([]*model.Message, error) {
|
||||
queryCtx, cancel := context.WithTimeout(ctx, f.researchBudget)
|
||||
defer cancel()
|
||||
var id pgtype.UUID
|
||||
if err := id.Scan(chatID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
params := sqlc.GetMessagesByChatIDParams{ChatID: id, LimitCount: 51}
|
||||
if after != nil {
|
||||
params.AfterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if err := params.AfterID.Scan(after.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
rows, err := sqlc.New(f.pool).GetMessagesByChatID(queryCtx, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]*model.Message, len(rows))
|
||||
for i, m := range rows {
|
||||
items[i] = &model.Message{ID: m.ID.String(), ChatID: m.ChatID.String(), SenderID: m.SenderID.String(), Text: m.Text, CreatedAt: m.CreatedAt.Time}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (f *fixture) messageDigest(ctx context.Context) (string, error) {
|
||||
rows, err := f.pool.Query(ctx, "SELECT row_to_json(m)::text FROM messages m ORDER BY id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
h := sha256.New()
|
||||
for rows.Next() {
|
||||
var line string
|
||||
if err = rows.Scan(&line); err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, _ = fmt.Fprintln(h, line)
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rebuild the report's index-comparison aggregates from retained raw samples.
|
||||
|
||||
This reads evidence only; it never starts a database or changes test assertions.
|
||||
Nearest-rank percentiles match sqlprobe. No confidence/SLO claim is implied.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
|
||||
|
||||
def percentile(values, percent):
|
||||
ordered = sorted(values)
|
||||
if not ordered or any(not math.isfinite(v) or v < 0 for v in ordered):
|
||||
raise ValueError('Missing or invalid timing samples')
|
||||
return ordered[max(0, math.ceil(len(ordered) * percent / 100) - 1)]
|
||||
|
||||
|
||||
def summarize(directory):
|
||||
data = json.loads((directory / 'indexes.json').read_text())
|
||||
trials = data['trials']
|
||||
if len(trials) != data['series'] * 2 or any(t['dataset_sha256'] != data['dataset_sha256'] for t in trials):
|
||||
raise ValueError('Incomplete trials or changed logical dataset')
|
||||
rows, writes = [], []
|
||||
for variant in ('A', 'B'):
|
||||
selected = [t for t in trials if t['variant'] == variant]
|
||||
if len(selected) != data['series']:
|
||||
raise ValueError('Unbalanced A/B series')
|
||||
for case in ('large_first', 'large_deep', 'medium_first', 'medium_deep', 'small_first', 'small_deep'):
|
||||
if any(len(t['read_cases'][case]['samples_ms']) != data['reads_per_case'] for t in selected):
|
||||
raise ValueError('Read sample count differs from the protocol')
|
||||
samples = [x for t in selected for x in t['read_cases'][case]['samples_ms']]
|
||||
elapsed = sum(t['read_cases'][case]['elapsed_seconds'] for t in selected)
|
||||
rows.append({'case': case, 'variant': variant, 'n': len(samples),
|
||||
**{'p' + str(p) + '_ms': percentile(samples, p) for p in (50, 95, 99)},
|
||||
'successful_rps': len(samples) / elapsed,
|
||||
'trial_p50_min': min(t['read_cases'][case]['latency_ms']['p50'] for t in selected),
|
||||
'trial_p50_max': max(t['read_cases'][case]['latency_ms']['p50'] for t in selected)})
|
||||
if any(len(t['write_samples_ms']) != data['write_batches_per_trial'] for t in selected):
|
||||
raise ValueError('Write sample count differs from the protocol')
|
||||
samples = [x for t in selected for x in t['write_samples_ms']]
|
||||
wal = [x for t in selected for x in t['write_wal_bytes']]
|
||||
writes.append({'variant': variant, 'batches': len(samples), 'rows_per_batch': data['rows_per_write_batch'],
|
||||
**{'p' + str(p) + '_ms': percentile(samples, p) for p in (50, 95, 99)},
|
||||
'median_wal_bytes': statistics.median(wal), 'index_bytes': selected[0]['index_bytes'],
|
||||
'median_build_ms': statistics.median(t['build_ms'] for t in selected)})
|
||||
rows.sort(key=lambda row: (row['case'], row['variant']))
|
||||
report = {'status': 'PASS', 'scope': 'index observations only; full run status is summary.json',
|
||||
'read_requests': sum(r['n'] for r in rows), 'read_errors': 0,
|
||||
'read_cases': rows, 'write_variants': writes}
|
||||
with (directory / 'READS.csv').open('w', newline='') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
(directory / 'comparison-summary.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
print('PASS: aggregates rebuilt from ' + str(report['read_requests']) + ' retained read samples')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('directory', type=Path)
|
||||
summarize(parser.parse_args().directory.resolve())
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Offline regression tests for the test harness, not evidence about the API."""
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import run as harness
|
||||
|
||||
|
||||
class HarnessTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.config = json.loads(Path(__file__).with_name("config.example.json").read_text())
|
||||
|
||||
def test_default_all_is_blocked_and_does_not_pretend_success(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory) / "result.json"
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if key not in ("LAB2_BASE_URL", "LAB2_EXPIRY_BASE_URL", "LAB2_TEST_DATABASE_URL", "LAB2_RESTORED_DATABASE_URL")}
|
||||
result = subprocess.run([sys.executable, str(Path(harness.__file__)), "--suite", "all", "--output", str(output)],
|
||||
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
items = json.loads(output.read_text())["results"]
|
||||
self.assertGreater(len(items), 10)
|
||||
self.assertTrue(all(item["status"] == "BLOCKED" for item in items))
|
||||
|
||||
def test_hooks_need_both_explicit_opt_in_and_real_configuration(self):
|
||||
h = harness.Harness(self.config, Path(__file__))
|
||||
with self.assertRaises(harness.Blocked):
|
||||
h.require_hooks("stop_postgres")
|
||||
h.allow_hooks = True
|
||||
with self.assertRaises(harness.Blocked):
|
||||
h.require_hooks("stop_postgres")
|
||||
|
||||
def test_recovery_runs_even_when_failure_hook_partially_fails(self):
|
||||
config = copy.deepcopy(self.config)
|
||||
config["hooks"].update(stop_postgres=["not-executed"], start_postgres=["not-executed"])
|
||||
h = harness.Harness(config, Path(__file__), True)
|
||||
calls = []
|
||||
|
||||
def hook(name):
|
||||
calls.append(name)
|
||||
if name == "stop_postgres":
|
||||
raise harness.Failure("synthetic partial failure")
|
||||
|
||||
h.hook = hook
|
||||
with self.assertRaises(harness.Failure):
|
||||
with h.disruption("stop_postgres", "start_postgres"):
|
||||
self.fail("failed setup must not execute test body")
|
||||
self.assertEqual(calls, ["stop_postgres", "start_postgres"])
|
||||
|
||||
def test_adapter_output_is_not_exposed_on_failure(self):
|
||||
with self.assertRaises(harness.Failure) as error:
|
||||
harness.bounded_command([sys.executable, "-c", "print('synthetic-private-marker'); raise SystemExit(7)"],
|
||||
Path(__file__).parent, 3)
|
||||
self.assertNotIn("synthetic-private-marker", str(error.exception))
|
||||
|
||||
def test_unimplemented_adapter_is_blocked(self):
|
||||
with self.assertRaises(harness.Blocked):
|
||||
harness.bounded_command([sys.executable, "-c", "raise SystemExit(2)"], Path(__file__).parent, 3)
|
||||
|
||||
def test_counter_reset_missing_and_boolean_do_not_pass(self):
|
||||
for before, after in (({}, {}), ({"sql_queries": 5}, {"sql_queries": 4}),
|
||||
({"sql_queries": False}, {"sql_queries": True})):
|
||||
with self.subTest(before=before):
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.counter_delta(before, after, "sql_queries")
|
||||
self.assertEqual(harness.counter_delta({"sql_queries": 5}, {"sql_queries": 8}, "sql_queries"), 3)
|
||||
|
||||
def test_snapshot_comparison_rejects_missing_changed_or_same_database(self):
|
||||
tables = {name: {"rows": 3, "sha256": "a" * 64}
|
||||
for name in ("users", "chats", "chat_members", "messages")}
|
||||
source = {"identity_sha256": "source", "empty": False, "tables": tables}
|
||||
restored = dict(source, identity_sha256="target")
|
||||
harness.compare_snapshots(source, restored)
|
||||
for broken in (source, dict(restored, tables={}), dict(restored, empty=True)):
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.compare_snapshots(source, broken)
|
||||
broken = copy.deepcopy(restored)
|
||||
broken["tables"]["messages"]["sha256"] = "b" * 64
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.compare_snapshots(source, broken)
|
||||
|
||||
def test_client_timeout_is_failure_not_a_successful_server_timeout(self):
|
||||
config = copy.deepcopy(self.config)
|
||||
config["hooks"].update(block_query=["not-executed"], unblock_query=["not-executed"])
|
||||
h = harness.Harness(config, Path(__file__), True)
|
||||
calls = []
|
||||
h.hook = lambda name: calls.append(name)
|
||||
|
||||
class FakeClient:
|
||||
def user(self, _):
|
||||
return {"id": "fixture", "token": "never-printed"}
|
||||
|
||||
def call(self, method, path, expected=200, **kwargs):
|
||||
if expected == 503:
|
||||
raise harness.Failure("connection timeout")
|
||||
return {}
|
||||
|
||||
h.client = lambda **_: FakeClient()
|
||||
with self.assertRaises(harness.Failure):
|
||||
h.timeout("query")
|
||||
self.assertEqual(calls, ["block_query", "unblock_query"])
|
||||
|
||||
def test_fixture_size_thresholds_are_not_silently_lowered(self):
|
||||
for key, value in (("plan_rows", 9999), ("research_rows", 99999), ("repetitions", 1)):
|
||||
config = copy.deepcopy(self.config)
|
||||
config["sql"][key] = value
|
||||
with self.assertRaises(harness.Failure):
|
||||
harness.validate_config(config)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user