Files
mtusi2026lab3/student-tests/scenarios.py
T

217 lines
9.9 KiB
Python

#!/usr/bin/env python3
"""Black-box synthetic tests and measured fault experiments; no credentials saved."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import importlib.util
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
from urllib.parse import quote
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure
from resilience import history
COMPOSE = [str(ROOT / 'scripts/compose.sh')]
BASE = os.getenv('BASE_URL', 'http://localhost:8080')
def cmd(*args):
return subprocess.check_output(args, cwd=ROOT, text=True, stderr=subprocess.DEVNULL).strip()
def ids():
return cmd(*COMPOSE, 'ps', '-q', 'api').splitlines()
def alias(container):
return cmd('docker', 'exec', container, 'python', '-c',
'import urllib.request; r=urllib.request.urlopen("http://127.0.0.1:8080/health/ready",timeout=2); print(r.headers["X-Instance-Id"])')
def wait_two(c, actor):
deadline = time.monotonic()+45
seen = set()
while time.monotonic()<deadline:
try:
for container in ids():
alias(container)
seen.add(c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['headers']['X-Instance-Id'])
if len(ids())==2 and len(seen)>=2:
return sorted(seen)
except Exception:
pass
time.sleep(.2)
raise AssertionError('Two ready API processes not observed through LB')
def idempotency():
c = Client(BASE)
alice, bob, eve, chat = c.bootstrap()
observed = wait_two(c, alice)
key = uuid.uuid4().hex
barrier = threading.Barrier(24)
def repeat(_):
local = Client(BASE)
barrier.wait()
return local.message(alice, chat, 'parallel synthetic', key)
with ThreadPoolExecutor(max_workers=24) as pool:
results = list(pool.map(repeat, range(24)))
message = results[0]['json']
assert all(r['json']==message and r['status']==201 for r in results)
parallel_instances = sorted({r['headers']['X-Instance-Id'] for r in results})
assert len(parallel_instances)==2
assert c.message(alice, chat, 'parallel synthetic', key)['json']==message
path = '/api/v1/chats/'+chat['id']+'/messages'
c.call('POST', path, 409, actor=alice, body={'text':'changed'}, headers={'Idempotency-Key':key})
for invalid in ('', 'space key', 'a'*129, 'invalid!' ):
c.call('POST', path, 400, actor=alice, body={'text':'invalid'}, headers={'Idempotency-Key':invalid})
c.call('POST', path, 400, actor=alice, body={'text':'missing'})
c.call('POST', path, 404, actor=eve, body={'text':'parallel synthetic'}, headers={'Idempotency-Key':key})
bob_message = c.message(bob, chat, 'parallel synthetic', key)['json']
assert bob_message['id'] != message['id']
other_chat = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Other scope','member_ids':[alice['id']]},schema='Chat')['json']
assert c.message(alice, other_chat, 'parallel synthetic', key)['json']['id']!=message['id']
# Simulate age >24h without changing application/host clock.
cmd(*COMPOSE, 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c',
"UPDATE message_requests SET created_at=NOW()-INTERVAL '25 hours' WHERE key='"+key+"'")
assert c.message(alice, chat, 'parallel synthetic', key)['json']==message
reader_instances=set()
for _ in range(12):
page=c.call('GET',path,actor=bob,schema='MessagePage')
assert message in page['json']['items']
assert sum(m['id']==message['id'] for m in page['json']['items'])==1
reader_instances.add(page['headers']['X-Instance-Id'])
assert len(reader_instances)==2
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('POST',path,401,actor=alice,body={'text':'parallel synthetic'},headers={'Idempotency-Key':key})
return {'result':'PASS','parallel_requests':24,'parallel_instances':parallel_instances,
'session_instances':observed,'reader_instances':sorted(reader_instances),
'same_message':True,'history_copies':1,'different_body':409,
'scope_user_and_chat':'PASS','aged_25h_replay':'PASS','revoked_replay':401,'outsider_replay':404}
def experiment(mode, target_index, duration):
c = Client(BASE, timeout=2)
alice, bob, eve, chat = c.bootstrap()
instances = wait_two(c, alice)
before=c.message(alice,chat,'confirmed before experiment')['json']
containers=sorted(ids())
target=containers[target_index]
target_alias=alias(target)
samples=[]
lock=threading.Lock()
ready=threading.Barrier(5)
start=time.monotonic()
stop_event=threading.Event()
resources=[]
def sample_resources():
while not stop_event.is_set():
try:
running=cmd(*COMPOSE,'ps','-q').splitlines()
lines=cmd('docker','stats','--no-stream','--format','{{json .}}',*running)
resources.append({'offset_seconds':round(time.monotonic()-start,3),
'containers':[json.loads(x) for x in lines.splitlines()]})
except Exception:
pass
stop_event.wait(1)
def worker(i):
local=Client(BASE,timeout=2)
ready.wait()
while not stop_event.is_set() and time.monotonic()-start < 120:
key=uuid.uuid4().hex
text='experiment-'+key
t=time.monotonic()
try:
result=local.message(alice,chat,text,key)
message=result['json']
ok=True
except Failure:
message=None
ok=False
done=time.monotonic()
with lock:
samples.append((t,done,ok,message))
sampler=threading.Thread(target=sample_resources)
sampler.start()
with ThreadPoolExecutor(max_workers=4) as pool:
futures=[pool.submit(worker,i) for i in range(4)]
ready.wait()
start=time.monotonic()
time.sleep(2) # measured pre-fault warm section
action_started=time.monotonic()
if mode=='failover':
env=dict(os.environ,TARGET_INSTANCE_ID=target_alias)
hook=subprocess.run([str(ROOT/'scripts/stop-one.sh')],env=env,capture_output=True,text=True,check=True)
action_events={'target_container':target,'target_instance':target_alias,'hook_output':hook.stdout.strip()}
inspect=json.loads(cmd('docker','inspect',target))[0]
assert inspect['State']['Running'] is False
assert len(ids())==1
action_events['target_running_after_hook']=False
action_finished=time.monotonic()
while time.monotonic()-start<duration:
time.sleep(.1)
else:
spec=importlib.util.spec_from_file_location('rolling',ROOT/'scripts/rolling-update.py')
mod=importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
action_events={'replacements':mod.rolling_update()}
action_finished=time.monotonic()
time.sleep(3)
stop_event.set()
for future in futures:
future.result()
sampler.join()
elapsed=time.monotonic()-start
successes=[s for s in samples if s[2]]
errors=len(samples)-len(successes)
confirmed=[s[3] for s in successes]+[before]
# Read all pages with the original session, verify every acknowledged object.
actual=history(c,bob,chat)
actual_by_id={m['id']:m for m in actual}
assert all(actual_by_id.get(m['id'])==m for m in confirmed)
assert len(actual)==len(actual_by_id)
assert len({m['text'] for m in actual})==len(actual)
after=[s for s in successes if s[0]>=action_finished]
assert after
recovery=after[0][1]-action_started
if mode=='failover':
assert recovery<=10
lat=sorted((s[1]-s[0])*1000 for s in successes)
pct=lambda p:round(lat[max(0,math.ceil(len(lat)*p)-1)],3)
report={'mode':mode,'result':'PASS','instances_before':instances,'duration_seconds':round(elapsed,3),
'concurrency':4,'successful_requests':len(successes),'errors':errors,
'error_ratio':round(errors/len(samples),6),'successful_rps':round(len(successes)/elapsed,3),
'successful_latency_ms':{'p50':pct(.5),'p95':pct(.95),'p99':pct(.99)},
'first_success_after_action_seconds':round(recovery,3),
'action_duration_seconds':round(action_finished-action_started,3),
'successful_requests_started_during_action':sum(action_started <= s[0] <= action_finished for s in successes),
'max_gap_between_successful_writes_seconds':round(max(b[1]-a[1] for a,b in zip(sorted(successes,key=lambda s:s[1]), sorted(successes,key=lambda s:s[1])[1:])),3),
'confirmed_checked':len(confirmed),'lost_confirmed':0,'read_write_original_session':'PASS',
'action':action_events,'resources':resources,
'method':'4 closed-loop writers through LB; errors counted, no retry; full history after action. Recovery includes hook duration and next fresh write.'}
if mode=='failover':
cmd(str(ROOT/'scripts/restore.sh'))
report['instances_after_restore']=wait_two(c,alice)
return report
if __name__=='__main__':
parser=argparse.ArgumentParser()
parser.add_argument('mode',choices=['idempotency','failover','rolling'])
parser.add_argument('--target-index',type=int,default=0,choices=[0,1])
parser.add_argument('--duration',type=float,default=15)
parser.add_argument('--output',required=True)
args=parser.parse_args()
report=idempotency() if args.mode=='idempotency' else experiment(args.mode,args.target_index,args.duration)
report['recorded_at_utc']=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()
Path(args.output).write_text(json.dumps(report,indent=2,ensure_ascii=False)+'\n')
print(json.dumps({k:v for k,v in report.items() if k!='resources'},indent=2,ensure_ascii=False))