ЛР 2: исследовать и ограничить cache stampede — на 5
Student application / application (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-25 15:42:14 +03:00
parent b5b35682c2
commit 799f56c513
116 changed files with 76270 additions and 91 deletions
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Real HTTP/PG/Valkey experiment. Run only on dedicated research network.
No source instrumentation, secret output, inferred SELECT counts or retries.
"""
import argparse, csv, datetime, hashlib, http.client, json, math, os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier
import time
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]/'tests'))
from client import Client
import psycopg
from psycopg import sql
import redis
def main():
p=argparse.ArgumentParser(); p.add_argument('--label',required=True); p.add_argument('--out',required=True); p.add_argument('--pilot',action='store_true'); a=p.parse_args()
out=Path(a.out); out.mkdir(parents=True,exist_ok=False)
plan=json.loads(Path('/workspace/evidence/grade5/plan.json').read_text(encoding='utf-8-sig'))
url=Path(os.environ['DATABASE_URL_FILE']).read_text().strip()
cache_url=Path(os.environ['CACHE_URL_FILE']).read_text().strip()
with psycopg.connect(url,autocommit=True) as setup:
setup.execute('CREATE EXTENSION IF NOT EXISTS pg_stat_statements')
if not setup.execute("SELECT 1 FROM pg_roles WHERE rolname='g5observer'").fetchone():
password=psycopg.conninfo.conninfo_to_dict(url)['password']
setup.execute(sql.SQL('CREATE ROLE g5observer LOGIN SUPERUSER PASSWORD {}').format(sql.Literal(password)))
app_oid=setup.execute("SELECT oid FROM pg_roles WHERE rolname='messenger'").fetchone()[0]
observer=psycopg.connect(url,user='g5observer',autocommit=True)
blocker=psycopg.connect(url,user='g5observer',autocommit=True)
cache=redis.Redis.from_url(cache_url,decode_responses=True,socket_timeout=2)
c=Client('http://api:8080'); actor=c.user('g5bench'); key='profile:'+actor['id']
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
clients=plan['clients']; conns=[http.client.HTTPConnection('api',8080,timeout=plan['http_timeout_seconds']) for _ in range(clients)]
for conn in conns:
conn.request('GET','/health/live'); response=conn.getresponse(); response.read(); assert response.status==200
def stats():
return {str(qid):{'query':query,'calls':calls,'exec_ms':ms,'rows':rows} for qid,query,calls,ms,rows in observer.execute('SELECT queryid,query,calls,total_exec_time,rows FROM pg_stat_statements WHERE userid=%s AND dbid=(SELECT oid FROM pg_database WHERE datname=current_database())',(app_oid,))}
def category(query):
if query.startswith('SELECT user_id FROM sessions WHERE token_hash='): return 'session_select'
if query.startswith('SELECT id,username,display_name,created_at FROM users WHERE id='): return 'profile_select'
if query.strip() in ('BEGIN','COMMIT','ROLLBACK'): return 'transaction'
if query.startswith('SELECT $1'): return 'health_or_constant'
return 'other'
request_file=(out/'requests.csv').open('w',newline=''); w=csv.DictWriter(request_file,fieldnames=['mode','repeat','burst','client','status','latency_ms','error']); w.writeheader()
bursts=[]; start_all=time.monotonic()
count=2 if a.pilot else plan['bursts_per_mode_repeat']; repeats=1 if a.pilot else plan['repeats']
def request(i,barrier):
conn=conns[i]; barrier.wait(timeout=10); started=time.perf_counter(); status=0; error=''
try:
conn.request('GET','/api/v1/users/me',headers={'Authorization':'Bearer '+actor['token']})
response=conn.getresponse(); data=response.read(); status=response.status
value=json.loads(data)
if status==200 and value!=actor['user']: error='UserMismatch'
if not response.getheader('X-Request-Id'): error='MissingRequestId'
if status!=200: error='HTTP'+str(status)
except Exception as exc:
error=type(exc).__name__; conn.close()
return {'client':i,'status':status,'latency_ms':(time.perf_counter()-started)*1000,'error':error}
with ThreadPoolExecutor(max_workers=clients) as executor:
for repeat in range(1,repeats+1):
modes=plan['modes']; modes=modes[repeat-1:]+modes[:repeat-1]
for mode in modes:
for burst in range(1,count+1):
if mode=='warm':
c.call('GET','/api/v1/users/me',actor=actor,schema='User'); assert cache.exists(key)
else:
cache.delete(key); assert not cache.exists(key)
if mode=='contended':
blocker.execute('BEGIN'); blocker.execute('LOCK TABLE users IN ACCESS EXCLUSIVE MODE')
before=stats(); barrier=Barrier(clients+1)
futures=[executor.submit(request,i,barrier) for i in range(clients)]
started=time.monotonic(); barrier.wait(timeout=10)
lock_waiters=None; lock_elapsed=0
if mode=='contended':
time.sleep(plan['contended_users_lock_seconds'])
lock_waiters=observer.execute("SELECT count(*) FROM pg_stat_activity WHERE usename='messenger' AND wait_event_type='Lock'").fetchone()[0]
blocker.execute('COMMIT'); lock_elapsed=time.monotonic()-started
results=[f.result() for f in futures]; elapsed=time.monotonic()-started
after=stats(); deltas=[]; totals={cat:0 for cat in ['session_select','profile_select','transaction','health_or_constant','other']}
for qid,entry in after.items():
old=before.get(qid,{'calls':0,'exec_ms':0,'rows':0}); calls=entry['calls']-old['calls']
if calls:
kind=category(entry['query']); totals[kind]+=calls
deltas.append({'queryid':qid,'query':entry['query'],'category':kind,'calls':calls,'exec_ms':entry['exec_ms']-old['exec_ms'],'rows':entry['rows']-old['rows']})
for result in results: w.writerow({'mode':mode,'repeat':repeat,'burst':burst,**result})
request_file.flush()
bursts.append({'mode':mode,'repeat':repeat,'burst':burst,'elapsed_s':elapsed,'lock_elapsed_s':lock_elapsed,'profile_lock_waiters':lock_waiters,'counts':totals,'all_sql':sum(totals.values()),'queries':deltas})
(out/'bursts.json').write_text(json.dumps(bursts,indent=2))
print(json.dumps({'repeat':repeat,'mode':mode,'profile_select':sum(b['counts']['profile_select'] for b in bursts if b['mode']==mode and b['repeat']==repeat),'requests':count*clients}),flush=True)
request_file.close()
meta={'label':a.label,'pilot':a.pilot,'started_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'wall_s':time.monotonic()-start_all,'plan':plan,'python':sys.version,'app_src_sha256':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(Path('/app/src').glob('*.py'))},'pg_version':observer.execute('SHOW server_version').fetchone()[0],'cache_version':cache.info('server')['redis_version']}
(out/'meta.json').write_text(json.dumps(meta,indent=2))
for conn in conns: conn.close()
cache.delete(key); observer.close(); blocker.close()
print('COMPLETE',a.label,'wall_s',round(meta['wall_s'],3),flush=True)
if __name__=='__main__': main()
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Own-project cache loss/restart, expiry while down, and log disclosure checks."""
import json, sys, time, uuid
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from grade4 import compose, wait_ready
sys.path.insert(0,str(Path(__file__).resolve().parents[2]/'tests'))
from client import Client,check
def main():
c=Client('http://api:8080');short=Client('http://api-expiry:8080')
a,b,eve,chat=c.bootstrap();expired=short.user('downexpiry');revoked=c.user('downrevoked')
key='profile:'+b['id'];marker='g5_private_body_'+uuid.uuid4().hex
first=c.message(a,chat,marker)['json']
response=c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a,body={'text':marker,'sender_id':eve['id']})
check(marker.encode() not in response['bytes'],'error echoes sensitive input')
c.call('GET','/api/v1/users/me',actor=b,schema='User')
check(compose('exec','-T','valkey','valkey-cli','DEL',key)=='1','own cache loss not applied')
try:
compose('stop','valkey');time.sleep(2.2)
start=time.monotonic()
c.call('GET','/api/v1/users/me',actor=b,schema='User')
c.call('GET','/api/v1/users/me',401,actor=expired)
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=revoked)
c.call('GET','/api/v1/users/me',401,actor=revoked)
c.call('GET','/api/v1/users/me',401)
second=c.message(b,chat,'synthetic during outage')['json']
page=c.call('GET','/api/v1/chats/'+chat['id']+'/messages',actor=a,schema='MessagePage')['json']
check(first in page['items'] and second in page['items'],'outage RAW')
print('PASS: Valkey down: valid user/read-after-write work, expired/revoked/anonymous 401, errors omit input; %.3fs'%(time.monotonic()-start))
finally:compose('start','valkey')
recovered=time.monotonic()
for _ in range(40):
if compose('exec','-T','valkey','valkey-cli','PING')=='PONG':break
time.sleep(.1)
check(compose('exec','-T','valkey','valkey-cli','EXISTS',key)=='0','deleted own key unexpectedly restored')
time.sleep(5.1) # Existing bounded optional-call circuit opens for five seconds.
c.call('GET','/api/v1/users/me',actor=b,schema='User')
check(json.loads(compose('exec','-T','valkey','valkey-cli','GET',key))==b['user'],'no PG refill after restart/cooldown')
check(0<int(compose('exec','-T','valkey','valkey-cli','TTL',key))<=60,'refill TTL')
c.call('GET','/api/v1/users/me',401,actor=expired);c.call('GET','/api/v1/users/me',401,actor=revoked)
print('PASS: own profile lost before actual Valkey restart; refill from PG after cooldown, TTL<=60, expired/revoked stay401; recovery %.3fs'%(time.monotonic()-recovered))
logs=compose('logs','--no-color','api','api-peer','api-expiry','postgres','valkey')
forbidden=[marker]
for actor in [a,b,eve,expired,revoked]:forbidden.extend([actor['token'],actor['registration']['password']])
check(not any(value in logs for value in forbidden),'log disclosure (values intentionally suppressed)')
check('$argon2id$' not in logs,'password hash in logs')
print('PASS: API/PG/Valkey logs contain no test message marker, five passwords/tokens or Argon2 hashes; cache only public User fields. This is a tested marker scope, not a universal proof.')
if __name__=='__main__':main()
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Additional real HTTP/PG/Valkey checks; synthetic own keys, no global flush."""
import base64, json, os, sys, time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier
from urllib.parse import urlencode
import psycopg, redis
sys.path.insert(0,str(Path(__file__).resolve().parents[2]/'tests'))
from client import Client,check,timestamp
def main():
c=Client('http://api:8080'); peer=Client('http://api-peer:8080'); short=Client('http://api-expiry:8080')
url=Path(os.environ['DATABASE_URL_FILE']).read_text().strip()
r=redis.Redis.from_url(Path(os.environ['CACHE_URL_FILE']).read_text().strip(),decode_responses=True)
a,b,eve,chat=c.bootstrap();key='profile:'+a['id']
def me(actor=a,client=c,expected=200):return client.call('GET','/api/v1/users/me',expected,actor=actor,schema='User' if expected==200 else None)
# Profiles contain no secret/session fields; malformed optional state never leaks into HTTP.
corrupt=['','null','[]','{}','not-json',json.dumps(dict(a['user'],id=b['id'])),json.dumps(dict(a['user'],display_name=[])),json.dumps(dict(a['user'],created_at='nonsense')),json.dumps(dict(a['user'],username=4)),json.dumps(dict(a['user'],password='DO_NOT_RETURN'))]
for value in corrupt:
r.set(key,value,ex=60);check(me()['json']==a['user'],'corrupt cache escaped');check(json.loads(r.get(key))==a['user'],'corrupt cache not repaired')
r.delete(key);check(me()['json']==a['user'],'cold load mismatch')
ttl=r.ttl(key);check(0<ttl<=60,'cold TTL');check(me()['json']==a['user'],'warm mismatch');check(r.ttl(key)<=ttl,'sliding TTL')
r.pexpire(key,30);time.sleep(.05);check(not r.exists(key),'expiry');check(me()['json']==a['user'],'expiry reload')
print('PASS: cold/warm/real TTL expiry; 10 empty/malformed/wrong-id/wrong-type/extra-field values repaired from PG')
# Semantic normalization inherited from lab1, adapted to PG and Bearer.
upper=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'upper','member_ids':[a['id'].upper(),b['id']]},schema='Chat')['json']
check(a['id'] in upper['member_ids'],'UUID normalization failed')
check(c.call('GET','/api/v1/chats/'+chat['id'].upper(),actor=a,schema='Chat')['json']['id']==chat['id'],'path UUID normalization')
c.call('POST','/api/v1/chats',400,actor=a,body={'title':'duplicate alias','member_ids':[a['id'],a['id'].upper()]})
c.call('GET','/api/v1/unknown_route',404)
c.call('GET','/api/v1/chats/'+chat['id']+'/messages?cursor=bad',404,actor=eve)
first=c.message(a,chat,'cursor-a')['json'];second=c.message(a,chat,'cursor-b')['json']
page=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=1',actor=a,schema='MessagePage')['json']
payload=json.loads(base64.urlsafe_b64decode(page['next_cursor']+'='*(-len(page['next_cursor'])%4)))
for identity in ['urn:uuid:'+first['id'],first['id'].upper(),first['id'].replace('-','')]:
payload['id']=identity;cursor=base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip('=')
continuation=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?'+urlencode({'cursor':cursor}),actor=a,schema='MessagePage')['json']
check(continuation['items']==[second],'UUID cursor alias not normalized')
for stamp in ['not-a-timestamp','2026-01-01T00:00:00','2026-02-30T00:00:00Z']:
payload['created_at']=stamp;cursor=base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip('=')
c.call('GET','/api/v1/chats/'+chat['id']+'/messages?'+urlencode({'cursor':cursor}),400,actor=a)
print('PASS: member/path/cursor UUID semantics; duplicate aliases 400; malformed timestamps 400; outsider+bad cursor 404; unknown route envelope')
# Sequential read-after-write through a separate process, then the reverse.
for writer,reader in [(c,peer),(peer,c)]:
created=writer.call('POST','/api/v1/chats',201,actor=a,body={'title':'RAW cross-process','member_ids':[a['id'],b['id']]},schema='Chat')['json']
check(reader.call('GET','/api/v1/chats/'+created['id'],actor=b,schema='Chat')['json']['id']==created['id'],'chat RAW')
check(created['id'] in {x['id'] for x in reader.call('GET','/api/v1/chats',actor=b,schema='ChatPage')['json']['items']},'chat list RAW')
msg=writer.message(a,created,'synthetic RAW')['json']
check(reader.call('GET','/api/v1/chats/'+created['id']+'/messages',actor=b,schema='MessagePage')['json']['items']==[msg],'message RAW')
print('PASS: chats/chat lists/messages read-after-write immediately across two API processes in both directions')
# Revocation and expiry remain authoritative for every optional cache state.
for state in ['warm','cold','corrupt']:
actor=c.user('g5logout');own='profile:'+actor['id'];me(actor)
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=actor)
if state=='cold':r.delete(own)
if state=='corrupt':r.set(own,'[]',ex=60)
me(actor,expected=401);me(actor,client=peer,expected=401)
actor=short.user('g5expiry');own='profile:'+actor['id'];me(actor,client=short)
if state=='cold':r.delete(own)
if state=='corrupt':r.set(own,'[]',ex=60)
time.sleep(2.2);me(actor,client=short,expected=401);me(actor,client=c,expected=401)
print('PASS: revoked/expired sessions 401 in warm/cold/corrupt cache and in another API process')
# Real DB counter demonstrates local scope and bounded fallback under slow leader.
with psycopg.connect(url,user='g5observer',autocommit=True) as obs,psycopg.connect(url,user='g5observer',autocommit=True) as lock:
def profile_count():return obs.execute("SELECT coalesce(sum(calls),0) FROM pg_stat_statements WHERE userid=(SELECT oid FROM pg_roles WHERE rolname='messenger') AND query LIKE 'SELECT id,username,display_name,created_at FROM users WHERE id=%'").fetchone()[0]
for delay,replicas in [(.2,2),(1.2,1)]:
r.delete(key);before=profile_count();lock.execute('BEGIN');lock.execute('LOCK TABLE users IN ACCESS EXCLUSIVE MODE')
barrier=Barrier(9)
def request(i):barrier.wait();return me(client=peer if replicas==2 and i%2 else c)
with ThreadPoolExecutor(8) as pool:
futures=[pool.submit(request,i) for i in range(8)];start=time.monotonic();barrier.wait();time.sleep(delay);lock.execute('COMMIT');results=[f.result() for f in futures]
count=int(profile_count()-before);check(all(x['json']==a['user'] for x in results),'concurrent fallback mismatch')
if replicas==2:check(1<=count<=2,'local scope unexpected SQL')
else:check(count>=2,'1s timeout did not use real PG fallback')
print('PASS: HTTP C8 lock=%.1fs processes=%d real profile SELECT=%d elapsed=%.3fs max_http=%.3fs'%(delay,replicas,count,time.monotonic()-start,max(x['elapsed'] for x in results)))
print('PASS: grade5 additional integration checks completed')
if __name__=='__main__':main()
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
out=evidence/grade5/checks
mkdir -p "$out"
make check validate > "$out/checks.txt" 2>&1
make test BASE_URL=http://api:8080 > "$out/smoke.txt" 2>&1
python student-tests/grade4.py core > "$out/core.txt" 2>&1
python student-tests/grade4.py expiry --base-url http://api-expiry:8080 > "$out/expiry.txt" 2>&1
python student-tests/grade4.py migrations > "$out/migrations.txt" 2>&1
python student-tests/grade4.py explain > "$out/explain.txt" 2>&1
python student-tests/grade4.py failures > "$out/failures.txt" 2>&1
docker compose ps -q api postgres valkey | xargs docker inspect --format '{{.Name}} {{.State.StartedAt}} {{.Image}}' > "$out/persistence.txt"
chmod +x scripts/restart.sh
make test-persistence BASE_URL=http://api:8080 ACTION_SCRIPT=scripts/restart.sh >> "$out/persistence.txt" 2>&1
docker compose ps -q api postgres valkey | xargs docker inspect --format '{{.Name}} {{.State.StartedAt}} {{.Image}}' >> "$out/persistence.txt"
python student-tests/grade4.py persistence_meta > "$out/session-persistence.txt" 2>&1
printf 'PASS: all public and grade4 tests; isolated Compose project only\n'
+56
View File
@@ -0,0 +1,56 @@
"""Mechanism tests complement the real HTTP + measured SQL experiment."""
import sys, time, unittest
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier, Event, Lock
from unittest.mock import patch
sys.path.insert(0, '/app')
from src import cache
class SingleFlightTests(unittest.TestCase):
def tearDown(self):
self.assertEqual(cache.flights, {})
def test_same_user_one_load(self):
barrier=Barrier(16); calls=[]
def load(): calls.append(1); time.sleep(.1); return {'public':'data'}
def call(_): barrier.wait(); return cache.profile('same',load)
with patch.object(cache,'_profile',side_effect=lambda uid,load:load()):
with ThreadPoolExecutor(16) as pool: results=list(pool.map(call,range(16)))
self.assertEqual(len(calls),1);self.assertEqual(results,[{'public':'data'}]*16)
def test_different_users_do_not_serialize(self):
barrier=Barrier(2)
def load(): barrier.wait(timeout=1);return 'public'
with patch.object(cache,'_profile',side_effect=lambda uid,load:load()):
with ThreadPoolExecutor(2) as pool:
results=list(pool.map(lambda uid:cache.profile(uid,load),['a','b']))
self.assertEqual(results,['public','public'])
def test_leader_exception_wakes_waiters_and_retry(self):
started=Event();release=Event()
def load(): started.set();release.wait(2);raise ValueError('synthetic')
with patch.object(cache,'_profile',side_effect=lambda uid,load:load()):
with ThreadPoolExecutor(8) as pool:
leader=pool.submit(cache.profile,'a',load);self.assertTrue(started.wait(1))
followers=[pool.submit(cache.profile,'a',load) for _ in range(7)]
time.sleep(.05);release.set()
for f in [leader,*followers]:
with self.assertRaises(ValueError):f.result(timeout=1)
self.assertEqual(cache.profile('a',lambda:'recovered'),'recovered')
def test_wait_timeout_fallback_does_not_replace_leader(self):
started=Event();release=Event()
def leader_load():started.set();release.wait(2);return 'leader'
with patch.object(cache,'_profile',side_effect=lambda uid,load:load()),patch.object(cache,'FLIGHT_WAIT',.05):
with ThreadPoolExecutor(2) as pool:
leader=pool.submit(cache.profile,'a',leader_load);self.assertTrue(started.wait(1))
t=time.monotonic();self.assertEqual(cache.profile('a',lambda:'fallback'),'fallback')
self.assertLess(time.monotonic()-t,.5);self.assertIn('a',cache.flights)
release.set();self.assertEqual(leader.result(timeout=1),'leader')
def test_registry_limit_direct_fallback(self):
with patch.object(cache,'FLIGHT_LIMIT',0),patch.object(cache,'_profile',side_effect=AssertionError):
self.assertEqual(cache.profile('a',lambda:'direct'),'direct')
if __name__=='__main__':unittest.main(verbosity=2)