Реализовать лабораторную 2: PostgreSQL, Bearer-сессии и Valkey

Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход,
opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON,
keyset-пагинацию по индексу, миграции, compose-стенд и собственные
проверки уровня 3/4. Трек 5 — план запроса и восстановление.
This commit is contained in:
IvanMeln1k
2026-11-30 23:51:33 +03:00
parent 65003b6119
commit 6ea767732e
469 changed files with 204712 additions and 10 deletions
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Accept both the Compose v2 plugin ("docker compose") and the standalone
# binary ("docker-compose"), so the same Makefile works on machines where only
# one of them is installed. This wrapper does not change any global setting.
set -eu
if docker compose version >/dev/null 2>&1; then
exec docker compose "$@"
fi
if command -v docker-compose >/dev/null 2>&1; then
exec docker-compose "$@"
fi
echo "Docker Compose is required (docker compose or docker-compose)" >&2
exit 2
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env python3
"""Infrastructure checks for lab2: real containers, pinned images, named
volumes, network isolation, non-root read-only API, health, graceful shutdown
and absence of secrets/tokens in logs and Git.
This script never stops the main stack; the graceful-shutdown proof uses a
separate short-lived container with a unique `mtusi-lab2-melnikov-` prefix.
"""
import json
import subprocess
import sys
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
API = 'mtusi-lab2-melnikov-api'
POSTGRES = 'mtusi-lab2-melnikov-postgres'
VALKEY = 'mtusi-lab2-melnikov-valkey'
GRACEFUL = 'mtusi-lab2-melnikov-graceful-check'
NETWORK = 'mtusi-lab2-melnikov-net'
VOLUMES = ['mtusi-lab2-melnikov-pgdata', 'mtusi-lab2-melnikov-valkeydata']
def docker(*args):
result = subprocess.run(['docker'] + list(args), capture_output=True, text=True)
if result.returncode != 0:
raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:300])
return result.stdout.strip()
def inspect(name):
return json.loads(docker('inspect', name))[0]
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
def api_headers(base):
import urllib.request
request = urllib.request.Request(base + '/health/live', headers={'Accept': 'application/json'})
with urllib.request.urlopen(request, timeout=10) as response:
return {'instance': response.headers.get('X-Instance-Id'),
'request': response.headers.get('X-Request-Id'),
'status': response.status}
def wait_healthy(name, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
state = inspect(name)['State']
if state.get('Health', {}).get('Status') == 'healthy':
return
time.sleep(0.5)
raise Failure(name + ' did not become healthy')
def main():
def configure(parser):
parser.add_argument('--image', default='mtusi-messenger-lab2-melnikov:1.0.0')
parser.add_argument('--output', default=None)
args = arguments('Container, volume, network and log checks', configure)
env = read_env()
observations = {}
# --- containers, images, volumes, network ------------------------------
for name in (API, POSTGRES, VALKEY):
wait_healthy(name)
containers = {}
for name in (API, POSTGRES, VALKEY):
data = inspect(name)
check(data['Name'] == '/' + name, 'unexpected container name ' + data['Name'])
check(data['State']['Running'], name + ' is not running')
check(data['State']['Health']['Status'] == 'healthy', name + ' is not healthy')
containers[name] = {
'image': data['Config']['Image'],
'image_id': data['Image'],
'started_at': data['State']['StartedAt'],
'restart_policy': data['HostConfig']['RestartPolicy']['Name'],
}
check(containers[POSTGRES]['image'].startswith('postgres:16.4-alpine3.20@sha256:'),
'PostgreSQL image is not pinned by digest')
check(containers[VALKEY]['image'].startswith('valkey/valkey:8.0.2-alpine@sha256:'),
'Valkey image is not pinned by digest')
api = inspect(API)
check(api['Config']['User'] == '10001:10001', 'API image user is not 10001:10001')
check(api['HostConfig']['ReadonlyRootfs'] is True, 'API root filesystem is writable')
check('ALL' in (api['HostConfig']['CapDrop'] or []), 'API does not drop all capabilities')
check(any('no-new-privileges' in item for item in (api['HostConfig']['SecurityOpt'] or [])),
'API lacks no-new-privileges')
check(docker('exec', API, 'id', '-u') == '10001', 'API process uid is not 10001')
ui = api['HostConfig']['PortBindings'].get('8080/tcp') or []
check(len(ui) == 1 and ui[0].get('HostIp') == '127.0.0.1', 'API port is not bound to loopback only')
for name in (POSTGRES, VALKEY):
data = inspect(name)
check(not data['HostConfig']['PortBindings'], name + ' publishes an internal port')
check(inspect(NETWORK)['Name'] == NETWORK, 'lab2 network missing')
volumes = {}
for name in VOLUMES:
data = inspect(name)
volumes[name] = data['Mountpoint']
check(data['Labels'].get('com.docker.compose.project') == 'mtusi-lab2-melnikov',
name + ' is not owned by the lab2 compose project')
observations['containers'] = containers
observations['volumes'] = volumes
observations['api_user'] = api['Config']['User']
observations['api_read_only'] = api['HostConfig']['ReadonlyRootfs']
observations['api_ports'] = ui
image = inspect(args.image)
check(image['Id'] == containers[API]['image_id'], 'running API image differs from inspected image')
labels = image['Config'].get('Labels') or {}
check(labels.get('org.opencontainers.image.title') == 'mtusi-messenger-lab2',
'API image label is missing')
observations['image'] = {
'reference': args.image,
'id': image['Id'],
'size_bytes': image['Size'],
'user': image['Config']['User'],
'healthcheck': image['Config'].get('Healthcheck', {}).get('Test'),
'created': image['Created'],
}
# --- Valkey is a real, persistent session store ------------------------
def valkey_cli(arguments):
return docker('exec', VALKEY, 'sh', '-c',
'valkey-cli --no-auth-warning -a "$VALKEY_PASSWORD" ' + arguments)
appendonly = valkey_cli('CONFIG GET appendonly')
appendfsync = valkey_cli('CONFIG GET appendfsync')
datadir = valkey_cli('CONFIG GET dir')
persistence = valkey_cli('INFO persistence')
dbsize = int(valkey_cli('DBSIZE'))
check('appendonly' in appendonly and 'yes' in appendonly, 'Valkey AOF is disabled')
check('appendfsync' in appendfsync and 'everysec' in appendfsync, 'Valkey appendfsync is not everysec')
check('/data' in datadir, 'Valkey data directory is not the named volume')
check('aof_enabled:1' in persistence, 'Valkey INFO does not report AOF enabled')
check('aof_last_write_status:ok' in persistence, 'Valkey AOF last write is not ok')
check(dbsize > 0, 'Valkey has no live sessions to persist')
observations['valkey'] = {
'appendonly': 'yes',
'appendfsync': 'everysec',
'dir': '/data',
'aof_enabled': True,
'aof_last_write_status': 'ok',
'session_keys': dbsize,
}
# --- health headers and instance stability -----------------------------
first = api_headers(args.base_url)
second = api_headers(args.base_url)
check(first['status'] == 200 and second['status'] == 200, 'liveness is not 200')
check(first['instance'] and first['instance'] == second['instance'], 'X-Instance-Id is not stable')
check(first['request'] and first['request'] != second['request'], 'X-Request-Id is not per-request')
observations['instance_id'] = first['instance']
# --- logs must not contain credentials or message bodies ---------------
client = Client(args.base_url, args.ca_file)
user = client.user('logs')
registration = user['registration']
chat = client.call('POST', '/api/v1/chats', 201, actor=user,
body={'title': 'Проверка логов', 'member_ids': [user['id']]}, schema='Chat')['json']
marker = 'log-secret-marker-' + registration['username']
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=user,
body={'text': marker}, schema='Message')
logs = docker('logs', '--tail', '400', API)
checks = {
'token_absent': user['token'] not in logs,
'password_absent': registration['password'] not in logs,
'message_body_absent': marker not in logs,
'authorization_header_absent': 'Authorization: Bearer' not in logs,
}
check(all(checks.values()), 'API logs leak a token, password or message body: ' + repr(checks))
observations['log_checks'] = checks
# --- graceful shutdown of a separate identical container ---------------
database_url = ('postgres://%s:%s@postgres:5432/%s?sslmode=disable'
% (env['POSTGRES_USER'], env['POSTGRES_PASSWORD'], env['POSTGRES_DB']))
cache_url = 'redis://:%s@valkey:6379/0' % env['VALKEY_PASSWORD']
started = time.monotonic()
try:
docker('run', '-d', '--name', GRACEFUL, '--network', NETWORK,
'--read-only', '--tmpfs', '/tmp', '--cap-drop', 'ALL',
'--security-opt', 'no-new-privileges:true', '--user', '10001:10001',
'-e', 'APP_HOST=0.0.0.0', '-e', 'APP_PORT=8080', '-e', 'APP_ENV=lab',
'-e', 'LOG_LEVEL=info', '-e', 'SESSION_TTL_SECONDS=3600',
'-e', 'DATABASE_URL=' + database_url, '-e', 'CACHE_URL=' + cache_url,
containers[API]['image_id'])
wait_healthy(GRACEFUL, timeout=45)
boot_seconds = time.monotonic() - started
shutdown_started = time.monotonic()
docker('stop', '--time', '15', GRACEFUL)
shutdown_seconds = time.monotonic() - shutdown_started
state = inspect(GRACEFUL)['State']
graceful_logs = docker('logs', GRACEFUL)
check(state['ExitCode'] == 0, 'graceful container exited with %r' % (state['ExitCode'],))
check('shutdown complete' in graceful_logs, 'graceful shutdown log line is missing')
check(shutdown_seconds <= 10, 'graceful shutdown took %.2fs (promised <=10s)' % shutdown_seconds)
observations['graceful_shutdown'] = {
'boot_seconds': round(boot_seconds, 3),
'shutdown_seconds': round(shutdown_seconds, 3),
'exit_code': state['ExitCode'],
}
finally:
try:
docker('rm', '-f', GRACEFUL)
except Failure:
pass
# --- secrets must not be tracked by Git --------------------------------
tracked = subprocess.run(['git', '-C', str(ROOT), 'ls-files'],
capture_output=True, text=True, check=True).stdout
tracked_files = [line for line in tracked.splitlines() if line]
forbidden = [name for name in tracked_files
if name == '.env' or name.startswith('secrets/') or name.endswith(('.pem', '.key', '.p12'))]
check(not forbidden, 'tracked secret-like files: ' + repr(forbidden))
check('.env.example' in tracked_files, '.env.example is not tracked')
check(subprocess.run(['git', '-C', str(ROOT), 'check-ignore', '-q', '.env']).returncode == 0,
'.env is not ignored by Git')
password = env['POSTGRES_PASSWORD']
if password:
leaked = subprocess.run(['git', '-C', str(ROOT), 'grep', '-F', '--', password],
capture_output=True, text=True).stdout
check(not leaked, 'a generated local password is present in tracked files')
observations['git'] = {'tracked_files': len(tracked_files), 'env_ignored': True,
'secret_like_tracked': forbidden}
observations['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps(observations, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({
'image_id': observations['image']['id'],
'image_size_bytes': observations['image']['size_bytes'],
'volumes': sorted(observations['volumes']),
'graceful_shutdown_seconds': observations['graceful_shutdown']['shutdown_seconds'],
'logs_clean': True,
'secret_like_tracked_files': forbidden,
}, ensure_ascii=False, sort_keys=True))
print('PASS: real containers, pinned images, named volumes, non-root read-only API, graceful shutdown, clean logs')
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)
+319
View File
@@ -0,0 +1,319 @@
#!/usr/bin/env python3
"""SQL-level checks for lab2: schema constraints, unique username under
concurrency, password hashes, transaction rollback of the composite chat
operation, idempotent migrations and EXPLAIN (ANALYZE, BUFFERS) on a history
of at least 10 000 messages.
All database commands run non-interactively inside the lab2 PostgreSQL
container with ON_ERROR_STOP=1.
"""
import datetime as dt
import json
import subprocess
import sys
import time
import urllib.request
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'
API = 'mtusi-lab2-melnikov-api'
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 psql(sql, allow_failure=False):
result = subprocess.run(
['docker', 'exec', '-i', POSTGRES, '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()[:400])
return result
def query(sql):
return psql(sql).stdout.strip()
def wait_ready(base_url, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(base_url + '/health/ready', timeout=3) as response:
if response.status == 200:
return
except Exception: # noqa: BLE001 - expected while the API restarts
pass
time.sleep(0.5)
raise Failure('API did not become ready after restart')
def ensure_large_history(c, output_dir):
"""Return (chat_id, message_count). Seeds 12 000 rows only when the
database does not already contain a 10 000+ message history."""
total = int(query('SELECT count(*) FROM messages;'))
if total >= 10000:
row = query("""
SELECT chat_id::text || '|' || count(*)
FROM messages GROUP BY chat_id ORDER BY count(*) DESC, min(created_at) LIMIT 1;
""")
chat_id, count = row.split('|')
return chat_id, int(count), total
owner = c.user('explain')
chat = c.call('POST', '/api/v1/chats', 201, actor=owner,
body={'title': 'level4 explain history',
'member_ids': [owner['id']]}, schema='Chat')['json']
target = 12000
psql("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '%s'::uuid, '%s'::uuid, 'level4 row ' || g,
timestamptz '2026-02-01 00:00:00+00' + (g || ' milliseconds')::interval
FROM generate_series(1, %d) AS g;
ANALYZE messages;
""" % (chat['id'], owner['id'], target))
count = int(query("SELECT count(*) FROM messages WHERE chat_id='%s';" % chat['id']))
check(count == target, 'seeded history has %d rows, want %d' % (count, target))
return chat['id'], count, total + target
def explain(sql):
result = psql('EXPLAIN (ANALYZE, BUFFERS) ' + sql + ';\n')
return result.stdout.strip()
def main():
def configure(parser):
parser.add_argument('--output-dir', default='evidence')
args = arguments('SQL constraints, rollback, migrations and EXPLAIN', configure)
c = Client(args.base_url, args.ca_file)
output_dir = ROOT / args.output_dir
output_dir.mkdir(parents=True, exist_ok=True)
setup = c.user('dbcheck')
evidence = {'checked_at': dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')}
# --- schema and constraints -------------------------------------------
versions = query('SELECT string_agg(version::text, \',\' ORDER BY version) FROM schema_migrations;')
check(versions == '1,2', 'schema_migrations versions = %r, want 1,2' % versions)
duplicate_users = int(query("""
SELECT count(*) FROM (SELECT username FROM users GROUP BY username HAVING count(*) > 1) duplicates;
"""))
check(duplicate_users == 0, 'duplicate usernames exist despite the unique index')
required_constraints = {
'users_pkey', 'users_username_format', 'users_display_name_length',
'users_password_hash_present', 'chats_pkey', 'chats_title_length',
'chat_members_pkey', 'chat_members_chat_id_fkey', 'chat_members_user_id_fkey',
'chat_members_position_nonnegative', 'messages_pkey', 'messages_text_length',
'messages_chat_fk', 'messages_sender_membership_fk',
}
present_constraints = set(query("""
SELECT conname FROM pg_constraint
WHERE conrelid IN ('users'::regclass, 'chats'::regclass, 'chat_members'::regclass, 'messages'::regclass);
""").splitlines())
missing = required_constraints - present_constraints
check(not missing, 'missing database constraints: ' + repr(sorted(missing)))
required_indexes = {'users_username_key', 'chat_members_user_chat_idx',
'messages_chat_created_id_idx', 'chats_created_id_idx'}
present_indexes = set(query("SELECT indexname FROM pg_indexes WHERE schemaname='public';").splitlines())
missing_indexes = required_indexes - present_indexes
check(not missing_indexes, 'missing indexes: ' + repr(sorted(missing_indexes)))
check(query("""
SELECT count(*) FROM information_schema.tables
WHERE table_schema='public' AND table_name ILIKE '%session%';
""") == '0', 'sessions must not be stored in PostgreSQL')
users = int(query('SELECT count(*) FROM users;'))
hashed = int(query("SELECT count(*) FROM users WHERE password_hash LIKE '$argon2id$%';"))
check(users >= 1, 'expected at least the setup user, found %d' % users)
check(hashed == users, 'not every stored password is an Argon2id PHC string')
check(query("SELECT count(*) FROM users WHERE password_hash IN ('', 'password');") == '0',
'empty or literal password hash found')
race_duplicates = int(query("""
SELECT count(*) FROM (SELECT username FROM users WHERE username LIKE 'race_%'
GROUP BY username HAVING count(*) > 1) duplicates;
"""))
check(race_duplicates == 0, 'concurrent registration created duplicate usernames')
evidence['schema'] = {
'migration_versions': versions,
'constraints_present': sorted(required_constraints),
'indexes_present': sorted(required_indexes),
'users': users,
'argon2id_hashes': hashed,
'duplicate_usernames': duplicate_users,
'race_duplicates': race_duplicates,
}
# --- database-level sender membership FK ------------------------------
chat_id = query('SELECT id::text FROM chats ORDER BY created_at LIMIT 1;')
outsider = query("""
SELECT id::text FROM users
WHERE id NOT IN (SELECT user_id FROM chat_members WHERE chat_id='%s')
ORDER BY created_at LIMIT 1;
""" % chat_id)
check(bool(outsider), 'could not find a non-member for the FK probe')
before = int(query('SELECT count(*) FROM messages;'))
failed = psql("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (gen_random_uuid(), '%s'::uuid, '%s'::uuid, 'fk probe', now());
""" % (chat_id, outsider), allow_failure=True)
after = int(query('SELECT count(*) FROM messages;'))
check(failed.returncode != 0, 'database accepted a message from a non-member sender')
check(before == after, 'failed FK insert changed the message count')
evidence['sender_membership_fk'] = {'rejected': True, 'messages_before': before, 'messages_after': after}
# --- rollback of the composite chat operation -------------------------
owner = c.user('rollback')
other = c.user('rollback')
psql("""
CREATE OR REPLACE FUNCTION lab2_rollback_probe() RETURNS trigger AS $$
BEGIN
IF EXISTS (SELECT 1 FROM chats WHERE id = NEW.chat_id AND title = 'rollback-probe') THEN
RAISE EXCEPTION 'injected composite failure';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS lab2_rollback_probe ON chat_members;
CREATE TRIGGER lab2_rollback_probe BEFORE INSERT ON chat_members
FOR EACH ROW EXECUTE FUNCTION lab2_rollback_probe();
""")
try:
response = c.call('POST', '/api/v1/chats', 500, actor=owner,
body={'title': 'rollback-probe', 'member_ids': [owner['id'], other['id']]})
check(response['json']['error']['code'] == 'internal_error', 'rollback probe error code')
message = response['json']['error']['message'].lower()
for leaked in ('injected', 'sql', 'lab2_rollback', 'trigger'):
check(leaked not in message, '500 body leaks internal detail %r' % leaked)
finally:
psql("""
DROP TRIGGER IF EXISTS lab2_rollback_probe ON chat_members;
DROP FUNCTION IF EXISTS lab2_rollback_probe();
""")
leftover = query("SELECT count(*) FROM chats WHERE title='rollback-probe';")
check(leftover == '0', 'composite chat operation left a chat without members after rollback')
evidence['composite_rollback'] = {'chats_left': int(leftover), 'api_status': 500}
# --- migrations re-run on API restart without duplicating data --------
counts_sql = ('SELECT (SELECT count(*) FROM users) || \',\' || (SELECT count(*) FROM chats) || \',\' || '
'(SELECT count(*) FROM chat_members) || \',\' || (SELECT count(*) FROM messages);')
before_counts = query(counts_sql)
started_before = json.loads(subprocess.run(
['docker', 'inspect', API], capture_output=True, text=True, check=True).stdout)[0]['State']['StartedAt']
subprocess.run(['docker', 'restart', API], check=True, capture_output=True)
wait_ready(args.base_url)
after_counts = query(counts_sql)
migrations_after = query('SELECT count(*) FROM schema_migrations;')
started_after = json.loads(subprocess.run(
['docker', 'inspect', API], capture_output=True, text=True, check=True).stdout)[0]['State']['StartedAt']
check(before_counts == after_counts, 'API restart duplicated or lost rows: %r -> %r'
% (before_counts, after_counts))
check(migrations_after == '2', 'migrations table changed after restart')
check(started_before != started_after, 'API was not actually restarted')
evidence['migrations_idempotent'] = {
'counts_before': before_counts, 'counts_after': after_counts,
'migrations_after': int(migrations_after), 'api_restarted': True,
}
# --- EXPLAIN on a >=10 000 message history ----------------------------
chat_id, history_count, total = ensure_large_history(c, output_dir)
check(history_count >= 10000, 'EXPLAIN history has only %d messages' % history_count)
deep_offset = max(1000, history_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;
""" % (chat_id, deep_offset)).split('|')
cursor_time, cursor_id = row
keyset_sql = ("""
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 50
""" % (chat_id, cursor_time, cursor_id))
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
""" % chat_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
""" % (chat_id, deep_offset))
first_plan = explain(first_sql)
keyset_plan = explain(keyset_sql)
offset_plan = explain(offset_sql)
for name, plan in (('first page', first_plan), ('deep keyset page', keyset_plan)):
check('Index Scan using messages_chat_created_id_idx' in plan,
name + ' does not use the history index:\n' + plan)
check('Seq Scan on messages' not in plan, name + ' performs a sequential scan')
check('Index Scan using messages_chat_created_id_idx' in offset_plan,
'naive OFFSET plan unexpectedly avoids the index')
import re
def scanned_rows(plan):
match = re.search(
r'Index Scan using messages_chat_created_id_idx.*?actual time=[\d.]+\.[\d.]+ rows=(\d+)',
plan, re.S)
return int(match.group(1)) if match else None
first_rows = scanned_rows(first_plan)
keyset_rows = scanned_rows(keyset_plan)
offset_rows = scanned_rows(offset_plan)
check(first_rows == 50, 'first page scanned %r rows, want 50' % (first_rows,))
check(keyset_rows == 50, 'deep keyset page scanned %r rows, want 50' % (keyset_rows,))
check(offset_rows is not None and offset_rows > deep_offset,
'OFFSET comparison did not demonstrate a large scan (%r rows)' % (offset_rows,))
plan_text = (
'LAB2 LEVEL 4 EXPLAIN EVIDENCE\n'
'messages in history: %d, total messages: %d, deep offset: %d\n\n'
'=== first page ===\n%s\n\n=== keyset page after offset %d ===\n%s\n\n'
'=== naive OFFSET %d ===\n%s\n' % (
history_count, total, deep_offset, first_plan, deep_offset, keyset_plan, deep_offset, offset_plan)
)
(output_dir / 'explain-level4.txt').write_text(plan_text)
evidence['explain'] = {
'chat_id': chat_id, 'history_messages': history_count, 'total_messages': total,
'first_page_index_rows': first_rows, 'keyset_page_index_rows': keyset_rows,
'offset_page_index_rows': offset_rows, 'deep_offset': deep_offset,
'index_used': 'messages_chat_created_id_idx',
}
(output_dir / 'db-checks.json').write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({
'migrations': versions,
'constraints': len(required_constraints),
'indexes': len(required_indexes),
'argon2id_hashes': hashed,
'composite_rollback_left_chats': int(leftover),
'migration_counts_stable': before_counts == after_counts,
'explain_history_messages': history_count,
'keyset_rows_read': keyset_rows,
'offset_rows_read': offset_rows,
}, ensure_ascii=False, sort_keys=True))
print('PASS: SQL constraints, FK, rollback, idempotent migrations and index-backed EXPLAIN')
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Short-TTL session expiry and API-restart test for lab2.
Operator contract: the API must be started with a short SESSION_TTL_SECONDS
(the Makefile target test-expiry recreates only the API with 15 seconds).
The script:
1. registers and logs in a synthetic user;
2. checks that /users/me works with the token;
3. optionally restarts ONLY the API container and checks the same token still
works (sessions live in Valkey, not in API memory) while the process
instance id changes;
4. waits for the original expiry deadline and checks the token now gets 401,
so the TTL was not extended by the restart.
No token is printed or written.
"""
import base64
import datetime as dt
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, timestamp # noqa: E402
def wait_ready(base_url, timeout=90):
import urllib.request
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(base_url + '/health/ready', timeout=3) as response:
if response.status == 200:
return
except Exception as exc: # noqa: BLE001 - readiness polling
last = exc
time.sleep(0.5)
raise Failure('API did not become ready after restart (' + type(last).__name__ + ')') from None
def main():
def configure(parser):
parser.add_argument('--restart-api', action='store_true',
help='restart only the API container through scripts/compose.sh')
parser.add_argument('--expected-ttl', type=int, default=15,
help='SESSION_TTL_SECONDS the API was started with')
args = arguments('Short-TTL session expiry and API restart', configure)
c = Client(args.base_url, args.ca_file)
actor = c.user('expiry')
registration = actor['registration']
credential = base64.b64encode(
(registration['username'] + ':' + registration['password']).encode('utf-8')).decode('ascii')
session = c.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
actor['token'] = session['token']
expires = timestamp(session['expires_at'])
now = dt.datetime.now(dt.timezone.utc)
remaining = (expires - now).total_seconds()
check(remaining > 1, 'session expired before the test started')
check(remaining <= args.expected_ttl + 2,
'session TTL is %.1fs, expected about %ds; start the API with the short TTL'
% (remaining, args.expected_ttl))
me = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json']
check(me['id'] == actor['id'], 'fresh token does not resolve to its user')
instance_before = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['headers']['X-Instance-Id']
check(bool(instance_before), 'missing X-Instance-Id')
if args.restart_api:
started = time.monotonic()
subprocess.run([str(ROOT / 'scripts/compose.sh'), '--env-file', '.env', 'restart', 'api'],
cwd=str(ROOT), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wait_ready(args.base_url)
restart_seconds = time.monotonic() - started
# The same token must still be valid: the session was not stored in the
# API process and was not dropped by recreating it.
same = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
check(same['json']['id'] == actor['id'], 'token was lost when the API restarted')
instance_after = same['headers']['X-Instance-Id']
check(instance_after != instance_before, 'API instance id did not change after restart')
print('PASS: token survived an API-only restart in %.2fs; instance %s -> %s'
% (restart_seconds, instance_before, instance_after))
else:
restart_seconds = None
instance_after = instance_before
# Wait for the absolute deadline that was returned at login. Polling also
# tolerates small clock differences between host and container.
deadline = time.monotonic() + max(0.0, (expires - dt.datetime.now(dt.timezone.utc)).total_seconds()) + 2
status = None
while time.monotonic() < deadline + 10:
response = c.call('GET', '/api/v1/users/me', (200, 401), actor=actor)
status = response['status']
if status == 401:
break
time.sleep(0.5)
check(status == 401, 'expired token still authenticates (status %r)' % (status,))
challenge = c.call('GET', '/api/v1/users/me', 401, actor=actor)['headers'].get('WWW-Authenticate', '')
check(challenge.lower().startswith('bearer'), 'expired token 401 has no Bearer challenge')
# Revoked/expired sessions cannot be logged out a second time.
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor)
summary = {
'checked_at': dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z'),
'configured_ttl_seconds': args.expected_ttl,
'observed_ttl_seconds': round(remaining, 3),
'api_restart': bool(args.restart_api),
'api_restart_seconds': None if restart_seconds is None else round(restart_seconds, 3),
'instance_before': instance_before,
'instance_after': instance_after,
'expired_status': status,
}
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
print('PASS: short-TTL expiry, absolute deadline, and API-restart session survival')
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""Dependency-outage checks for lab2.
Stops and starts the real lab2 containers with `docker stop` / `docker start`.
Volumes are never removed. It verifies the level-4 requirement that loss of
Valkey or PostgreSQL produces a bounded 503 and never turns an anonymous
request into a trusted one, and that recovery keeps the existing session and
confirmed data.
The operator is expected to run this against the local teaching stand only.
"""
import base64
import datetime as dt
import json
import subprocess
import sys
import time
import urllib.error
import urllib.request
import uuid
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'
VALKEY = 'mtusi-lab2-melnikov-valkey'
VOLUMES = ['mtusi-lab2-melnikov-pgdata', 'mtusi-lab2-melnikov-valkeydata']
def docker(*args, quiet=False):
result = subprocess.run(['docker'] + list(args), capture_output=True, text=True)
if result.returncode != 0:
raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:200])
return result.stdout.strip()
def inspect_state(name):
raw = docker('inspect', name)
return json.loads(raw)[0]
def http(base, method, path, token=None, body=None, timeout=10, extra_headers=None):
headers = {'Accept': 'application/json'}
data = None
if token:
headers['Authorization'] = 'Bearer ' + token
if extra_headers:
headers.update(extra_headers)
if body is not None:
data = json.dumps(body).encode('utf-8')
headers['Content-Type'] = 'application/json'
request = urllib.request.Request(base + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
raw = response.read()
return response.status, dict(response.headers), json.loads(raw) if raw else None
except urllib.error.HTTPError as error:
raw = error.read()
return error.code, dict(error.headers), json.loads(raw) if raw else None
except Exception: # noqa: BLE001 - a refused connection is an expected observation
return None, {}, None
def wait_status(base, path, expected, timeout=45):
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
status, _, _ = http(base, 'GET', path)
last = status
if status == expected:
return
time.sleep(0.5)
raise Failure('%s did not reach %s within %ss (last %r)' % (path, expected, timeout, last))
def expect_unavailable(base, path, token=None):
status, headers, payload = http(base, 'GET', path, token=token)
check(status == 503, path + ' expected 503, got %r' % (status,))
check(payload and payload.get('error', {}).get('code') == 'unavailable', path + ' error code')
check(payload['error']['request_id'] == headers.get('X-Request-Id'), path + ' request id mismatch')
return {'path': path, 'status': status, 'code': payload['error']['code']}
def main():
def configure(parser):
parser.add_argument('--output', default=None, help='optional JSON evidence path')
args = arguments('Stop/start Valkey and PostgreSQL; volumes are preserved', configure)
c = Client(args.base_url, args.ca_file)
actor = c.user('failure')
chat = c.call('POST', '/api/v1/chats', 201, actor=actor,
body={'title': 'Отказ зависимости', 'member_ids': [actor['id']]}, schema='Chat')['json']
probe = 'failure-probe-' + uuid.uuid4().hex
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': probe}, schema='Message')['json']
volume_before = {name: inspect_state(name)['Mountpoint'] for name in VOLUMES}
states_before = {name: inspect_state(name)['State']['StartedAt'] for name in (POSTGRES, VALKEY)}
observations = {'probe_message_id': message['id'], 'volumes_before': volume_before,
'containers_started_before': states_before}
try:
# ---- Valkey outage -------------------------------------------------
docker('stop', '--time', '20', VALKEY)
stopped = time.monotonic()
wait_status(args.base_url, '/health/ready', 503)
valkey = {}
status, headers, payload = http(args.base_url, 'GET', '/health/live')
check(status == 200 and payload == {'status': 'ok'}, 'liveness must stay 200 without Valkey')
valkey['liveness'] = {'status': status, 'body': payload}
valkey['readiness'] = {'status': 503}
valkey['authenticated_request'] = expect_unavailable(args.base_url, '/api/v1/users/me', actor['token'])
status, headers, payload = http(args.base_url, 'GET', '/api/v1/users/me')
check(status == 401 and payload['error']['code'] == 'unauthorized',
'anonymous request without Valkey must stay 401')
valkey['anonymous_request'] = {'status': status, 'code': payload['error']['code']}
credential = 'Basic ' + base64.b64encode(
(actor['registration']['username'] + ':' + actor['registration']['password']).encode('utf-8')).decode('ascii')
status, headers, payload = http(args.base_url, 'POST', '/api/v1/auth/sessions',
extra_headers={'Authorization': credential})
check(status == 503 and payload['error']['code'] == 'unavailable',
'login with valid credentials must be a bounded 503 without Valkey')
valkey['login'] = {'status': status, 'code': payload['error']['code']}
# Registration only needs PostgreSQL; it is allowed to work while the
# session store is down, and proves the outage is bounded to sessions.
outage_user = 'outage_' + uuid.uuid4().hex[:10]
status, headers, payload = http(args.base_url, 'POST', '/api/v1/users', body={
'username': outage_user,
'display_name': 'Во время отказа Valkey',
'password': 'Outage-password-123',
})
check(status == 201 and payload['username'] == outage_user,
'registration should be independent of the session store')
valkey['registration_while_down'] = {'status': status}
# ---- Valkey recovery ----------------------------------------------
docker('start', VALKEY)
wait_status(args.base_url, '/health/ready', 200)
valkey['recovery_seconds'] = round(time.monotonic() - stopped, 3)
status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me', token=actor['token'])
check(status == 200 and payload['id'] == actor['id'],
'existing session did not survive the Valkey stop/start')
valkey['session_after_recovery'] = {'status': status}
observations['valkey_outage'] = valkey
# ---- PostgreSQL outage --------------------------------------------
docker('stop', '--time', '20', POSTGRES)
stopped = time.monotonic()
wait_status(args.base_url, '/health/ready', 503)
postgres = {}
status, _, payload = http(args.base_url, 'GET', '/health/live')
check(status == 200 and payload == {'status': 'ok'}, 'liveness must stay 200 without PostgreSQL')
postgres['liveness'] = {'status': status, 'body': payload}
postgres['readiness'] = {'status': http(args.base_url, 'GET', '/health/ready')[0]}
postgres['authenticated_request'] = expect_unavailable(args.base_url, '/api/v1/users/me', actor['token'])
status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me')
check(status == 401, 'anonymous request without PostgreSQL must stay 401')
postgres['anonymous_request'] = {'status': status, 'code': payload['error']['code']}
status, _, payload = http(args.base_url, 'POST', '/api/v1/users', body={
'username': 'unreachable_' + uuid.uuid4().hex[:8],
'display_name': 'Не должно создаться',
'password': 'Outage-password-123',
})
check(status == 503 and payload['error']['code'] == 'unavailable',
'registration must be a bounded 503 without PostgreSQL')
postgres['registration'] = {'status': status, 'code': payload['error']['code']}
# ---- PostgreSQL recovery ------------------------------------------
docker('start', POSTGRES)
wait_status(args.base_url, '/health/ready', 200)
postgres['recovery_seconds'] = round(time.monotonic() - stopped, 3)
status, _, payload = http(args.base_url, 'GET', '/api/v1/users/me', token=actor['token'])
check(status == 200 and payload['id'] == actor['id'],
'existing session did not survive the PostgreSQL stop/start')
postgres['session_after_recovery'] = {'status': status}
status, _, payload = http(
args.base_url, 'GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', token=actor['token'])
check(status == 200 and any(item['id'] == message['id'] for item in payload['items']),
'confirmed message was lost across the PostgreSQL stop/start')
postgres['message_after_recovery'] = {'status': status, 'found': True}
observations['postgres_outage'] = postgres
finally:
for name in (POSTGRES, VALKEY):
state = inspect_state(name)['State']
if not state['Running']:
docker('start', name)
try:
wait_status(args.base_url, '/health/ready', 200)
except Failure:
pass
volume_after = {name: inspect_state(name)['Mountpoint'] for name in VOLUMES}
states_after = {name: inspect_state(name)['State']['StartedAt'] for name in (POSTGRES, VALKEY)}
check(volume_after == volume_before, 'named volumes changed or were removed during the outage test')
check(all(states_after[name] != states_before[name] for name in states_before),
'containers were not really restarted')
observations['volumes_after'] = volume_after
observations['containers_started_after'] = states_after
observations['finished_at'] = dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps(observations, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({'valkey_recovery_seconds': observations['valkey_outage']['recovery_seconds'],
'postgres_recovery_seconds': observations['postgres_outage']['recovery_seconds'],
'volumes_kept': sorted(volume_after),
'workers_really_restarted': True}, ensure_ascii=False, sort_keys=True))
print('PASS: bounded 503 on Valkey/PostgreSQL outage; session and data survive recovery; volumes kept')
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Create a local .env with fresh synthetic passwords. The file is ignored by
# Git, is readable only by the current user, and its values are never printed.
set -eu
cd "$(dirname "$0")/.."
if [ -f .env ]; then
echo ".env already exists; refusing to overwrite it" >&2
exit 0
fi
# Alphanumeric only, so the values are safe inside a URL with no percent
# encoding. 32 bytes of /dev/urandom gives 256 bits of entropy.
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
}
postgres_password=$(random_secret)
valkey_password=$(random_secret)
if [ "${#postgres_password}" -ne 32 ] || [ "${#valkey_password}" -ne 32 ]; then
echo "could not generate local secrets" >&2
exit 1
fi
umask 077
sed \
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${postgres_password}|" \
-e "s|^VALKEY_PASSWORD=.*|VALKEY_PASSWORD=${valkey_password}|" \
.env.example > .env
chmod 600 .env
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Restart the API and every state store this lab uses, keeping the named
# volumes and all data. This is the hook for
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
# It never removes volumes, never re-seeds and never prints credentials.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
echo "restart.sh: .env is missing; run make env first" >&2
exit 2
fi
if ! ./scripts/compose.sh --env-file .env ps --status running --quiet >/dev/null 2>&1; then
echo "restart.sh: compose stack is not available" >&2
exit 2
fi
wait_healthy() {
container=$1
attempts=0
while [ "$attempts" -lt 60 ]; do
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || echo missing)
if [ "$status" = "healthy" ] || [ "$status" = "running" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: $container did not become healthy" >&2
return 1
}
echo "restart.sh: restarting postgres and valkey (volumes kept)"
./scripts/compose.sh --env-file .env restart postgres valkey
wait_healthy mtusi-lab2-melnikov-postgres
wait_healthy mtusi-lab2-melnikov-valkey
echo "restart.sh: restarting api (migrations re-applied idempotently)"
./scripts/compose.sh --env-file .env restart api
wait_healthy mtusi-lab2-melnikov-api
echo "restart.sh: all lab2 services restarted with volumes preserved"
+520
View File
@@ -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)
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Wait until /health/ready answers 200. Usage: scripts/wait-ready.sh [url]
set -eu
url=${1:-http://127.0.0.1:8080/health/ready}
attempts=0
while [ "$attempts" -lt 90 ]; do
if curl -fsS -o /dev/null "$url" 2>/dev/null; then
echo "ready: $url"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "not ready after 90 seconds: $url" >&2
exit 1