This commit is contained in:
@@ -1,9 +1,28 @@
|
||||
# Заготовки проверок lab2 на оценку 5
|
||||
# Проверки 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).
|
||||
Основание: [полный чек-лист](../../LAB2_CHECKLIST.md), README/COURSE,
|
||||
Основание: [требования лабораторной](../../README.md), README/COURSE,
|
||||
contracts/README и OpenAPI преподавателя. Ожидаемые API-статусы и границы
|
||||
не подгоняются под текущие ответы сервера.
|
||||
|
||||
@@ -27,6 +46,14 @@ python3 student-tests/lab2/run.py \
|
||||
через 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 ничего не запускается. Пустой
|
||||
|
||||
@@ -17,7 +17,7 @@ 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 track1 import Sampler
|
||||
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)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import check, timestamp
|
||||
from validation_edges import acceptance as json_acceptance
|
||||
|
||||
|
||||
def room(c, actor, members=None, title="Lab2 business fixture"):
|
||||
@@ -48,6 +49,53 @@ def boundaries(c):
|
||||
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"})
|
||||
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"})
|
||||
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):
|
||||
@@ -69,23 +117,31 @@ def cursors(c):
|
||||
c.call("GET", path, 404, actor=outsider)
|
||||
c.call("POST", path, 404, actor=outsider, body={"text": "hidden"})
|
||||
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):
|
||||
actor = c.user("concurrent")
|
||||
chat = room(c, actor)
|
||||
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()
|
||||
confirmed = local.message(actor, chat, "Read-after-write " + str(index))["json"]
|
||||
page = local.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
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(min(32, concurrency * 4))))
|
||||
check({m["id"] for m in history(c, actor, chat)} == {m["id"] for m in messages},
|
||||
"concurrent writes lost or duplicated confirmations")
|
||||
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,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."}
|
||||
@@ -20,6 +20,7 @@ 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
|
||||
|
||||
@@ -333,9 +334,9 @@ class Harness:
|
||||
|
||||
SUITES = {
|
||||
"auth": "Existing normal auth cases",
|
||||
"business-boundaries": "Title/text/member validation and malformed JSON",
|
||||
"business-cursors": "Cursor binding, changing limit, empty/complete pages and ACL",
|
||||
"read-after-write": "Concurrent confirmations are visible immediately",
|
||||
"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",
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
|
||||
"highload/db/migrations"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -50,13 +51,14 @@ func (r *recorder) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.Tr
|
||||
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
|
||||
admin *pgx.Conn
|
||||
pool *pgxpool.Pool
|
||||
schema string
|
||||
owns bool
|
||||
user string
|
||||
chats []string
|
||||
record recorder
|
||||
researchBudget time.Duration
|
||||
}
|
||||
|
||||
func (f *fixture) cleanup() error {
|
||||
@@ -160,18 +162,28 @@ ORDER BY created_at,id OFFSET (SELECT count(*)*8/10 FROM messages WHERE chat_id=
|
||||
}
|
||||
|
||||
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.record.mu.Lock()
|
||||
f.record.active = true
|
||||
f.record.mu.Unlock()
|
||||
started := time.Now()
|
||||
items, err := repo.GetMessagesByChatID(ctx, f.chats[0], 51, after)
|
||||
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 = errors.New("fixture history returned an unexpected page length")
|
||||
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) {
|
||||
@@ -194,7 +206,11 @@ func maxVisited(node map[string]any) float64 {
|
||||
}
|
||||
|
||||
func (f *fixture) plan(ctx context.Context, after *repository2.MessagePosition) (map[string]any, error) {
|
||||
if _, err := f.read(ctx, after); err != nil {
|
||||
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()
|
||||
@@ -450,20 +466,29 @@ func main() {
|
||||
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" {
|
||||
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, 3*time.Minute)
|
||||
ctx, cancel := context.WithTimeout(signals, *timeout)
|
||||
defer cancel()
|
||||
result, err := execute(ctx, *mode, url, *schema, *rows, *budget, *repetitions)
|
||||
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)
|
||||
|
||||
@@ -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())
|
||||
Reference in New Issue
Block a user