[+] lab 2
Application acceptance / api (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Xabenskie
2026-11-02 11:02:27 +03:00
parent 1da034a841
commit 990a36c95f
41 changed files with 1826 additions and 24 deletions
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
umask 077
mkdir -p secrets
python3 - <<'PY'
from pathlib import Path
import secrets
root = Path('secrets')
p = root / 'postgres_password'
if not p.exists():
p.write_text(secrets.token_hex(24))
pw = p.read_text().strip()
for name, value in {
'database_url': f'postgresql://messenger:{pw}@postgres:5432/messenger',
'cache_url': 'redis://redis:6379/0',
}.items():
path = root / name
if not path.exists():
path.write_text(value)
# Bind-mounted Docker secrets must be readable by container uid 10001.
# Parent directory remains 0700 on the host.
for path in root.iterdir():
path.chmod(0o444)
if not Path('.env').exists():
Path('.env').write_text('SESSION_TTL_SECONDS=3600\n')
print('Local secrets ready (values hidden).')
PY
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Capture repeatable short load run and sanitized environment/resource evidence."""
import datetime
import json
import platform
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def output(args):
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
def counts():
code = "import json,psycopg; from messenger.db import setting; c=psycopg.connect(setting('DATABASE_URL')); print(json.dumps({t:c.execute('SELECT count(*) FROM '+t).fetchone()[0] for t in ['users','chats','messages','sessions']})); c.close()"
return json.loads(output(['docker','compose','exec','-T','api','python','-c',code]))
def main():
names = ['mtusi-lab2-api-1','mtusi-lab2-postgres-1','mtusi-lab2-redis-1']
environment = {
'captured_at_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'host_os': platform.platform(), 'host_architecture': platform.machine(),
'docker': json.loads(output(['docker','info','--format','{"server_version":"{{.ServerVersion}}","cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"architecture":"{{.Architecture}}"}'])),
'python_in_image': output(['docker','compose','exec','-T','api','python','--version']),
'dataset_before': counts(),
'limits': {'api':'1 CPU / 512 MiB','postgres':'1 CPU / 512 MiB','redis':'0.5 CPU / 128 MiB'},
'warmup': 'API already healthy; acceptance, persistence and dependency checks performed before benchmark. No separate timed load warmup.',
'repetitions': 1, 'duration_seconds':30, 'concurrency':4,
}
if sys.platform == 'darwin':
environment['host_cpu'] = output(['sysctl','-n','machdep.cpu.brand_string'])
environment['host_memory_bytes'] = int(output(['sysctl','-n','hw.memsize']))
samples = []
with (ROOT/'evidence/load-output.txt').open('w') as log:
proc = subprocess.Popen([sys.executable,'tests/load.py','--duration','30','--concurrency','4','--output','evidence/load.json'],cwd=ROOT,stdout=log,stderr=subprocess.STDOUT)
while proc.poll() is None:
rows = output(['docker','stats','--no-stream','--format','{{json .}}',*names])
samples.append({'at_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),
'containers':[{k:v for k,v in json.loads(row).items() if k in ('Name','CPUPerc','MemUsage','MemPerc','PIDs')}
for row in rows.splitlines()]})
time.sleep(1)
if proc.returncode:
raise SystemExit(proc.returncode)
environment['dataset_after'] = counts()
(ROOT/'evidence/environment.json').write_text(json.dumps(environment,ensure_ascii=False,indent=2)+'\n')
(ROOT/'evidence/resources.json').write_text(json.dumps(samples,indent=2)+'\n')
print((ROOT/'evidence/load.json').read_text())
if __name__ == '__main__':
main()
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# A unique disposable Compose project; never touches normal project volumes.
set -eu
cd "$(dirname "$0")/.."
project="mtusi-lab2-migration-check-$$"
if [ -n "$(docker compose -p "$project" ps -aq)" ]; then
echo 'Refusing to reuse a pre-existing scratch project' >&2
exit 1
fi
cleanup() {
docker compose -p "$project" down --volumes >/dev/null 2>&1
}
trap cleanup EXIT INT TERM
docker compose -p "$project" up -d --wait --wait-timeout 90 postgres redis
docker compose -p "$project" run --rm --no-deps api sh -c 'python -m messenger.migrate && python -m messenger.migrate && python -m pytest student-tests -q -o cache_dir=/tmp/pytest-cache'
echo 'PASS: migrations and application tests on fresh disposable PostgreSQL and Redis volumes.'
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Repeatable grade-4 index experiment: SQL plans on 10000 fresh synthetic messages."""
import json
from uuid import uuid4
import psycopg
from psycopg.rows import dict_row
from messenger.db import setting
from messenger.security import HASHER
def main():
uid, cid = uuid4(), uuid4()
with psycopg.connect(setting('DATABASE_URL'), row_factory=dict_row) as conn:
conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',
(uid, 'plan_' + uuid4().hex[:24], 'Synthetic plan user', HASHER.hash(str(uuid4()))))
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (cid, 'Synthetic 10000-message index experiment'))
conn.execute('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)', (cid, uid))
conn.execute("INSERT INTO messages(id,chat_id,sender_id,text,created_at) SELECT gen_random_uuid(),%s,%s, 'Synthetic message '||n, timestamptz '2026-01-01T00:00:00Z' + n * interval '1 millisecond' FROM generate_series(1,10000) AS n", (cid, uid))
with psycopg.connect(setting('DATABASE_URL'), row_factory=dict_row, autocommit=True) as conn:
conn.execute('ANALYZE messages')
# OFFSET is used only to choose an experimental pivot, never by the application pagination.
pivot = conn.execute('SELECT created_at,id FROM messages WHERE chat_id=%s ORDER BY created_at,id OFFSET 9000 LIMIT 1', (cid,)).fetchone()
result = {'messages_in_chat': 10000, 'limit_plus_one': 51,
'index': 'messages_history_idx (chat_id, created_at, id)',
'first_sql': 'SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 ORDER BY created_at,id LIMIT 51',
'deep_sql': 'SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3) ORDER BY created_at,id LIMIT 51',
'first': None, 'deep_after_9001': None}
for key, condition, params in [
('first', '', (cid,)),
('deep_after_9001', ' AND (created_at,id) > (%s,%s)', (cid, pivot['created_at'], pivot['id']))
]:
plan = conn.execute('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s'+condition+' ORDER BY created_at,id LIMIT 51', params).fetchone()['QUERY PLAN'][0]
result[key] = plan
nodes = [plan['Plan']]
index_found = False
while nodes:
node = nodes.pop()
index_found |= node.get('Index Name') == 'messages_history_idx'
nodes.extend(node.get('Plans', []))
if not index_found:
raise RuntimeError('Planner did not use history index: ' + key)
print(json.dumps(result, indent=2, default=str))
if __name__ == '__main__':
main()
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose restart api postgres redis
docker compose up -d --wait --wait-timeout 90
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Explicit local dependency fault experiment. Restores stopped services in finally."""
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, check
def compose(*args):
return subprocess.run(['docker', 'compose', *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
def wait_ready(c):
deadline = time.monotonic() + 60
while True:
try:
c.call('GET', '/health/ready', schema='Health')
return
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(0.5)
def main():
c = Client(timeout=6)
actor = c.user('fault')
key = 'user:' + actor['id']
compose('exec', '-T', 'redis', 'redis-cli', 'DEL', key)
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
ttl = int(compose('exec', '-T', 'redis', 'redis-cli', 'TTL', key))
check(0 < ttl <= 60, 'profile was not cached with TTL')
def hits():
stats = compose('exec', '-T', 'redis', 'redis-cli', 'INFO', 'stats')
return int(next(line.split(':')[1] for line in stats.splitlines() if line.startswith('keyspace_hits:')))
before = hits()
check(c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'] == actor['user'], 'cached profile differs')
check(hits() > before, 'second profile read did not hit Redis')
results = {'cache_ttl_seconds': ttl, 'cache_miss_hit': 'PASS'}
try:
compose('stop', '-t', '2', 'redis')
response = c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
check(response['json'] == actor['user'] and response['elapsed'] < 3, 'Redis fallback failed or unbounded')
c.call('GET', '/health/ready', schema='Health')
c.call('GET', '/api/v1/users/me', 401)
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
c.call('GET', '/api/v1/users/me', 401, actor=actor)
results['redis_outage'] = {'result': 'PASS', 'fallback_seconds': round(response['elapsed'], 4),
'readiness': 200, 'anonymous': 401, 'logout': 204, 'revoked': 401}
finally:
compose('start', 'redis')
# Restored cache contains the old public profile, but may never bypass session revocation.
c.call('GET', '/api/v1/users/me', 401, actor=actor)
actor = c.user('dbfault')
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
try:
compose('stop', '-t', '2', 'postgres')
c.call('GET', '/health/live', schema='Health')
ready = c.call('GET', '/health/ready', 503)
response = c.call('GET', '/api/v1/users/me', 503, actor=actor)
check(response['elapsed'] < 5 and ready['elapsed'] < 5, 'Database timeout exceeded bound')
c.call('GET', '/api/v1/users/me', 401)
results['postgres_outage'] = {'result': 'PASS', 'authenticated_status':503,
'response_seconds':round(response['elapsed'], 4),
'readiness':503, 'liveness':200, 'anonymous':401}
finally:
compose('start', 'postgres')
recovered = time.monotonic()
wait_ready(c)
check(c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'] == actor['user'], 'session lost after DB recovery')
results['postgres_recovery_seconds'] = round(time.monotonic()-recovered, 4)
results['result'] = 'PASS'
print(json.dumps(results, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Public persistence test plus proof all three real containers restarted, volumes unchanged."""
import json
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def snapshot():
ids = subprocess.check_output(['docker','compose','ps','-q'],cwd=ROOT,text=True).split()
data = json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
return {item['Config']['Labels']['com.docker.compose.service']: {
'container': item['Name'].lstrip('/'), 'started_at': item['State']['StartedAt'],
'image': item['Config']['Image'],
'volumes': sorted(m['Name'] for m in item['Mounts'] if m['Type']=='volume')
} for item in data}
def main():
before = snapshot()
result = subprocess.run([sys.executable, 'tests/resilience.py', '--mode', 'persistence',
'--action-script', 'scripts/restart.sh'],cwd=ROOT,capture_output=True,text=True)
after = snapshot()
print(result.stdout, end='')
if result.returncode:
print(result.stderr, file=sys.stderr)
raise SystemExit(result.returncode)
for service in ['api','postgres','redis']:
assert before[service]['started_at'] != after[service]['started_at'], service + ' did not restart'
assert before[service]['volumes'] == after[service]['volumes'], service + ' volumes changed'
evidence = {'result':'PASS','before':before,'after':after,'public_test':result.stdout.strip()}
path = ROOT / 'evidence' / 'persistence.json'
path.write_text(json.dumps(evidence, indent=2)+'\n')
print('PASS: actual API/PostgreSQL/Redis restart confirmed; volume identities unchanged.')
if __name__ == '__main__':
main()