выполненная лаб3

This commit is contained in:
2026-10-23 18:29:24 +03:00
parent 0ab3a341aa
commit f026c27938
57 changed files with 32952 additions and 33 deletions
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""Generate local synthetic credentials once; never print their values."""
from pathlib import Path
import secrets
root=Path(__file__).resolve().parents[1]
folder=root/'secrets'
folder.mkdir(mode=0o700,exist_ok=True)
folder.chmod(0o700)
password=folder/'db_password'
if not password.exists():
password.write_text(secrets.token_hex(32))
for name,value in {'database_url':'postgresql://messenger:'+password.read_text().strip()+'@postgres:5432/messenger','cache_url':'redis://redis:6379/0'}.items():
path=folder/name
if not path.exists(): path.write_text(value)
for path in folder.iterdir(): path.chmod(0o600)
if not (root/'.env').exists(): (root/'.env').write_text('API_REPLICAS=2\nSESSION_TTL_SECONDS=3600\n')
print('Local secrets ready (values hidden).')
+20
View File
@@ -0,0 +1,20 @@
import sys,base64,uuid
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client,check
c=Client()
a,b,e,chat=c.bootstrap()
path='/api/v1/chats/'+chat['id']
results={'contract_extra':{}}
# Full UTF-8 password range, including a colon; malformed JSON and invalid limits.
unicode_name='utf_'+uuid.uuid4().hex[:16]
unicode_password='🔑'*120+':пароль!'
check(len(unicode_password)==128,'password fixture length')
c.call('POST','/api/v1/users',201,body={'username':unicode_name,'display_name':'UTF-8','password':unicode_password},schema='User')
credential=base64.b64encode((unicode_name+':'+unicode_password).encode()).decode()
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')
c.call('POST','/api/v1/users',400,raw=b'{',headers={'Content-Type':'application/json'})
c.call('GET',path+'/messages?limit='+('9'*100),400,actor=a)
results['contract_extra']['utf8_128_password_with_colon']=True
print('PASS: 128-codepoint UTF-8 password with colon; malformed JSON and oversized limit rejected')
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
import sys,os,platform,json,subprocess,datetime
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parent))
from experiments import command,dc,save
info={'collected_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'host':platform.platform(),'machine':platform.machine(),'logical_cpus':os.cpu_count(),'host_memory_bytes':int(command(['sysctl','-n','hw.memsize']).strip()),'host_cpu':command(['sysctl','-n','machdep.cpu.brand_string']).strip(),'docker_version':command(['docker','version','--format','{{json .Server}}']).strip(),'compose_version':dc('version').strip(),'docker_resources':json.loads(command(['docker','info','--format','{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"os":"{{.OperatingSystem}}","architecture":"{{.Architecture}}"}']))}
info['dataset']=json.loads(dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',"SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'messages',(SELECT count(*) FROM messages),'idempotency',(SELECT count(*) FROM idempotency),'database_bytes',pg_database_size(current_database()))"))
info['versions']={'python':command(['docker','exec',dc('ps','-q','api').split()[0],'python','--version']).strip(),'postgres':dc('exec','-T','postgres','postgres','--version').strip(),'redis':dc('exec','-T','redis','redis-server','--version').strip(),'haproxy':dc('exec','-T','lb','haproxy','-v').strip()}
# Hash inputs so measurements can be tied to saved sources without publishing secrets.
import hashlib
info['source_sha256']={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for pattern in ('app/*.py','migrations/*.sql','infra/*.cfg','scripts/experiments.py','compose.yaml','Dockerfile','requirements.lock') for p in Path('.').glob(pattern)}
save(sys.argv[1] if len(sys.argv)>1 else 'environment.json',info)
print('Sanitized environment and source hashes saved.')
+225
View File
@@ -0,0 +1,225 @@
#!/usr/bin/env python3
"""Reproducible real-container experiments. Only synthetic data; no tokens on disk."""
import sys,os,json,time,subprocess,statistics,threading,math,uuid
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
ROOT=Path(__file__).resolve().parents[1]
os.chdir(ROOT)
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
OUT=ROOT/'evidence'; OUT.mkdir(exist_ok=True)
def command(args,env=None):
proc=subprocess.Popen(args,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
waited=0
try:
while True:
try:
output,_=proc.communicate(timeout=15)
break
except subprocess.TimeoutExpired:
waited+=15
print(' Ожидание: '+' '.join(args[:3])+'… ('+str(waited)+' с)',flush=True)
except KeyboardInterrupt:
proc.terminate()
try: proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
proc.kill(); proc.communicate()
raise
if proc.returncode: raise RuntimeError('Command failed: '+str(args)+'\n'+output)
return output
def dc(*args,env=None): return command(['docker','compose',*args],env)
def save(name,data): (OUT/name).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
def inventory():
ids=dc('ps','-q').split()
return [json.loads(line) for line in command(['docker','inspect','--format','{"id":"{{.Id}}","name":"{{.Name}}","hostname":"{{.Config.Hostname}}","state":"{{.State.Status}}","image":"{{.Config.Image}}","nano_cpus":{{.HostConfig.NanoCpus}},"memory":{{.HostConfig.Memory}},"published_ports":{{json .HostConfig.PortBindings}}}',*ids]).splitlines()]
def up_wait(env=None,replicas=None):
print('Подготовка стенда из локальных образов, ожидание готовности (до 90 с)…',flush=True)
args=['up','-d','--no-build','--pull','never','--wait','--wait-timeout','90']
if replicas is not None: args+=['--scale','api='+str(replicas)]
try: dc(*args,env=env)
except RuntimeError as exc:
# A recreated DB invalidates existing pool connections. Compose may fail
# immediately on an old 'unhealthy' status; restart API pools, then wait.
if 'unhealthy' not in str(exc): raise
dc('restart','api',env=env)
dc(*args,env=env)
time.sleep(3)
def restore(): up_wait()
def sample_stats(stop,rows):
while not stop.is_set():
try:
rows.append({'at':time.time(),'containers':[json.loads(x) for x in dc('stats','--no-stream','--format','{{json .}}').splitlines()]})
except Exception: pass
stop.wait(.5)
def benchmark(duration=10,concurrency=16,action=None):
c=Client(); a,b,e,chat=c.bootstrap()
# Explicit warm-up, excluded from measured interval.
for i in range(50): c.message(a,chat,'warmup-'+str(i))
barrier=threading.Barrier(concurrency+1,action=lambda: started.__setitem__(0,time.monotonic())); lat=[]; errors=[]; observed=set(); confirmed=set(); lock=threading.Lock()
started=[0]; stats=[]; stop=threading.Event()
sampler=threading.Thread(target=sample_stats,args=(stop,stats)); sampler.start()
action_result={}
def run_action():
time.sleep(2)
try: action_result['output']=action(); action_result['ok']=True
except Exception as exc: action_result.update(ok=False,error=str(exc))
action_result['finished_seconds']=time.monotonic()-started[0]
def worker(n):
local=Client(timeout=6); barrier.wait(); index=0
while time.monotonic()-started[0]<duration:
begin=time.monotonic()
try:
response=local.message(a,chat,'load-%s-%s'%(n,index))
# Each worker also reads periodically during failures/updates.
if index%10==0: local.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=1',actor=b,schema='MessagePage')
with lock:
lat.append((time.monotonic()-begin)*1000); observed.add(response['headers']['X-Instance-Id']); confirmed.add(response['json']['id'])
except Failure as exc:
with lock: errors.append({'at_seconds':round(begin-started[0],4),'error':str(exc)})
index+=1
with ThreadPoolExecutor(max_workers=concurrency) as pool:
jobs=[pool.submit(worker,n) for n in range(concurrency)]
started[0]=time.monotonic(); barrier.wait()
thread=threading.Thread(target=run_action) if action else None
if thread: thread.start()
for job in jobs: job.result()
elapsed=time.monotonic()-started[0]
if thread: thread.join()
stop.set(); sampler.join()
lat.sort()
def pct(p): return round(lat[max(0,math.ceil(p*len(lat))-1)],3) if lat else None
result={'duration':duration,'elapsed':round(elapsed,3),'concurrency':concurrency,'success':len(lat),'errors':len(errors),'rps':round(len(lat)/elapsed,3),'p50_ms':pct(.5),'p95_ms':pct(.95),'p99_ms':pct(.99),'instances':sorted(observed),'error_details':errors,'stats':stats,'action':action_result,'warmup_messages':50}
check(bool(lat),'no successes')
if action:
check(action_result.get('ok'),'action failed')
from resilience import history
stored=history(c,b,chat)
check(confirmed.issubset({item['id'] for item in stored}),'confirmed message lost during action')
check(len(stored)==len({item['id'] for item in stored}),'duplicate IDs')
result['confirmed_messages_verified']=len(confirmed)
return result
def correctness():
print('Проверки займут несколько минут. Результаты сохраняются в evidence/.',flush=True)
restore()
print('[1/6] Публичные smoke и проверка структуры',flush=True)
# Preserve raw stdout from unmodified public tests.
(OUT/'smoke.txt').write_text(command(['make','test']))
(OUT/'check.txt').write_text(command(['make','check']))
before=inventory(); save('containers-initial.json',before)
print('[2/6] 24 конкурентных повтора одного сообщения',flush=True)
c=Client(); a,b,e,chat=c.bootstrap(); path='/api/v1/chats/'+chat['id']+'/messages'
key=uuid.uuid4().hex; gate=threading.Barrier(24)
def repeat(i):
local=Client(); gate.wait()
return local.message(a,chat,'parallel-idempotency',key=key,attachments=[] if i%2 else None)
with ThreadPoolExecutor(max_workers=24) as pool: replies=list(pool.map(repeat,range(24)))
check(len({r['json']['id'] for r in replies})==1,'duplicate idempotency effects')
instances=sorted({r['headers']['X-Instance-Id'] for r in replies}); check(len(instances)>=2,'parallel replay missed replicas')
items=c.call('GET',path,actor=b,schema='MessagePage')['json']['items']; check(len(items)==1,'duplicate stored messages')
c.call('POST',path,409,actor=a,body={'text':'different'},headers={'Idempotency-Key':key})
save('idempotency.json',{'concurrent_requests':24,'instances':instances,'distinct_message_ids':1,'stored_messages':len(items),'different_body_status':409,'absent_vs_empty_attachments':'equal'})
# Public test chooses target from the response: rotate serving order until each physical container was stopped.
print('[3/6] Отказ каждой API по очереди (15 с на попытку)',flush=True)
seen=set(); attempts=[]
for attempt in range(8):
restore()
if attempt%2: Client().call('GET','/health/live',schema='Health') # rotate round-robin before target selection
print(' Попытка '+str(attempt+1),flush=True)
output=command(['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh'])
stopped=dc('ps','-a','--format','json')
states=[json.loads(line) for line in stopped.splitlines() if line.strip()]
targets=[r['Name'] for r in states if r['Service']=='api' and r['State']=='exited']
seen.update(targets)
attempts.append({'attempt':attempt+1,'stdout':output,'stopped':targets,'inventory_after':[{'name':r['Name'],'state':r['State'],'id':r['ID']} for r in states]})
save('failover.json',attempts)
if len(seen)>=2: break
check(len(seen)>=2,'did not stop each API replica')
restore()
print('[4/6] Перезапуск стенда с сохранением данных и сессии',flush=True)
(OUT/'persistence.txt').write_text(command(['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh']))
save('containers-after-restart.json',inventory())
print('[5/6] Последовательная замена контейнеров под нагрузкой (35 с)',flush=True)
save('rolling.json',benchmark(35,16,lambda:command(['sh','scripts/rolling-update.sh'])))
save('containers-after-rolling.json',inventory())
restore()
print('[6/6] Остановка каждой API под нагрузкой (15 с на реплику)',flush=True)
availability=[]
for item in inventory():
if '-api-' not in item['name']: continue
target=item['hostname']+'-selected'
def action(target=target):
return command(['sh','scripts/stop-one.sh'],dict(os.environ,TARGET_INSTANCE_ID=target))
row=benchmark(15,16,action); row['target_container']=item['name']
availability.append(row); save('availability-load.json',availability)
restore()
print('Correctness, each-replica failure, persistence and rolling: PASS',flush=True)
def configure(n,cpu,memory,pool=8,fast=1,db_cpu=1):
env=dict(os.environ,DB_CPUS=str(db_cpu),API_REPLICAS=str(n),API_CPUS=str(cpu),API_MEMORY=memory,POOL_MAX=str(pool),MESSAGE_ACCESS_FAST=str(fast))
up_wait(env,n)
return env
def scaling():
results=[]
for mode in ('fixed','growing'):
for n in (1,2,4):
cpu=1/n if mode=='fixed' else .5
mem=str(1024//n if mode=='fixed' else 256)+'m'
configure(n,cpu,mem)
for repeat in range(1,4):
row=benchmark(10,32); row.update(series=mode,replicas=n,cpu_per_api=cpu,memory_per_api=mem,repeat=repeat,pool=8)
results.append(row); save('scaling.json',results)
print(mode,n,repeat,row['rps'],row['errors'],flush=True)
sweeps=[]
configure(4,.5,'256m')
for concurrency in (1,4,16,64,128):
row=benchmark(10,concurrency); row.update(replicas=4)
sweeps.append(row); save('saturation.json',sweeps)
print('saturation',concurrency,row['rps'],row['p95_ms'],flush=True)
improvements=[]
for fast in (0,1):
configure(4,.5,'256m',fast=fast)
for repeat in range(1,4):
row=benchmark(10,32); row.update(fast_membership=bool(fast),repeat=repeat)
improvements.append(row); save('improvement.json',improvements)
print('improvement',fast,repeat,row['rps'],flush=True)
configure(2,.5,'256m')
save('containers-final.json',inventory())
def improvement_low():
rows=[]
# Alternate A/B ordering to reduce monotonic database growth/temperature bias.
for repeat in (1,2,3):
for fast in ((0,1) if repeat%2 else (1,0)):
configure(4,.5,'256m',fast=fast)
row=benchmark(10,4); row.update(fast_membership=bool(fast),repeat=repeat)
rows.append(row); save('improvement-low.json',rows)
print('improvement C4',fast,repeat,row['rps'],flush=True)
configure(2,.5,'256m')
def bottleneck():
results=[]
for db_cpu in (.1,1):
for n in (1,2,4):
configure(n,.5,'256m',db_cpu=db_cpu)
for repeat in (1,2):
row=benchmark(10,4)
row.update(db_cpu=db_cpu,replicas=n,repeat=repeat)
results.append(row); save('db-bottleneck.json',results)
print('db',db_cpu,n,repeat,row['rps'],row['p95_ms'],flush=True)
configure(2,.5,'256m')
if __name__=='__main__':
try:
mode=sys.argv[1] if len(sys.argv)>1 else 'correctness'
actions={'correctness':correctness,'scaling':scaling,'bottleneck':bottleneck,'improvement-low':improvement_low}
if mode not in actions: raise SystemExit('Unknown experiment: '+mode)
actions[mode]()
except KeyboardInterrupt:
print('\nПроверка прервана. Для восстановления стенда выполните:\n'
'docker compose up -d --no-build --pull never --wait --wait-timeout 120',flush=True)
raise SystemExit(130) from None
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
import sys,os,time,json,base64,uuid
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parent))
from experiments import dc,save,restore,Client,Failure,check,command
results={}
# Retain previous lab's strict validation and Unicode password range.
results['contract_extra']=command([sys.executable,'scripts/contract_extra.py']).strip()
c=Client(); a,b,e,chat=c.bootstrap(); path='/api/v1/chats/'+chat['id']+'/messages'
for key in ('bad key','x'*129,'ü'):
# HTTP headers must be latin-1 encodable.
c.call('POST',path,400,actor=a,body={'text':'invalid key'},headers={'Idempotency-Key':key})
for payload in ({'text':'ok','sender_id':a['id']},{'text':True},{'text':'x','attachment_ids':False},{'text':'x','attachment_ids':{}}):
c.call('POST',path,400,actor=a,body=payload,headers={'Idempotency-Key':uuid.uuid4().hex})
results['strict_message_validation']='PASS'
# Same key belongs independently to each authenticated sender and chat.
key=uuid.uuid4().hex
m1=c.message(a,chat,'scoped',key)['json']; m2=c.message(b,chat,'scoped',key)['json']
chat2=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'scope','member_ids':[a['id']]},schema='Chat')['json']
m3=c.message(a,chat2,'scoped',key)['json']
check(len({m['id'] for m in (m1,m2,m3)})==3,'key scope too broad')
results['key_scope']='PASS: 3 independent messages'
canonical=c.call('POST',path,201,actor=a,body={'attachment_ids':[],'text':'scoped'},headers={'Idempotency-Key':key},schema='Message')['json']
check(canonical==m1,'JSON key order changed replay')
results['canonical_json_order']='PASS: reversed fields and explicit [] replay the same message'
from urllib.parse import quote
page=c.call('GET',path+'?limit=1',actor=a,schema='MessagePage')['json']
check(page['next_cursor'] is not None,'cursor fixture missing')
c.call('GET','/api/v1/chats/'+chat2['id']+'/messages?cursor='+quote(page['next_cursor'],safe=''),400,actor=a)
results['cursor_scope']='PASS: cursor from another chat rejected with 400'
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a)
for _ in range(16): c.call('POST',path,401,actor=a,body={'text':'scoped'},headers={'Idempotency-Key':key})
results['revoked_session_cannot_replay']='PASS'
# Explicit replay across a real process stop, with the original key and token.
key=uuid.uuid4().hex
first=c.message(b,chat,'replay after physical stop',key)
target=first['headers']['X-Instance-Id']; started=time.monotonic()
hook=command(['sh','scripts/stop-one.sh'],dict(os.environ,TARGET_INSTANCE_ID=target))
while True:
try:
replay=c.message(b,chat,'replay after physical stop',key)
break
except Failure:
check(time.monotonic()-started<10,'cross-failover replay did not recover')
time.sleep(.2)
check(first['json']==replay['json'],'replay changed after physical stop')
check(target!=replay['headers']['X-Instance-Id'],'stopped instance still serves replay')
save('idempotency-failover.json',{'original_instance':target,'replay_instance':replay['headers']['X-Instance-Id'],'same_message':True,'status':replay['status'],'seconds':round(time.monotonic()-started,3),'hook':hook})
results['same_key_after_physical_failover']='PASS: same Message and 201 via a different process with original token'
restore()
dc('stop','redis')
try:
c.call('GET','/api/v1/users/me',actor=b,schema='User'); c.call('GET','/health/ready',schema='Health')
results['redis_outage']='PASS: profile falls back to PostgreSQL, ready=200'
finally: dc('start','redis')
dc('stop','postgres')
try:
probe = "import urllib.request,urllib.error;\nfor path in ('live','ready'):\n try: r=urllib.request.urlopen('http://localhost:8080/health/'+path,timeout=8); print(path,r.status)\n except urllib.error.HTTPError as e: print(path,e.code)"
output=command(['docker','exec',dc('ps','-q','api').split()[0],'python','-c',probe])
check('live 200' in output and 'ready 503' in output,'health dependency semantics')
results['postgres_outage']=output.strip()+'; no DB failover claimed'
finally: restore()
env=dict(os.environ,SESSION_TTL_SECONDS='2')
dc('up','-d','--wait','--wait-timeout','90',env=env); time.sleep(3)
c=Client(); a=c.user('ttl'); time.sleep(2.2)
c.call('GET','/api/v1/users/me',401,actor=a)
results['expiry']='PASS: TTL=2 seconds, old token gives 401'
restore()
save('extra-checks.json',results)
print(json.dumps(results,ensure_ascii=False,indent=2))
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Audit schema migrations and final infrastructure without exposing credentials."""
import sys,json
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parent))
from experiments import dc,command,save,inventory,restore
restore()
query='SELECT version,applied_at FROM schema_migrations ORDER BY version'
before=dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',query)
dc('run','--rm','migrate');dc('run','--rm','migrate')
after=dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',query)
assert before==after,'migration was applied twice'
Path('evidence/migrations.txt').write_text('Command: docker compose run --rm migrate (twice)\nBefore == after (including applied_at): PASS\n'+after)
items=inventory();apis=[r for r in items if '-api-' in r['name']]
assert len(apis)==2
assert all(not r['published_ports'] for r in apis)
assert all(r['nano_cpus']==500000000 and r['memory']==268435456 for r in apis)
save('containers-final.json',items)
command([sys.executable,'scripts/environment.py','environment-final.json'])
print('PASS: two private APIs, expected limits, migrations applied once, source hashes saved.')
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Plot saved measurements only; never fabricates or reruns data."""
import os
os.environ.setdefault('MPLCONFIGDIR','/tmp/mtusi-lab3-matplotlib')
import json,statistics,csv
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT=Path(__file__).resolve().parents[1]; E=ROOT/'evidence'
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,'axes.spines.right':False})
def read(name): return json.loads((E/name).read_text())
def grouped(rows,key,value):
keys=sorted({r[key] for r in rows})
vals=[[r[value] for r in rows if r[key]==k] for k in keys]
return keys,[statistics.mean(v) for v in vals],[statistics.stdev(v) if len(v)>1 else 0 for v in vals]
def finish(fig,name):
fig.tight_layout(); fig.savefig(E/(name+'.png'),dpi=180); fig.savefig(E/(name+'.svg')); plt.close(fig)
rows=read('scaling.json')
fig,axes=plt.subplots(1,2,figsize=(11,4))
for mode,label,color in [('fixed','Всего 1 CPU / 1 GiB','#2563eb'),('growing','0.5 CPU / 256 MiB на API','#ea580c')]:
group=[r for r in rows if r['series']==mode]
for ax,metric in zip(axes,['rps','p95_ms']):
x,y,err=grouped(group,'replicas',metric); ax.errorbar(x,y,yerr=err,marker='o',capsize=4,label=label,color=color)
for ax in axes: ax.set_xlabel('API-реплики'); ax.set_xticks([1,2,4]); ax.grid(alpha=.2)
axes[0].set_ylabel('Успешные итерации / с'); axes[1].set_ylabel('p95, мс'); axes[0].legend(fontsize=8)
fig.suptitle('Масштабирование: C=32, три повтора, ± выборочное σ')
finish(fig,'scaling')
rows=read('saturation.json'); fig,axes=plt.subplots(1,2,figsize=(11,4))
for ax,metric,label in zip(axes,['rps','p95_ms'],['Успешные итерации / с','p95, мс']):
ax.plot([r['concurrency'] for r in rows],[r[metric] for r in rows],marker='o',color='#2563eb'); ax.set_xlabel('Concurrency'); ax.set_ylabel(label); ax.set_xscale('log',base=2); ax.set_xticks([1,4,16,64,128],labels=['1','4','16','64','128']); ax.grid(alpha=.2)
fig.suptitle('Рост очередей: 4 API × 0.5 CPU / 256 MiB, PostgreSQL 1 CPU')
finish(fig,'saturation')
fig,axes=plt.subplots(1,2,figsize=(11,4))
for ax,name,c in zip(axes,['improvement.json','improvement-low.json'],[32,4]):
rows=read(name)
x,y,err=grouped(rows,'fast_membership','rps')
ax.bar(['Полный Chat','Только членство'],y,yerr=err,capsize=5,color=['#94a3b8','#16a34a'])
ax.set_ylabel('Успешные итерации / с'); ax.set_title(f'Concurrency {c}'); ax.grid(axis='y',alpha=.2)
for i,v in enumerate(y): ax.text(i,v+max(err)+5,f'{v:.1f}',ha='center')
fig.suptitle('A/B: один SELECT вместо двух, 4 API, три повтора')
finish(fig,'improvement')
rows=read('db-bottleneck.json'); fig,axes=plt.subplots(1,2,figsize=(11,4))
for db,color in [(.1,'#dc2626'),(1,'#16a34a')]:
group=[r for r in rows if r['db_cpu']==db]
for ax,metric in zip(axes,['rps','p95_ms']):
x,y,err=grouped(group,'replicas',metric); ax.errorbar(x,y,yerr=err,marker='o',capsize=4,label=f'PostgreSQL: {db} CPU',color=color)
for ax in axes: ax.set_xlabel('API-реплики (0.5 CPU / 256 MiB каждая)'); ax.set_xticks([1,2,4]); ax.grid(alpha=.2)
axes[0].set_ylabel('Успешные итерации / с'); axes[1].set_ylabel('p95, мс'); axes[0].legend()
fig.suptitle('Контролируемый предел общей БД: C=4, два повтора')
finish(fig,'db-bottleneck')
# Compact raw per-run table alongside the full JSON including container resource samples.
with (E/'measurements.csv').open('w') as f:
fields=['experiment','series','replicas','db_cpu','fast_membership','repeat','concurrency','elapsed','success','errors','rps','p50_ms','p95_ms','p99_ms']
writer=csv.DictWriter(f,fieldnames=fields,extrasaction='ignore'); writer.writeheader()
for name in ['scaling','saturation','improvement','improvement-low','db-bottleneck']:
for row in read(name+'.json'): writer.writerow(dict(row,experiment=name))
print('Four plots and raw per-run CSV generated from evidence JSON.')
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Recreate real containers, retain PostgreSQL volume. No migration race.
docker compose down
docker compose up -d --no-build --pull never --wait --wait-timeout 90
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# First build the new image and apply compatible migrations once:
# docker compose build api; docker compose run --rm migrate
# One surge container, wait readiness, remove one old container, repeat.
# The old IDs are captured before creating replacements.
old_ids=$(docker compose ps -q api)
count=$(printf '%s\n' "$old_ids" | wc -l | tr -d ' ')
[ "$count" -ge 2 ] || { echo 'At least two APIs required' >&2; exit 1; }
for old in $old_ids; do
docker compose up -d --no-build --pull never --no-deps --no-recreate --scale "api=$((count + 1))" api
for id in $(docker compose ps -q api); do
python3 scripts/wait-container.py "$id"
done
docker stop --time 5 "$old"
docker rm "$old"
done
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/bootstrap.py
docker compose config --quiet
docker compose up -d --build --wait --wait-timeout 120
make check
make validate PYTHON=.venv/bin/python
python3 scripts/experiments.py scaling
python3 scripts/environment.py environment-before-db.json
python3 scripts/experiments.py bottleneck
python3 scripts/experiments.py improvement-low
python3 scripts/experiments.py correctness
python3 scripts/extra-checks.py
python3 scripts/final-audit.py
.venv/bin/python scripts/plots.py
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?Set TARGET_INSTANCE_ID from a real API response}"
for id in $(docker compose ps -q api); do
host=$(docker inspect -f '{{.Config.Hostname}}' "$id")
case "$TARGET_INSTANCE_ID" in
"$host"-*)
printf 'Stopping API container %s (hostname %s)\n' "$id" "$host"
docker stop --time 5 "$id"
docker inspect -f '{{.Id}} {{.State.Status}}' "$id"
exit 0;;
esac
done
printf 'No running API matches target\n' >&2
exit 1
+7
View File
@@ -0,0 +1,7 @@
import subprocess,sys,time
for _ in range(90):
if subprocess.check_output(['docker','inspect','-f','{{.State.Health.Status}}',sys.argv[1]],text=True).strip()=='healthy':
time.sleep(2) # allow HAProxy rise check and DNS refresh
break
time.sleep(1)
else: raise SystemExit('container did not become ready')