Implement lab3 scaling, shared idempotency, failure research and defense guide

This commit is contained in:
2026-10-29 21:36:47 +03:00
parent 0ab3a341aa
commit 99c87315cf
58 changed files with 8860 additions and 24 deletions
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Run committed solution from a real local clone, new credentials and volumes."""
import json,os,socket,subprocess,tempfile,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
lab=json.loads((ROOT/'lab.json').read_text())['number']
project='verify-lab'+str(lab)+'-'+uuid.uuid4().hex[:10]
with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
with tempfile.TemporaryDirectory(prefix=project+'-') as directory:
clone=Path(directory)/'repo';subprocess.run(['git','clone','--no-hardlinks',str(ROOT),str(clone)],check=True)
env=dict(os.environ,COMPOSE_PROJECT_NAME=project,APP_PORT=str(port),API_REPLICAS='2',SESSION_TTL_SECONDS='3600')
def run(*args):subprocess.run(args,cwd=clone,env=env,check=True)
def snapshots():
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=clone,env=env,text=True).splitlines()
result={}
for id in ids:
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
service=item['Config']['Labels']['com.docker.compose.service']
if service in ['api','postgres','valkey','s3']:result[item['Name']]={'service':service,'started_at':item['State']['StartedAt'],'image_id':item['Image'],'user':item['Config'].get('User',''),'pid1':item['Path']}
return result
try:
run('make','up');run('make','check');run('make','test','BASE_URL=http://localhost:'+str(port))
before=snapshots();run('make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL=http://localhost:'+str(port));after=snapshots()
for name,item in before.items():assert after[name]['started_at']!=item['started_at'],name+' was not restarted'
for item in after.values():
if item['service']=='api':assert item['user']=='10001:10001' and item['pid1']=='/usr/local/bin/messenger'
(ROOT/'evidence/persistence-processes.json').write_text(json.dumps({'scope':'disposable real clean clone','before':before,'after':after},indent=2)+'\n')
print('PASS: real clean clone, fresh secrets/volumes, smoke, same-session persistence, actual store/API restart, non-root PID1')
finally:
# Only this unique synthetic project, never the working lab volumes.
run('docker','compose','down','-v','--remove-orphans')
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Concurrent repeats through LB and the full idempotency scope."""
import concurrent.futures as futures
import json
from pathlib import Path
import sys
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client,arguments,check
def main():
args=arguments('Student idempotency tests')
c=Client(args.base_url)
alice,bob,eve,chat=c.bootstrap()
key=uuid.uuid4().hex
def send(_):
return Client(c.base).message(alice,chat,'Concurrent one',key=key)
with futures.ThreadPoolExecutor(max_workers=12) as pool:results=list(pool.map(send,range(24)))
check(len({r['json']['id'] for r in results})==1,'duplicate committed message')
instances=sorted({r['headers']['X-Instance-Id'] for r in results})
check(len(instances)>=2,'must observe two API processes')
path='/api/v1/chats/'+chat['id']+'/messages'
c.call('POST',path,409,actor=alice,body={'text':'changed'},headers={'Idempotency-Key':key})
for headers in [{},{'Idempotency-Key':'x'*129},{'Idempotency-Key':'bad key'}]:c.call('POST',path,400,actor=alice,body={'text':'x'},headers=headers)
different=c.message(bob,chat,'Bob independent',key=key)['json']
check(different['id']!=results[0]['json']['id'],'user scope collided')
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id']]},schema='Chat')['json']
c.message(alice,other,'Other scope',key=key)
page=c.call('GET',path,actor=alice,schema='MessagePage')['json']
check(len(page['items'])==2,'history has a duplicate')
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('POST',path,401,actor=alice,body={'text':'Concurrent one'},headers={'Idempotency-Key':key})
result={'parallel_requests':24,'created_messages':1,'observed_instances':instances,'user_chat_scope':True,'revalidation_after_logout':True}
(Path(__file__).resolve().parents[1]/'evidence/integration.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS:',json.dumps(result))
if __name__=='__main__':main()
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Stop each real container, then replace them in sequence under writes."""
import json,os,subprocess,sys,threading,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
BASE=os.environ.get('BASE_URL','http://localhost:8083')
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def inspect(id):return json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
def ready():
deadline=time.monotonic()+45
while time.monotonic()<deadline:
try:
dc('up','-d','--no-deps','--wait','api');time.sleep(2);return
except subprocess.CalledProcessError:time.sleep(1)
raise AssertionError('API did not recover')
def run_phase(c,actor,chat,action,seconds=7):
results=[];failed=0;stop=threading.Event();events=[];seen=set()
def write():
nonlocal failed
client=Client(BASE,timeout=2);key=uuid.uuid4().hex
while not stop.is_set():
try:
response=client.message(actor,chat,'operation probe '+key,key=key)
results.append((time.monotonic(),response['json']['id']))
seen.add(response['headers']['X-Instance-Id']);key=uuid.uuid4().hex
except Failure:failed+=1
time.sleep(.02)
worker=threading.Thread(target=write);worker.start();time.sleep(1)
started=time.monotonic();action();action_done=time.monotonic();time.sleep(seconds);stop.set();worker.join()
history=[];path='/api/v1/chats/'+chat['id']+'/messages?limit=100'
from urllib.parse import quote
while True:
page=c.call('GET',path,actor=actor,schema='MessagePage')['json'];history+=page['items']
if page['next_cursor'] is None:break
path='/api/v1/chats/'+chat['id']+'/messages?limit=100&cursor='+quote(page['next_cursor'],safe='')
ids=[m['id'] for m in history];check(len(ids)==len(set(ids)),'duplicate IDs')
check({i for _,i in results}.issubset(set(ids)),'lost confirmed message')
successes_after=[t for t,_ in results if t>=action_done]
check(successes_after,'no successful write after action')
recovery=successes_after[0]-started
return {'successful_writes':len(results),'errors':failed,'successful_rps':len(results)/(time.monotonic()-started+1),'first_recovery_seconds':round(recovery,3),'action_seconds':round(action_done-started,3),'instances':sorted(seen),'confirmed_preserved':True}
def main():
ready();c=Client(BASE);a,b,e,chat=c.bootstrap();results={'failures':[]}
ids=dc('ps','-q','api').splitlines();check(len(ids)==2,'requires two API containers')
for id in ids:
alias=inspect(id)['Config']['Hostname']
env=dict(os.environ,TARGET_INSTANCE_ID=alias)
def action():subprocess.run([str(ROOT/'scripts/stop-one.sh')],env=env,check=True,stdout=subprocess.DEVNULL)
try:
result=run_phase(c,a,chat,action);result['stopped_alias']=alias
check(not inspect(id)['State']['Running'],'target is still running')
check(result['first_recovery_seconds']<10,'recovery >10s')
results['failures'].append(result)
finally:ready()
results['rolling']=run_phase(c,a,chat,lambda:subprocess.run([str(ROOT/'scripts/rolling.sh')],check=True,stdout=subprocess.DEVNULL),seconds=2)
check(len(dc('ps','-q','api').splitlines())==2,'rolling lost replicas')
(ROOT/'evidence/operations.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS: each API stopped and rolling replacement completed; confirmed writes preserved')
if __name__=='__main__':main()
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Render source JSON as a reproducible scientific figure and a compact table."""
import csv,json,statistics
from collections import defaultdict
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT=Path(__file__).resolve().parents[1]
report=json.loads((ROOT/'evidence/scaling.json').read_text());groups=defaultdict(list)
for run in report['runs']:groups[(run['series'],run['replicas'],run['concurrency'],run.get('pool_per_api',10))].append(run)
summary=[]
for (series,n,clients,pool),rows in sorted(groups.items()):
result={'series':series,'replicas':n,'clients':clients,'pool_per_api':pool,'repeats':len(rows)}
for field in ['successful_rps','error_fraction','p50_ms','p95_ms','p99_ms']:result[field]=statistics.median(r[field] for r in rows)
summary.append(result)
with (ROOT/'evidence/scaling-summary.csv').open('w') as f:
w=csv.DictWriter(f,fieldnames=list(summary[0]));w.writeheader();w.writerows(summary)
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,'axes.spines.right':False})
fig,axes=plt.subplots(2,2,figsize=(11,7),layout='constrained')
colors={1:'#147d92',2:'#d27925',4:'#814eac'}
for col,series in enumerate(['fixed','growing']):
for n in [1,2,4]:
rows=[r for r in summary if r['series']==series and r['replicas']==n]
axes[0,col].plot([r['clients'] for r in rows],[r['successful_rps'] for r in rows],marker='o',color=colors[n],label=f'{n} API')
axes[1,col].plot([r['clients'] for r in rows],[r['p99_ms'] for r in rows],marker='o',color=colors[n])
axes[0,col].set_title('Fixed: total API 2 CPU / 1024 MiB' if series=='fixed' else 'Growing: 1 CPU / 512 MiB per API')
axes[0,col].set_ylabel('Successful responses / s');axes[0,col].legend(frameon=False)
axes[1,col].set_ylabel('p99 of successful responses, ms');axes[1,col].set_xlabel('Concurrent clients')
for ax in axes[:,col]:ax.set_xticks([4,16,64]);ax.grid(alpha=.2)
fig.suptitle('Messenger POST scaling — medians of two 6 s runs, 16 chats',fontsize=14)
fig.savefig(ROOT/'evidence/scaling.png',dpi=180)
fig.savefig(ROOT/'evidence/scaling.pdf')
lines=['# Масштабирование: измеренные результаты','', 'Raw: `scaling.json`. График: `scaling.png`; таблица: `scaling-summary.csv`.', '', 'Медианы двух 6-секундных прогонов после 2 s прогрева на каждую конкуренцию. PostgreSQL2 CPU/512MiB, LB1 CPU/128MiB. 16 чатов, 4/16/64 closed-loop клиента, reusable HTTP connections; без retry. Процентили только успешных HTTP201; ошибки отдельно. Каждый point содержит raw cgroups и samples PostgreSQL.','', '| Серия | API | Клиенты | RPS | Ошибки % | p50 ms | p95 ms | p99 ms |','|---|---:|---:|---:|---:|---:|---:|---:|']
for r in summary:
lines.append(f"| {r['series']}"+(f" pool={r['pool_per_api']}" if r['series']=='pool_improvement' else '')+f" | {r['replicas']} | {r['clients']} | {r['successful_rps']:.1f} | {100*r['error_fraction']:.3f} | {r['p50_ms']:.3f} | {r['p95_ms']:.3f} | {r['p99_ms']:.3f} |")
lines += ['','## Ресурсы и ожидания','', '| Серия | API | Клиенты | CPU API sum % | CPU PostgreSQL % | CPU LB % | API max cgroup peak MiB |','|---|---:|---:|---:|---:|---:|---:|']
for (series,n,clients,pool),runs in sorted(groups.items()):
if series=='pool_improvement':continue
def cpu(service):return statistics.median(sum(v['cpu_percent'] for v in r['cgroup_after'].values() if v['service']==service) for r in runs)
peak=max(v['memory_peak'] for r in runs for v in r['cgroup_after'].values() if v['service']=='api')/2**20
lines.append(f'| {series} | {n} | {clients} | {cpu("api"):.1f} | {cpu("postgres"):.1f} | {cpu("lb"):.1f} | {peak:.1f} |')
lines += ['','CPU100%=один core. CPU измерен за окно snapshots, включающее небольшую инструментальную накладную стоимость, не только ровно6s. memory.peak накоплен с запуска контейнера, current до/после тоже сохранён. Pg_stat_activity samples позволяют наблюдать WAL/locks/CPU, но не являются непрерывным профилем.','']
for pool,rows in report.get('pool_diagnostics',{}).items():
# Each instance emits cumulative counters; retain the final sample per instance
# when available; otherwise show conservative maxima rather than sum duplicates.
last={}
for row in rows:last[row.get('instance','unknown')]=row
for instance,row in last.items():lines.append(f"- Pool{pool}, instance{instance}: acquires={row['acquires']}, empty_acquires={row['empty_acquires']}, accumulated empty wait={row['wait_ns']/1e9:.3f}s (process lifetime counters).")
lines += ['','## Границы измерения','', 'Короткие прогоны на одном host, warm caches, fixed ordering, растущие tables и coordinated omission. Предельные задержки во время перегрузки могут быть недооценены closed-loop моделью. Токены только в памяти и stdin генератора, в evidence не сохраняются. SQL/RAM/WAL и работа нескольких процессов ограничивают масштабирование; выводы относятся к измеренному POST-профилю.']
(ROOT/'evidence/scaling-summary.md').write_text('\n'.join(lines)+'\n')
print('Wrote PNG/PDF/CSV/Markdown from raw evidence')
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""1/2/4 replicas, fixed and growing resources, raw cgroups and pool diagnostics."""
import json,os,platform,statistics,subprocess,sys,time,threading
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
BASE='http://localhost:8083'
ENV=dict(os.environ,POOL_DIAGNOSTICS='1')
def dc(*a,env=None):return subprocess.check_output(['docker','compose',*a],cwd=ROOT,env=env or ENV,text=True,stderr=subprocess.DEVNULL).strip()
def snapshot():
result={}
for service in ['api','postgres','lb']:
for id in dc('ps','-q',service).splitlines():
raw=subprocess.check_output(['docker','exec',id,'sh','-c','cat /sys/fs/cgroup/cpu.stat; cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak'],text=True).splitlines()
values={};numbers=[]
for line in raw:
items=line.split()
if len(items)==2:values[items[0]]=int(items[1])
else:numbers.append(int(line))
result[id[:12]]={'service':service,'usage_usec':values['usage_usec'],'nr_throttled':values['nr_throttled'],'throttled_usec':values['throttled_usec'],'memory_current':numbers[0],'memory_peak':numbers[1]}
return result
def main():
binary=ROOT/'bin/bench';binary.parent.mkdir(exist_ok=True)
subprocess.run(['go','build','-o',str(binary),'./cmd/bench'],cwd=ROOT,env=dict(os.environ,GOCACHE='/private/tmp/highload-go-cache'),check=True)
redo=set(filter(None,os.environ.get('SCALING_REDO','').split(',')))
report={'host':{'platform':platform.platform(),'machine':platform.machine(),'logical_cpus':os.cpu_count(),'docker':subprocess.check_output(['docker','info','--format','{{.Architecture}} CPUs={{.NCPU}} Memory={{.MemTotal}}'],text=True).strip()},'method':{'warmup_seconds':2,'duration_seconds':6,'repetitions':2,'chats':16,'profile':'one immutable ~128-character POST per worker, uniform round-robin among 16 chats; fresh unique key; no retry; successful percentiles; closed loop'},'runs':[]}
if redo:report=json.loads((ROOT/'evidence/scaling.json').read_text())
def configure(n,cpu,memory,pool=10):
env=dict(ENV,API_REPLICAS=str(n),API_CPUS=str(cpu),API_MEMORY=str(memory)+'m',DB_POOL_MAX=str(pool))
dc('up','-d','--no-deps','--scale','api='+str(n),'--force-recreate','--wait','api',env=env)
time.sleep(3)
return env
def bench(fixture,concurrency,duration):
waits=[];stop=threading.Event()
def observe():
while not stop.is_set():
try:waits.append(dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',"SELECT coalesce(wait_event_type,'CPU')||':'||coalesce(wait_event,'running')||':'||count(*) FROM pg_stat_activity WHERE datname='messenger' AND pid<>pg_backend_pid() AND state<>'idle' GROUP BY wait_event_type,wait_event"))
except subprocess.CalledProcessError:pass
stop.wait(.5)
monitor=threading.Thread(target=observe);monitor.start()
try:output=subprocess.check_output([str(binary),'-base',BASE,'-concurrency',str(concurrency),'-duration',str(duration)+'s'],input=json.dumps(fixture),text=True)
finally:stop.set();monitor.join()
result=json.loads(output);result['pg_wait_samples']=waits;return result
try:
for series in ['fixed','growing']:
for n in [1,2,4]:
if redo and series+':'+str(n) not in redo:continue
if redo:report['runs']=[r for r in report['runs'] if not (r['series']==series and r['replicas']==n)]
cpu=2/n if series=='fixed' else 1;memory=1024//n if series=='fixed' else 512
configure(n,cpu,memory)
c=Client(BASE);a=c.user('scaling');chats=[]
for i in range(16):chats.append(c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Scaling','member_ids':[a['id']]},schema='Chat')['json']['id'])
fixture={'token':a['token'],'chats':chats}
for clients in [4,16,64]:
bench(fixture,clients,2)
for repeat in range(2):
before=snapshot();started=time.time();result=bench(fixture,clients,6);after=snapshot()
result.update(started_unix=started,series=series,replicas=n,cpu_per_api=cpu,memory_mib_per_api=memory,pool_per_api=10,repeat=repeat+1,cgroup_before=before,cgroup_after=after)
for id,stat in after.items():
stat['cpu_percent']=100*(stat['usage_usec']-before[id]['usage_usec'])/1e6/(time.time()-started)
result['messages_in_database_after']=int(dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc','SELECT count(*) FROM messages'))
report['runs'].append(result);(ROOT/'evidence/scaling.json').write_text(json.dumps(report,indent=2)+'\n')
print(series,n,clients,repeat+1,round(result['successful_rps']),flush=True)
# Deliberate pool starvation baseline and one measured improvement.
for pool in [1,10]:
if redo and 'pool' not in redo:continue
if redo:report['runs']=[r for r in report['runs'] if not (r['series']=='pool_improvement' and r['pool_per_api']==pool)]
configure(2,1,512,pool)
c=Client(BASE);a=c.user('pool');chats=[c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Pool','member_ids':[a['id']]},schema='Chat')['json']['id'] for _ in range(16)]
fixture={'token':a['token'],'chats':chats};bench(fixture,32,2)
for rep in range(3):
result=bench(fixture,32,6);result.update(series='pool_improvement',replicas=2,pool_per_api=pool,repeat=rep+1)
report['runs'].append(result)
report.setdefault('pool_diagnostics',{})[str(pool)]=[json.loads(line) for line in dc('logs','--no-log-prefix','--tail','10000','api').splitlines() if line.startswith('{') and '"msg":"pool"' in line]
(ROOT/'evidence/scaling.json').write_text(json.dumps(report,indent=2)+'\n')
finally:dc('up','-d','--no-deps','--scale','api=2','--force-recreate','--wait','api',env=dict(os.environ,API_REPLICAS='2',API_CPUS='1',API_MEMORY='256m',DB_POOL_MAX='10'))
print('DONE',flush=True)
if __name__=='__main__':main()
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""Small sanitized runtime manifest; no environment, passwords or tokens."""
import json,platform,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=ROOT,text=True).splitlines()
result={'platform':platform.platform(),'containers':[]}
for id in ids:
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
result['containers'].append({'service':item['Config']['Labels']['com.docker.compose.service'],'name':item['Name'],'alias':item['Config']['Hostname'],'image':item['Config']['Image'],'image_id':item['Image'],'user':item['Config']['User'],'pid1_path':item['Path'],'started_at':item['State']['StartedAt'],'memory_limit_bytes':item['HostConfig']['Memory'],'nano_cpus_limit':item['HostConfig']['NanoCpus'],'published_ports':item['NetworkSettings']['Ports'],'health':item['State'].get('Health',{}).get('Status'),'mount_targets':[m['Destination'] for m in item['Mounts']]})
result['postgres_durability']=subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',"SELECT name||'='||setting FROM pg_settings WHERE name IN ('fsync','synchronous_commit','full_page_writes','max_connections') ORDER BY name"],cwd=ROOT,text=True).splitlines()
(ROOT/'evidence/runtime.json').write_text(json.dumps(result,indent=2)+'\n')
print('Saved sanitized runtime manifest: resources, images, PID1, ports, durability')