ЛР 2 — БВТ2303 — Брезгунова — на 5

This commit is contained in:
2026-10-22 13:28:45 +03:00
parent 65003b6119
commit 9ac1762101
31 changed files with 3387 additions and 37 deletions
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Extra assertions on the student's local Compose stack; restores stopped services/TTL."""
import base64
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
COMPOSE = ['docker', 'compose', '--env-file', '.env']
BASE = os.environ.get('BASE_URL', 'http://127.0.0.1:8080')
def command(args, **kwargs):
result = subprocess.run(args, cwd=ROOT, capture_output=True, **kwargs)
if result.returncode:
raise AssertionError('Infrastructure command failed: '+args[0]+' '+args[1])
return result.stdout.decode().strip()
def compose(*args, env=None):
return command(COMPOSE+list(args), env=env)
def sql(query):
return command(COMPOSE+['exec', '-T', 'postgres', 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-U', 'messenger', '-d', 'messenger', '-At', '-c', query])
def ready(c):
deadline = time.monotonic()+90
while time.monotonic()<deadline:
try:
c.call('GET', '/health/ready', schema='Health')
return
except AssertionError:
time.sleep(0.5)
raise AssertionError('API readiness timeout')
def metrics(c):
result = c.call('GET', '/metrics')['bytes'].decode()
return {line.split()[0]: float(line.split()[1]) for line in result.splitlines() if line and not line.startswith('#') and '{' not in line}
def main():
c = Client(BASE, timeout=5)
ready(c)
alice,bob,eve,chat = c.bootstrap()
results = {}
# Database uniqueness, not an application-side check, resolves this race.
registration = dict(alice['registration'], username='race_'+uuid.uuid4().hex[:16])
with ThreadPoolExecutor(max_workers=4) as pool:
statuses = list(pool.map(lambda _: Client(BASE).call('POST', '/api/v1/users', [201,409], body=registration)['status'], range(4)))
check(sorted(statuses)==[201,409,409,409], 'duplicate registration race')
results['registration_race'] = statuses
# Unknown second member fails AFTER inserting a chat and its first member.
before = sql('SELECT count(*) FROM chats')
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title':'rollback','member_ids':[alice['id'],str(uuid.uuid4())]})
check(sql('SELECT count(*) FROM chats')==before, 'partial chat survived rollback')
check(sql('SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id=m.chat_id WHERE c.id IS NULL')=='0', 'orphan membership')
results['rollback'] = 'PASS: chat and membership inserts rolled back'
# Hash and tokens never stored as plaintext.
check(sql("SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users")=='t', 'not all passwords use Argon2id')
check(sql('SELECT bool_and(octet_length(token_hash)=32) FROM sessions')=='t', 'invalid token hashes')
results['credential_storage'] = 'Argon2id; 32-byte session digests'
# Resource-bound cursor, sender spoof, Unicode password beyond bcrypt byte limit.
other = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Other','member_ids':[alice['id']]},schema='Chat')['json']
c.message(alice,chat,'one');c.message(alice,chat,'two')
page = c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=1',actor=alice,schema='MessagePage')['json']
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+page['next_cursor'],400,actor=alice)
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=alice,body={'text':'spoof','sender_id':eve['id']})
unicode_body = {'username':'uni_'+uuid.uuid4().hex[:16], 'display_name':'Юникод', 'password':'🔑'*127+':'}
c.call('POST','/api/v1/users',201,body=unicode_body,schema='User')
credential = base64.b64encode((unicode_body['username']+':'+unicode_body['password']).encode()).decode()
session = c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json']
c.call('DELETE','/api/v1/auth/sessions/current',204,actor={'token':session['token']})
results['contract_edges'] = 'PASS: cursor scope, no sender spoof, 128 Unicode password characters including colon'
# Profile cache proves actual Redis use without caching session authorization.
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
before_hits = metrics(c)['messenger_profile_cache_hits_total']
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
check(metrics(c)['messenger_profile_cache_hits_total']>before_hits, 'Redis profile cache unused')
compose('stop','redis')
try:
start = time.monotonic()
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
c.call('GET','/health/ready',schema='Health')
c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']})
check(metrics(c)['messenger_profile_cache_failures_total']>0, 'missing cache fallback metric')
results['redis_down'] = {'fallback':'PASS','seconds':round(time.monotonic()-start,3)}
finally:
compose('start','redis')
ready(c)
# A lost cache is harmless: existing sessions and confirmed messages are in PostgreSQL.
compose('exec','-T','redis','redis-cli','FLUSHDB')
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
c.call('GET','/api/v1/chats/'+chat['id']+'/messages',actor=bob,schema='MessagePage')
results['cache_loss'] = 'PASS: cache rebuild; original session/data valid'
compose('stop','postgres')
try:
start = time.monotonic()
c.call('GET','/api/v1/users/me',503,actor=alice)
c.call('GET','/health/ready',503)
c.call('GET','/health/live',schema='Health')
c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']})
elapsed = time.monotonic()-start
check(elapsed<7, 'database outage unbounded')
results['postgres_down'] = {'protected_request':503,'readiness':503,'liveness':200,'seconds':round(elapsed,3)}
finally:
compose('start','postgres')
ready(c)
# Re-running migrations on startup changes neither schema version nor data.
counts = sql("SELECT (SELECT count(*) FROM schema_migrations)||':'||(SELECT count(*) FROM users)||':'||(SELECT count(*) FROM messages)")
compose('restart','api');ready(c)
check(sql("SELECT (SELECT count(*) FROM schema_migrations)||':'||(SELECT count(*) FROM users)||':'||(SELECT count(*) FROM messages)")==counts, 'migration replay modified data')
results['migration_replay'] = 'PASS: same migration/user/message counts'
# Dedicated short TTL run. Restore normal configuration even on assertion failure.
short_env = dict(os.environ, SESSION_TTL_SECONDS='2')
try:
compose('up','-d','--no-deps','api',env=short_env);ready(c)
short = c.user('short')
c.call('GET','/api/v1/users/me',actor=short,schema='User')
time.sleep(2.2)
c.call('GET','/api/v1/users/me',401,actor=short)
results['expiry'] = 'PASS: SESSION_TTL_SECONDS=2 rejects existing token after expiry'
finally:
compose('up','-d','--no-deps','api');ready(c)
c.call('GET','/api/v1/users/me',401,actor=short)
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('GET','/api/v1/users/me',401,actor=alice)
results['logout'] = 'PASS: revoked token rejected'
(ROOT/'evidence'/'integration.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print('PASS: races, rollback, KDF, cache hit/loss/outage, DB outage, migration replay, expiry, logout')
if __name__=='__main__':
main()
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Public closed-loop load with contemporaneous Docker CPU/RAM samples."""
import datetime as dt
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
def main():
samples = []
ids = subprocess.run(['docker','compose','ps','-q','api','postgres','redis'],cwd=ROOT,capture_output=True,text=True,check=True).stdout.split()
started = time.monotonic()
proc = subprocess.Popen([sys.executable,'tests/load.py','--base-url','http://127.0.0.1:8080','--duration','30','--concurrency','4','--output','evidence/load.json'],cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',errors='replace')
while proc.poll() is None:
result = subprocess.run(['docker','stats','--no-stream','--format','{{json .}}']+ids,cwd=ROOT,capture_output=True,text=True)
samples.append({'seconds':round(time.monotonic()-started,3),'containers':[json.loads(line) for line in result.stdout.splitlines()]})
time.sleep(3)
out,err = proc.communicate()
evidence = {'sampled_at_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'command':'python tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 4 --output evidence/load.json', 'exit_code':proc.returncode,'stdout':out.strip(),'stderr':err.strip(),'samples':samples}
(ROOT/'evidence'/'resources.json').write_text(json.dumps(evidence,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(out.strip())
if proc.returncode:
print(err)
raise SystemExit(proc.returncode)
if __name__=='__main__':
main()
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Track 2: isolated 100k dataset, index/write comparison, dump -> NEW DB -> checks.
Uses only synthetic data in uniquely named research databases; never changes app tables.
"""
import datetime as dt
import json
from pathlib import Path
import platform
import re
import statistics
import subprocess
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = ['docker', 'compose', '--env-file', '.env']
USER = '11111111-1111-4111-8111-111111111111'
HOT = '22222222-2222-4222-8222-222222222222'
def command(args, data=None):
result = subprocess.run(args, cwd=ROOT, input=data, capture_output=True)
if result.returncode:
raise RuntimeError('Research infrastructure command failed: '+args[0]+' '+args[1]+'; '+result.stderr.decode(errors='replace')[:500])
return result.stdout
def sql(database, query, service='postgres'):
return command(COMPOSE+['exec','-T',service,'psql','-X','-v','ON_ERROR_STOP=1','-U','messenger','-d',database,'-At','-c',query]).decode().strip()
def plan(database, query, rollback=False):
query = 'EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) '+query
if rollback:
query = 'BEGIN; '+query+'; ROLLBACK;'
output = sql(database, query)
start = output.index('[')
value, _ = json.JSONDecoder().raw_decode(output[start:])
return value[0]
def fingerprint(database, service='postgres'):
query = """SELECT json_build_object(
'users',(SELECT count(*) FROM users),
'chats',(SELECT count(*) FROM chats),
'members',(SELECT count(*) FROM chat_members),
'messages',(SELECT count(*) FROM messages),
'content_digest',(SELECT md5(string_agg(md5(row(id,chat_id,sender_id,text,created_at)::text),'' ORDER BY id)) FROM messages),
'selected',(SELECT json_agg(x) FROM (SELECT * FROM messages ORDER BY id LIMIT 10) x))"""
return json.loads(sql(database, query, service))
def main():
suffix = uuid.uuid4().hex[:12]
database, restored = 'research_'+suffix, 'research_restore_'+suffix
created = []
results = {'generated_at_utc':dt.datetime.now(dt.timezone.utc).isoformat(),
'hypothesis':'Index (chat_id,created_at,id) bounds keyset page work independently of total chat history, at a measurable write/index-space cost.',
'host':platform.platform(),'limits':{'postgres_cpu':1,'postgres_memory_mb':512},
'messages':100000,'distribution':[80000,15000]+[625]*8,'warmup_reads':2,'measured_repetitions':5,'variants':{}}
try:
command(COMPOSE+['--profile','research','up','-d','--wait','restore'])
for name, service, admin in [(database,'postgres','messenger'),(restored,'restore','restore_validation')]:
assert re.fullmatch(r'research_(restore_)?[a-f0-9]{12}',name)
sql(admin,'CREATE DATABASE '+name,service)
created.append((name, service, admin))
sql(database,(ROOT/'migrations'/'001_initial.sql').read_text(encoding='utf-8'))
sql(database,"INSERT INTO users(id,username,display_name,password_hash) VALUES('"+USER+"','research_user','Synthetic researcher','research-fixture-not-a-login')")
for chat_index, count in enumerate(results['distribution']):
chat_id = HOT if chat_index==0 else str(uuid.uuid5(uuid.NAMESPACE_DNS,'lab2-research-chat-'+str(chat_index)))
sql(database,f"INSERT INTO chats(id,title) VALUES('{chat_id}','Research {chat_index}'); INSERT INTO chat_members(chat_id,user_id,position) VALUES('{chat_id}','{USER}',0)")
sql(database,f"INSERT INTO messages(id,chat_id,sender_id,text,created_at) SELECT md5('seed-{chat_index}-'||n)::uuid,'{chat_id}','{USER}',repeat('x',{200 if chat_index==0 else 40}),'2026-01-01T00:00:00Z'::timestamptz+n*interval '1 second' FROM generate_series(1,{count}) n")
sql(database,'ANALYZE messages')
results['postgres_version'] = sql(database,'SELECT version()')
variants = {'chat_only':'CREATE INDEX research_chat_only ON messages(chat_id)',
'keyset':'CREATE INDEX messages_history ON messages(chat_id,created_at,id)'}
for variant,ddl in variants.items():
sql(database,'DROP INDEX IF EXISTS messages_history; DROP INDEX IF EXISTS research_chat_only; '+ddl+'; ANALYZE messages')
index_name = 'research_chat_only' if variant=='chat_only' else 'messages_history'
measurements = {'index_bytes':int(sql(database,"SELECT pg_relation_size('"+index_name+"')")), 'pages':{}}
for position in [0,40000,79000]:
query = f"SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id='{HOT}' AND (created_at,id)>('2026-01-01T00:00:00Z'::timestamptz+{position}*interval '1 second','ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid) ORDER BY created_at,id LIMIT 51"
for _ in range(2):
plan(database,query)
plans = [plan(database,query) for _ in range(5)]
measurements['pages'][str(position)] = {'execution_ms':[p['Execution Time'] for p in plans],
'median_ms':statistics.median(p['Execution Time'] for p in plans),'representative_plan':plans[2]}
writes = []
for repetition in range(5):
# Roll back after EACH measured insertion, so both variants see the same logical dataset.
query = f"INSERT INTO messages(id,chat_id,sender_id,text,created_at) SELECT md5('write-{variant}-{repetition}-'||n)::uuid,'{HOT}','{USER}',repeat('w',200),'2026-02-01T00:00:00Z'::timestamptz+n*interval '1 second' FROM generate_series(1,2000) n"
writes.append(plan(database,query,rollback=True))
measurements['write_2000'] = {'execution_ms':[p['Execution Time'] for p in writes],
'median_ms':statistics.median(p['Execution Time'] for p in writes),'representative_plan':writes[2]}
results['variants'][variant] = measurements
# The selected production index remains in the restored schema.
source = fingerprint(database)
check_count = source['messages']==100000 and source['chats']==10
if not check_count:
raise AssertionError('Research dataset count mismatch')
folder = ROOT/'backups'
folder.mkdir(exist_ok=True)
backup = folder/(database+'.dump')
start = time.monotonic()
dump = command(COMPOSE+['exec','-T','postgres','pg_dump','-U','messenger','-d',database,'-Fc'])
backup.write_bytes(dump)
backup_seconds = time.monotonic()-start
start = time.monotonic()
command(COMPOSE+['exec','-T','restore','pg_restore','--exit-on-error','--no-owner','-U','messenger','-d',restored], data=dump)
restore_seconds = time.monotonic()-start
target = fingerprint(restored,'restore')
if source!=target:
raise AssertionError('Restored data differs from snapshot')
results['backup_restore'] = {'backup_bytes':len(dump),'backup_seconds':round(backup_seconds,3),
'restore_seconds':round(restore_seconds,3),'source':source,'restored':target,'equal':True,
'scope':'empty database on separate PostgreSQL container and separate named volume; all counts, ordered digest of every message, and 10 complete messages match'}
results['limitations'] = ['Warm buffer cache, 5 sequential trials, local single-host containers; no claim of max production throughput.',
'Write timing is EXPLAIN ANALYZE of 2000 inserts followed by rollback; includes constraints/triggers and excludes durable COMMIT latency. Aborted inserts can leave dead tuples.',
'Logical backup captures the dump snapshot. Writes committed after that snapshot are not included; no WAL archiving/PITR. Restore time excludes operator detection and provisioning.',
'Research fixtures use SQL bulk insert; HTTP validation/authentication cost is measured separately by the public load tool.']
(ROOT/'evidence'/'research.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print('PASS: 100000 messages, two indexes/read-write measurements, backup restored to new database with matching content')
print(json.dumps({'read_middle_ms':{name:value['pages']['40000']['median_ms'] for name,value in results['variants'].items()},'restore_seconds':results['backup_restore']['restore_seconds']},ensure_ascii=False))
finally:
for name, service, admin in reversed(created):
# Only drop names generated AND created by this invocation, never application DB.
assert re.fullmatch(r'research_(restore_)?[a-f0-9]{12}',name)
sql(admin,'DROP DATABASE '+name+' WITH (FORCE)', service)
command(COMPOSE+['--profile','research','stop','restore'])
if __name__=='__main__':
main()
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Run local checks serially and keep sanitized output + restart scope evidence."""
import datetime as dt
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = ['docker','compose','--env-file','.env']
def command(args):
result = subprocess.run(args,cwd=ROOT,capture_output=True,text=True,encoding='utf-8',errors='replace')
return result
def snapshot():
ids = command(COMPOSE+['ps','-q','api','postgres','redis'])
if ids.returncode:
raise RuntimeError('Cannot inspect local lab stack')
result = command(['docker','inspect','--format','{{json .Name}} {{json .Id}} {{json .State.StartedAt}} {{json .State.Status}}']+ids.stdout.split())
if result.returncode:
raise RuntimeError('Cannot inspect restart scope')
# Narrow format intentionally excludes environment/credentials.
return result.stdout.strip().splitlines()
def main():
results = {'timestamp_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'host':platform.platform(),'base_url':'http://127.0.0.1:8080','checks':[]}
hook = 'scripts/restart.cmd' if os.name=='nt' else 'scripts/restart.sh'
if os.name!='nt':
(ROOT/hook).chmod(0o755)
commands = [
[sys.executable,'scripts/check_contract.py'],
[sys.executable,'tests/smoke.py','--base-url',results['base_url']],
[sys.executable,'tests/resilience.py','--mode','persistence','--action-script',hook,'--base-url',results['base_url']],
[sys.executable,'student-tests/integration.py'],
[sys.executable,'student-tests/research.py'],
[sys.executable,'tests/load.py','--base-url',results['base_url'],'--duration','30','--concurrency','4','--output','evidence/load.json'],
]
try:
for args in commands:
persistence = 'tests/resilience.py' in args
if persistence:
results['restart_before'] = snapshot()
start = time.monotonic()
completed = command(args)
entry = {'command':' '.join(args[1:]),'exit_code':completed.returncode,'seconds':round(time.monotonic()-start,3),'stdout':completed.stdout.strip(),'stderr':completed.stderr.strip()}
results['checks'].append(entry)
print(entry['stdout'],flush=True)
if persistence:
results['restart_after'] = snapshot()
if completed.returncode==0:
before = {line.split()[0]:line.split()[2] for line in results['restart_before']}
after = {line.split()[0]:line.split()[2] for line in results['restart_after']}
if before.keys()!=after.keys() or any(before[key]==after[key] for key in before):
raise AssertionError('Not every API/state-store process restarted')
results['restart_scope_verified'] = True
if completed.returncode:
print(entry['stderr'],flush=True)
raise SystemExit(completed.returncode)
finally:
(ROOT/'evidence'/'verification.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
if __name__=='__main__':
main()