forked from mtusi2026/mtusi2026lab2
Реализовать лабораторную 2: PostgreSQL, Bearer-сессии и Valkey
Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход, opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON, keyset-пагинацию по индексу, миграции, compose-стенд и собственные проверки уровня 3/4. Трек 5 — план запроса и восстановление.
This commit is contained in:
@@ -0,0 +1,520 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level-5 track 2: query plan and recovery.
|
||||
|
||||
Experiment (contract: README.md "Оценка 5", track 2):
|
||||
* build >=100 000 messages in six chats of uneven size (60000, 25000,
|
||||
10000, 4000, 900, 100);
|
||||
* compare the production composite index (chat_id, created_at, id) with a
|
||||
naive chat_id-only index for the same keyset page, including
|
||||
EXPLAIN (ANALYZE, BUFFERS) and a write-cost microbenchmark;
|
||||
* take a PostgreSQL custom-format backup, restore it into a NEW PostgreSQL
|
||||
container with a NEW volume, and reconcile row counts, per-chat counts,
|
||||
an ordered checksum and one selected message;
|
||||
* record wall-clock timings, the source revision, image id, host limits and
|
||||
the raw plans in evidence/track5/.
|
||||
|
||||
The script is explicit and safe for the local teaching stand: the temporary
|
||||
restore container and volume are removed in `finally`; the main lab volumes are
|
||||
never touched. It is idempotent for a single stand because research chats are
|
||||
looked up by title+owner and only the missing message range is inserted.
|
||||
"""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check # noqa: E402
|
||||
|
||||
POSTGRES = 'mtusi-lab2-melnikov-postgres'
|
||||
RESTORE = 'mtusi-lab2-melnikov-pgrestore'
|
||||
RESTORE_VOLUME = 'mtusi-lab2-melnikov-restoredata'
|
||||
NETWORK = 'mtusi-lab2-melnikov-net'
|
||||
POSTGRES_IMAGE = 'postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c'
|
||||
RESEARCH_PASSWORD = 'Track5-research-password-123'
|
||||
SIZES = [
|
||||
('track5 uneven 60000', 60000),
|
||||
('track5 uneven 25000', 25000),
|
||||
('track5 uneven 10000', 10000),
|
||||
('track5 uneven 4000', 4000),
|
||||
('track5 uneven 900', 900),
|
||||
('track5 uneven 100', 100),
|
||||
]
|
||||
|
||||
|
||||
def read_env():
|
||||
values = {}
|
||||
for line in (ROOT / '.env').read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
key, value = line.split('=', 1)
|
||||
values[key.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
ENV = read_env()
|
||||
|
||||
|
||||
def docker(*args, check_result=True):
|
||||
result = subprocess.run(['docker'] + list(args), capture_output=True, text=True)
|
||||
if check_result and result.returncode != 0:
|
||||
raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:400])
|
||||
return result
|
||||
|
||||
|
||||
def psql(sql, container=POSTGRES, allow_failure=False):
|
||||
result = subprocess.run(
|
||||
['docker', 'exec', '-i', container, 'psql', '-X', '-A', '-t', '-F', '|',
|
||||
'-v', 'ON_ERROR_STOP=1', '-U', ENV['POSTGRES_USER'], '-d', ENV['POSTGRES_DB']],
|
||||
input=sql, capture_output=True, text=True)
|
||||
if result.returncode != 0 and not allow_failure:
|
||||
raise Failure('psql failed: ' + result.stderr.strip()[:500])
|
||||
return result
|
||||
|
||||
|
||||
def query(sql, container=POSTGRES):
|
||||
return psql(sql, container).stdout.strip()
|
||||
|
||||
|
||||
def now_iso():
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def basic_header(username, password):
|
||||
import base64
|
||||
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def research_actor(client):
|
||||
"""Reuse the fixed research account, falling back to a random one if a
|
||||
previous run used a different password for the same username."""
|
||||
username = 'track5_owner'
|
||||
body = {'username': username, 'display_name': 'Track 5 research',
|
||||
'password': RESEARCH_PASSWORD}
|
||||
response = client.call('POST', '/api/v1/users', (201, 409), body=body)
|
||||
if response['status'] == 201:
|
||||
user = json.loads(response['bytes'])
|
||||
else:
|
||||
try:
|
||||
session = client.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': basic_header(username, RESEARCH_PASSWORD)},
|
||||
schema='Session')['json']
|
||||
return {'id': session['user']['id'], 'token': session['token'],
|
||||
'registration': body, 'user': session['user']}
|
||||
except Failure:
|
||||
username = 'track5_owner_' + os.urandom(5).hex()
|
||||
body = {'username': username, 'display_name': 'Track 5 research',
|
||||
'password': RESEARCH_PASSWORD}
|
||||
user = client.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
|
||||
session = client.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': basic_header(username, RESEARCH_PASSWORD)},
|
||||
schema='Session')['json']
|
||||
check(session['user']['id'] == user['id'], 'research login resolved to another user')
|
||||
return {'id': user['id'], 'token': session['token'], 'registration': body, 'user': user}
|
||||
|
||||
|
||||
def ensure_datasets(client):
|
||||
actor = research_actor(client)
|
||||
datasets = []
|
||||
for title, target in SIZES:
|
||||
existing = query("""
|
||||
SELECT c.id::text FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = '%s'::uuid
|
||||
WHERE c.title = '%s'
|
||||
ORDER BY c.created_at LIMIT 1;
|
||||
""" % (actor['id'], title))
|
||||
if existing:
|
||||
chat = {'id': existing, 'title': title}
|
||||
else:
|
||||
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': title, 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
count = int(query("SELECT count(*) FROM messages WHERE chat_id='%s';" % chat['id']))
|
||||
if count < target:
|
||||
psql("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), '%s'::uuid, '%s'::uuid,
|
||||
'track5 %s row ' || g,
|
||||
timestamptz '2026-01-01 00:00:00+00' + (g || ' milliseconds')::interval
|
||||
FROM generate_series(%d, %d) AS g;
|
||||
""" % (chat['id'], actor['id'], target, count + 1, target))
|
||||
count = int(query("SELECT count(*) FROM messages WHERE chat_id='%s';" % chat['id']))
|
||||
check(count == target, '%s has %d messages, want %d' % (title, count, target))
|
||||
datasets.append({'title': title, 'chat_id': chat['id'], 'messages': count})
|
||||
psql('ANALYZE messages; ANALYZE chats; ANALYZE users; ANALYZE chat_members;')
|
||||
return actor, datasets
|
||||
|
||||
|
||||
def explain(sql):
|
||||
return query('EXPLAIN (ANALYZE, BUFFERS) ' + sql + ';')
|
||||
|
||||
|
||||
def index_scan_rows(plan, index_name):
|
||||
match = re.search(
|
||||
r'Index Scan using ' + re.escape(index_name) +
|
||||
r'.*?actual time=[\d.]+\.\.[\d.]+ rows=(\d+)', plan, re.S)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def execution_time(plan):
|
||||
match = re.search(r'Execution Time: ([\d.]+) ms', plan)
|
||||
return float(match.group(1)) if match else None
|
||||
|
||||
|
||||
def keyset_sql(chat_id, cursor_time, cursor_id, limit=50):
|
||||
return ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id='%s'::uuid AND (created_at, messages.id) > ('%s'::timestamptz, '%s'::uuid)
|
||||
ORDER BY created_at, messages.id LIMIT %d
|
||||
""" % (chat_id, cursor_time, cursor_id, limit))
|
||||
|
||||
|
||||
def measure_indexes(largest_chat, output_dir):
|
||||
count = largest_chat['messages']
|
||||
deep_offset = max(1000, count // 2)
|
||||
row = query("""
|
||||
SELECT created_at::text || '|' || id::text FROM messages
|
||||
WHERE chat_id='%s' ORDER BY created_at, messages.id OFFSET %d LIMIT 1;
|
||||
""" % (largest_chat['chat_id'], deep_offset)).split('|')
|
||||
cursor_time, cursor_id = row
|
||||
first_sql = ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE chat_id='%s'::uuid ORDER BY created_at, messages.id LIMIT 50
|
||||
""" % largest_chat['chat_id'])
|
||||
deep_sql = keyset_sql(largest_chat['chat_id'], cursor_time, cursor_id)
|
||||
offset_sql = ("""
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE chat_id='%s'::uuid
|
||||
ORDER BY created_at, messages.id OFFSET %d LIMIT 50
|
||||
""" % (largest_chat['chat_id'], deep_offset))
|
||||
|
||||
started = time.monotonic()
|
||||
first_a = explain(first_sql)
|
||||
deep_a = explain(deep_sql)
|
||||
offset_a = explain(offset_sql)
|
||||
index_a_seconds = time.monotonic() - started
|
||||
check('Index Scan using messages_chat_created_id_idx' in first_a,
|
||||
'first page does not use the composite index:\n' + first_a)
|
||||
check('Index Scan using messages_chat_created_id_idx' in deep_a,
|
||||
'deep keyset page does not use the composite index:\n' + deep_a)
|
||||
a_rows = index_scan_rows(deep_a, 'messages_chat_created_id_idx')
|
||||
offset_rows = index_scan_rows(offset_a, 'messages_chat_created_id_idx')
|
||||
check(a_rows == 50, 'composite index deep page read %r rows, want 50' % (a_rows,))
|
||||
check(offset_rows is not None and offset_rows > deep_offset,
|
||||
'OFFSET plan did not scan a large prefix (%r)' % (offset_rows,))
|
||||
(output_dir / 'explain-composite-index.txt').write_text(
|
||||
'COMPOSITE INDEX (chat_id, created_at, id)\n\n'
|
||||
'=== first page ===\n%s\n\n=== deep keyset page, offset %d ===\n%s\n\n'
|
||||
'=== naive OFFSET %d ===\n%s\n' % (first_a, deep_offset, deep_a, deep_offset, offset_a))
|
||||
|
||||
# Swap indexes and repeat the same deep keyset query.
|
||||
psql("""
|
||||
DROP INDEX messages_chat_created_id_idx;
|
||||
CREATE INDEX messages_chat_only_idx ON messages (chat_id);
|
||||
ANALYZE messages;
|
||||
""")
|
||||
try:
|
||||
started = time.monotonic()
|
||||
deep_b = explain(deep_sql)
|
||||
index_b_seconds = time.monotonic() - started
|
||||
check('messages_chat_created_id_idx' not in deep_b, 'composite index still used after it was dropped')
|
||||
check(('messages_chat_only_idx' in deep_b) or ('Seq Scan on messages' in deep_b),
|
||||
'naive index comparison plan is unexpected:\n' + deep_b)
|
||||
finally:
|
||||
psql("""
|
||||
DROP INDEX IF EXISTS messages_chat_only_idx;
|
||||
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
ANALYZE messages;
|
||||
""")
|
||||
restored = explain(deep_sql)
|
||||
check('Index Scan using messages_chat_created_id_idx' in restored,
|
||||
'composite index was not restored:\n' + restored)
|
||||
(output_dir / 'explain-chat-only-index.txt').write_text(
|
||||
'NAIVE INDEX (chat_id) ONLY\n\n=== deep keyset page, offset %d ===\n%s\n' % (deep_offset, deep_b))
|
||||
|
||||
return {
|
||||
'largest_chat_id': largest_chat['chat_id'],
|
||||
'largest_chat_messages': count,
|
||||
'deep_offset': deep_offset,
|
||||
'cursor': {'created_at': cursor_time, 'id': cursor_id},
|
||||
'composite_index': {
|
||||
'deep_page_rows_read': a_rows,
|
||||
'offset_page_rows_read': offset_rows,
|
||||
'first_page_execution_ms': execution_time(first_a),
|
||||
'deep_page_execution_ms': execution_time(deep_a),
|
||||
'offset_page_execution_ms': execution_time(offset_a),
|
||||
'planning_and_execution_seconds_for_three_queries': round(index_a_seconds, 3),
|
||||
},
|
||||
'chat_only_index': {
|
||||
'deep_page_execution_ms': execution_time(deep_b),
|
||||
'plan_uses_chat_only_index': 'messages_chat_only_idx' in deep_b,
|
||||
'plan_uses_seq_scan': 'Seq Scan on messages' in deep_b,
|
||||
'plan_wall_seconds': round(index_b_seconds, 3),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_cost(output_dir):
|
||||
psql("""
|
||||
DROP TABLE IF EXISTS track5_write_composite;
|
||||
DROP TABLE IF EXISTS track5_write_chat_only;
|
||||
CREATE TABLE track5_write_composite (
|
||||
id uuid NOT NULL, chat_id uuid NOT NULL, created_at timestamptz NOT NULL, payload text NOT NULL);
|
||||
CREATE TABLE track5_write_chat_only (
|
||||
id uuid NOT NULL, chat_id uuid NOT NULL, created_at timestamptz NOT NULL, payload text NOT NULL);
|
||||
CREATE INDEX track5_write_composite_idx ON track5_write_composite (chat_id, created_at, id);
|
||||
CREATE INDEX track5_write_chat_only_idx ON track5_write_chat_only (chat_id);
|
||||
""")
|
||||
insert = """
|
||||
INSERT INTO %s (id, chat_id, created_at, payload)
|
||||
SELECT gen_random_uuid(), gen_random_uuid(),
|
||||
timestamptz '2026-03-01 00:00:00+00' + (g || ' milliseconds')::interval,
|
||||
'write cost row ' || g
|
||||
FROM generate_series(1, 20000) AS g
|
||||
"""
|
||||
measurements = {'rows_per_run': 20000, 'runs': 3, 'metric': 'PostgreSQL EXPLAIN ANALYZE Execution Time, ms'}
|
||||
try:
|
||||
for label, table in (('composite', 'track5_write_composite'), ('chat_only', 'track5_write_chat_only')):
|
||||
times = []
|
||||
for _ in range(3):
|
||||
psql('TRUNCATE %s;' % table)
|
||||
plan = query('EXPLAIN (ANALYZE, TIMING OFF, SUMMARY ON) ' + (insert % table) + ';')
|
||||
value = execution_time(plan)
|
||||
check(value is not None, 'no Execution Time in write-cost plan')
|
||||
times.append(value)
|
||||
measurements[label] = {'runs_ms': times, 'median_ms': round(sorted(times)[1], 3)}
|
||||
finally:
|
||||
psql('DROP TABLE IF EXISTS track5_write_composite; DROP TABLE IF EXISTS track5_write_chat_only;')
|
||||
(output_dir / 'write-cost.json').write_text(json.dumps(measurements, indent=2) + '\n')
|
||||
return measurements
|
||||
|
||||
|
||||
def wait_pg(container, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = docker('exec', container, 'pg_isready', '-U', ENV['POSTGRES_USER'],
|
||||
'-d', ENV['POSTGRES_DB'], check_result=False)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise Failure(container + ' did not become ready')
|
||||
|
||||
|
||||
def backup_and_restore(largest_chat, output_dir, artifacts_dir):
|
||||
"""pg_dump -> new container+volume -> pg_restore -> reconcile."""
|
||||
dump_in_container = '/tmp/lab2-track5.dump'
|
||||
dump_path = artifacts_dir / 'lab2-track5.dump'
|
||||
source_counts = query("""
|
||||
SELECT (SELECT count(*) FROM users) || '|' || (SELECT count(*) FROM chats) || '|' ||
|
||||
(SELECT count(*) FROM chat_members) || '|' || (SELECT count(*) FROM messages) || '|' ||
|
||||
(SELECT count(*) FROM schema_migrations);
|
||||
""")
|
||||
per_chat_before = query("""
|
||||
SELECT chat_id::text || '|' || count(*) FROM messages GROUP BY chat_id ORDER BY chat_id;
|
||||
""")
|
||||
checksum_sql = """
|
||||
SELECT md5(coalesce(string_agg(id::text || ':' || text || ':' || created_at::text,
|
||||
',' ORDER BY created_at, id), ''))
|
||||
FROM messages WHERE chat_id='%s';
|
||||
""" % largest_chat['chat_id']
|
||||
checksum_before = query(checksum_sql)
|
||||
selected = query("""
|
||||
SELECT id::text || '|' || chat_id::text || '|' || sender_id::text || '|' || text || '|' || created_at::text
|
||||
FROM messages WHERE chat_id='%s' ORDER BY created_at, messages.id OFFSET 30000 LIMIT 1;
|
||||
""" % largest_chat['chat_id']).split('|')
|
||||
check(len(selected) == 5, 'selected message query returned unexpected data')
|
||||
selected_id = selected[0]
|
||||
|
||||
started = time.monotonic()
|
||||
dump = docker('exec', POSTGRES, 'pg_dump', '-U', ENV['POSTGRES_USER'],
|
||||
'-d', ENV['POSTGRES_DB'], '-Fc', '-f', dump_in_container)
|
||||
dump_seconds = time.monotonic() - started
|
||||
copy = docker('cp', POSTGRES + ':' + dump_in_container, str(dump_path))
|
||||
dump_bytes = dump_path.stat().st_size
|
||||
dump_sha = hashlib.sha256(dump_path.read_bytes()).hexdigest()
|
||||
|
||||
# Any leftovers from an interrupted run are temporary restore resources;
|
||||
# the main lab volumes are never named here.
|
||||
docker('rm', '-f', RESTORE, check_result=False)
|
||||
docker('volume', 'rm', '-f', RESTORE_VOLUME, check_result=False)
|
||||
recovery_started = time.monotonic()
|
||||
docker('run', '-d', '--name', RESTORE, '--network', NETWORK,
|
||||
'-e', 'POSTGRES_USER=' + ENV['POSTGRES_USER'],
|
||||
'-e', 'POSTGRES_PASSWORD=' + ENV['POSTGRES_PASSWORD'],
|
||||
'-e', 'POSTGRES_DB=' + ENV['POSTGRES_DB'],
|
||||
'-v', RESTORE_VOLUME + ':/var/lib/postgresql/data',
|
||||
POSTGRES_IMAGE)
|
||||
try:
|
||||
wait_pg(RESTORE, timeout=90)
|
||||
docker('cp', str(dump_path), RESTORE + ':' + dump_in_container)
|
||||
restore_started = time.monotonic()
|
||||
restore = docker('exec', RESTORE, 'pg_restore', '-U', ENV['POSTGRES_USER'],
|
||||
'-d', ENV['POSTGRES_DB'], '--no-owner', '--no-privileges',
|
||||
'--clean', '--if-exists', dump_in_container)
|
||||
restore_seconds = time.monotonic() - restore_started
|
||||
total_recovery_seconds = time.monotonic() - recovery_started
|
||||
|
||||
restored_counts = query("""
|
||||
SELECT (SELECT count(*) FROM users) || '|' || (SELECT count(*) FROM chats) || '|' ||
|
||||
(SELECT count(*) FROM chat_members) || '|' || (SELECT count(*) FROM messages) || '|' ||
|
||||
(SELECT count(*) FROM schema_migrations);
|
||||
""", container=RESTORE)
|
||||
per_chat_after = query("""
|
||||
SELECT chat_id::text || '|' || count(*) FROM messages GROUP BY chat_id ORDER BY chat_id;
|
||||
""", container=RESTORE)
|
||||
checksum_after = query(checksum_sql, container=RESTORE)
|
||||
selected_after = query("""
|
||||
SELECT id::text || '|' || chat_id::text || '|' || sender_id::text || '|' || text || '|' || created_at::text
|
||||
FROM messages WHERE id='%s'::uuid;
|
||||
""" % selected_id, container=RESTORE).split('|')
|
||||
check(restored_counts == source_counts,
|
||||
'restored row counts differ: %r != %r' % (restored_counts, source_counts))
|
||||
check(per_chat_after == per_chat_before, 'restored per-chat counts differ')
|
||||
check(checksum_after == checksum_before, 'restored history checksum differs')
|
||||
check(selected_after == selected, 'selected message differs after restore')
|
||||
finally:
|
||||
docker('rm', '-f', RESTORE, check_result=False)
|
||||
docker('volume', 'rm', '-f', RESTORE_VOLUME, check_result=False)
|
||||
docker('exec', POSTGRES, 'rm', '-f', dump_in_container, check_result=False)
|
||||
dump_path.unlink(missing_ok=True)
|
||||
|
||||
result = {
|
||||
'source_counts_users_chats_members_messages_migrations': source_counts,
|
||||
'restored_counts': restored_counts,
|
||||
'counts_equal': source_counts == restored_counts,
|
||||
'per_chat_counts_equal': per_chat_after == per_chat_before,
|
||||
'history_checksum_md5': checksum_before,
|
||||
'checksum_equal': checksum_after == checksum_before,
|
||||
'selected_message_id': selected_id,
|
||||
'selected_message_equal': selected_after == selected,
|
||||
'dump_seconds': round(dump_seconds, 3),
|
||||
'dump_bytes': dump_bytes,
|
||||
'dump_sha256': dump_sha,
|
||||
'restore_seconds': round(restore_seconds, 3),
|
||||
'total_recovery_seconds_including_container_start': round(total_recovery_seconds, 3),
|
||||
'restore_target': {'container': RESTORE, 'volume': RESTORE_VOLUME, 'image': POSTGRES_IMAGE},
|
||||
'cleanup': 'restore container and volume removed in finally; dump file deleted',
|
||||
}
|
||||
(output_dir / 'backup-restore.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--output-dir', default='evidence/track5')
|
||||
parser.add_argument('--artifacts', default=None,
|
||||
help='directory for the raw dump; a temporary directory is used by default')
|
||||
|
||||
args = arguments('Level-5 track 2: indexes, write cost, backup/restore', configure)
|
||||
output_dir = ROOT / args.output_dir
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
artifacts = Path(args.artifacts) if args.artifacts else Path(tempfile.mkdtemp(prefix='mtusi-lab2-track5-'))
|
||||
artifacts.mkdir(parents=True, exist_ok=True)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
started_at = now_iso()
|
||||
started = time.monotonic()
|
||||
seed_started_at = now_iso()
|
||||
actor, datasets = ensure_datasets(c)
|
||||
seed_seconds = time.monotonic() - started
|
||||
seed_finished_at = now_iso()
|
||||
total_messages = int(query('SELECT count(*) FROM messages;'))
|
||||
check(total_messages >= 100000, 'research dataset has only %d messages' % total_messages)
|
||||
|
||||
largest = max(datasets, key=lambda item: item['messages'])
|
||||
phase_started = time.monotonic()
|
||||
index_started_at = now_iso()
|
||||
indexes = measure_indexes(largest, output_dir)
|
||||
indexes['interval'] = {'started_at': index_started_at, 'finished_at': now_iso(),
|
||||
'seconds': round(time.monotonic() - phase_started, 3)}
|
||||
|
||||
phase_started = time.monotonic()
|
||||
write_started_at = now_iso()
|
||||
writes = write_cost(output_dir)
|
||||
writes['interval'] = {'started_at': write_started_at, 'finished_at': now_iso(),
|
||||
'seconds': round(time.monotonic() - phase_started, 3)}
|
||||
|
||||
phase_started = time.monotonic()
|
||||
backup_started_at = now_iso()
|
||||
backup = backup_and_restore(largest, output_dir, artifacts)
|
||||
backup['interval'] = {'started_at': backup_started_at, 'finished_at': now_iso(),
|
||||
'seconds': round(time.monotonic() - phase_started, 3)}
|
||||
|
||||
info = json.loads(subprocess.run(['docker', 'info', '--format', '{{json .}}'],
|
||||
capture_output=True, text=True, check=True).stdout)
|
||||
image = json.loads(subprocess.run(['docker', 'inspect', 'mtusi-messenger-lab2-melnikov:1.0.0'],
|
||||
capture_output=True, text=True, check=True).stdout)[0]
|
||||
revision = subprocess.run(['git', '-C', str(ROOT), 'rev-parse', 'HEAD'],
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
status = subprocess.run(['git', '-C', str(ROOT), 'status', '--porcelain'],
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
|
||||
summary = {
|
||||
'track': 'track 2: query plan and recovery',
|
||||
'started_at': started_at,
|
||||
'finished_at': now_iso(),
|
||||
'duration_seconds': round(time.monotonic() - started, 3),
|
||||
'code_revision': revision,
|
||||
'git_status': status,
|
||||
'image': {'reference': 'mtusi-messenger-lab2-melnikov:1.0.0', 'id': image['Id'],
|
||||
'created': image['Created']},
|
||||
'postgres_image': POSTGRES_IMAGE,
|
||||
'host': {'docker_server_version': info.get('ServerVersion'),
|
||||
'cpus': info.get('NCPU'), 'memory_bytes': info.get('MemTotal'),
|
||||
'architecture': info.get('Architecture')},
|
||||
'declared_limits': {'api': '1 CPU / 256 MiB', 'postgres': '1 CPU / 512 MiB',
|
||||
'valkey': '1 CPU / 256 MiB'},
|
||||
'dataset': {'chat_sizes': SIZES, 'per_chat': datasets, 'total_messages': total_messages,
|
||||
'seed_and_verify_seconds': round(seed_seconds, 3),
|
||||
'seed_interval': {'started_at': seed_started_at, 'finished_at': seed_finished_at},
|
||||
'sample_timestamps': 'research chats sorted by (created_at,id), one-millisecond steps '
|
||||
'from 2026-01-01T00:00:00Z per chat'},
|
||||
'indexes': indexes,
|
||||
'write_cost': writes,
|
||||
'backup_restore': backup,
|
||||
'artifacts_dir_removed_after_run': str(artifacts) if args.artifacts else 'temporary directory',
|
||||
'measurement_notes': [
|
||||
'EXPLAIN elapsed values are PostgreSQL Execution Time on the local container; wall times include psql/docker exec overhead.',
|
||||
'deep page cursor is a real (created_at, id) row at the recorded OFFSET; the OFFSET comparison scans the same prefix.',
|
||||
'write cost measures INSERT plus index maintenance for 20 000 synthetic rows, 3 runs per index, median reported.',
|
||||
'backup is a single pg_dump custom-format snapshot; no WAL archiving, so RPO is the age of the last dump.',
|
||||
'restore target is a new PostgreSQL container with a new named volume, removed after reconciliation.',
|
||||
],
|
||||
}
|
||||
(output_dir / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n')
|
||||
|
||||
if not args.artifacts:
|
||||
shutil.rmtree(artifacts, ignore_errors=True)
|
||||
print(json.dumps({
|
||||
'total_messages': total_messages,
|
||||
'largest_chat_messages': largest['messages'],
|
||||
'composite_deep_rows': indexes['composite_index']['deep_page_rows_read'],
|
||||
'offset_rows': indexes['composite_index']['offset_page_rows_read'],
|
||||
'write_median_ms': {'composite': writes['composite']['median_ms'],
|
||||
'chat_only': writes['chat_only']['median_ms']},
|
||||
'dump_seconds': backup['dump_seconds'],
|
||||
'dump_bytes': backup['dump_bytes'],
|
||||
'restore_seconds': backup['restore_seconds'],
|
||||
'total_recovery_seconds': backup['total_recovery_seconds_including_container_start'],
|
||||
'counts_equal': backup['source_counts_users_chats_members_messages_migrations'] == backup['restored_counts'],
|
||||
'checksum_equal': backup['checksum_equal'],
|
||||
}, ensure_ascii=False, sort_keys=True))
|
||||
print('PASS: track 2 completed; summary in evidence/track5/summary.json')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user