Files
mtusi2026lab2/student-tests/lab2/budgets.py

120 lines
9.1 KiB
Python

#!/usr/bin/env python3
"""Bounded closed-loop HTTP latency matrix. Tokens stay only in memory."""
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import importlib.util
import json
import os
from pathlib import Path
import re
import sys
import threading
import time
import uuid
ROOT=Path(__file__).resolve().parents[2]
sys.path[:0]=[str(ROOT/'tests'),str(ROOT/'student-tests'),str(ROOT/'student-tests/lab2')]
from client import Client,Failure
from auth_contract import basic
from resources import Sampler
spec=importlib.util.spec_from_file_location('budget_harness',ROOT/'student-tests/lab2/run.py')
harness=importlib.util.module_from_spec(spec);spec.loader.exec_module(harness)
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--base-url',required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--repeats',type=int,default=2);p.add_argument('--per-worker',type=int,default=3)
p.add_argument('--history',type=int,default=1000);p.add_argument('--client-timeout',type=float,default=15)
a=p.parse_args()
if not 2<=a.repeats<=3 or not 2<=a.per_worker<=10 or not 1000<=a.history<=10000:p.error('bounded profile: repeats 2..3, per-worker 2..10, history 1000..10000')
a.output.mkdir(parents=True,exist_ok=False)
factory=lambda:Client(a.base_url,timeout=a.client_timeout)
c=factory();actors=[c.user('bud'+uuid.uuid4().hex[:4]) for _ in range(10)]
chat=c.call('POST','/api/v1/chats',201,actor=actors[0],body={'title':'Budget history','member_ids':[x['id'] for x in actors]},schema='Chat')['json']
for index in range(a.history):c.message(actors[0],chat,'history fixture '+str(index)+' '+('x'*100))
cursor=None
traversed=set()
for _ in range((a.history*8//10)//100):
path='/api/v1/chats/'+chat['id']+'/messages?limit=100'+('&cursor='+cursor if cursor else '')
page=c.call('GET',path,actor=actors[0],schema='MessagePage')['json']
ids={m['id'] for m in page['items']}
if traversed & ids:raise RuntimeError('deep fixture repeated a page')
traversed.update(ids);cursor=page['next_cursor']
if not cursor or len(traversed)!=((a.history*8//10)//100)*100:raise RuntimeError('deep-page fixture lacks correct cursor position')
path='/api/v1/chats/'+chat['id']+'/messages'
names=['registration','login','me','create_chat','send_message','history_first','history_deep','logout']
samples=[];phases=[];resource_errors={};resources={}
samplers={}
config=json.loads(os.environ.get('LAB2_RESOURCE_CONTAINERS','{}'))
for role,entry in config.items():
sampler=Sampler(entry['name'],1.0);samplers[role]=(sampler,entry['cpus']);sampler.thread.start()
began=time.monotonic()
try:
for concurrency in [1,5,10]:
# Logout credentials are prepared before measuring the logout phase;
# preparation latency is not misreported as logout throughput.
logout_tokens=[[] for _ in range(concurrency)]
for worker in range(concurrency):
actor=actors[worker]
for _ in range(1+a.repeats*a.per_worker):
session=c.call('POST','/api/v1/auth/sessions',201,headers=basic(actor['registration']['username'],actor['registration']['password']),schema='Session')['json']
logout_tokens[worker].append(session['token'])
for operation in names:
for repeat in range(0,a.repeats+1):
count=1 if repeat==0 else a.per_worker
barrier=threading.Barrier(concurrency)
phase_clients=[factory() for _ in range(concurrency)]
def worker(number):
local=phase_clients[number];actor=actors[number];records=[];barrier.wait(timeout=30)
for request in range(count):
start=time.monotonic();status=None;kind=None
try:
if operation=='registration':result=local.call('POST','/api/v1/users',201,body={'username':'budget_'+uuid.uuid4().hex[:20],'display_name':'Budget fixture','password':'Synthetic:password-for-measurement'},schema='User')
elif operation=='login':result=local.call('POST','/api/v1/auth/sessions',201,headers=basic(actor['registration']['username'],actor['registration']['password']),schema='Session')
elif operation=='me':result=local.call('GET','/api/v1/users/me',actor=actor,schema='User')
elif operation=='create_chat':result=local.call('POST','/api/v1/chats',201,actor=actor,body={'title':'Unique '+uuid.uuid4().hex,'member_ids':[actor['id']]},schema='Chat')
elif operation=='send_message':result=local.message(actor,chat,'Synthetic '+uuid.uuid4().hex+' '+('x'*80))
elif operation=='history_first':result=local.call('GET',path+'?limit=50',actor=actor,schema='MessagePage')
elif operation=='history_deep':result=local.call('GET',path+'?limit=50&cursor='+cursor,actor=actor,schema='MessagePage')
else:result=local.call('DELETE','/api/v1/auth/sessions/current',204,actor=dict(actor,token=logout_tokens[number].pop()))
status=result['status']
except TimeoutError:kind='client_timeout'
except Failure as exc:
message=str(exc);match=re.search(r'received (\d+)',message)
if match:status=int(match.group(1));kind='http_'+str(status)
else:kind='client_timeout' if 'Timeout' in message else ('transport' if 'connection/TLS' in message else 'contract')
except OSError:kind='transport'
records.append({'operation':operation,'clients':concurrency,'repeat':repeat,'warmup':repeat==0,'worker':number,'request':request,'elapsed_ms':1000*(time.monotonic()-start),'status':status,'error':kind,'success':kind is None})
return records
start=time.monotonic()
with ThreadPoolExecutor(max_workers=concurrency) as pool:
records=[row for group in pool.map(worker,range(concurrency)) for row in group]
elapsed=time.monotonic()-start;samples.extend(records)
phases.append({'operation':operation,'clients':concurrency,'repeat':repeat,'warmup':repeat==0,'requests':len(records),'elapsed_seconds':elapsed,'successful_rps':sum(r['success'] for r in records)/elapsed,'errors':dict(Counter(r['error'] for r in records if r['error']))})
print(operation,'clients='+str(concurrency),'complete',flush=True)
finally:
ended=time.monotonic()
for role,(sampler,cpus) in samplers.items():
try:resources[role]=sampler.finish(began,ended,cpus)
except RuntimeError as exc:resource_errors[role]=str(exc)
measured=[r for r in samples if not r['warmup']];table=[]
for concurrency in [1,5,10]:
for operation in names:
rows=[r for r in measured if r['operation']==operation and r['clients']==concurrency];ok=[r for r in rows if r['success']]
elapsed=sum(p['elapsed_seconds'] for p in phases if not p['warmup'] and p['operation']==operation and p['clients']==concurrency)
table.append({'operation':operation,'clients':concurrency,'requests':len(rows),'successes':len(ok),'errors':dict(Counter(r['error'] for r in rows if r['error'])),'elapsed_seconds':elapsed,'successful_rps':len(ok)/elapsed,'success_latency_ms':harness.percentiles([r['elapsed_ms']/1000 for r in ok]) if ok else None,'all_request_latency_ms':harness.percentiles([r['elapsed_ms']/1000 for r in rows])})
report={'generator':'Python urllib public Client; closed loop, no retries, concurrency is clients not arrival rate','method':{'concurrency':[1,5,10],'repeats':a.repeats,'requests_per_worker_per_repeat':a.per_worker,'warmup_requests_per_worker_per_operation':1,'initial_history_messages':a.history,'deep_cursor_after_messages':((a.history*8//10)//100)*100,'message_payload_codepoints':123,'message_payload_padding_chars':80,'seed_payload_padding_chars':100,'client_timeout_seconds':a.client_timeout,'limits':config},'elapsed_seconds':ended-began,'table':table,'phases':phases,'samples':samples,'resources':resources,'resource_errors':resource_errors,'internal_sql_or_pool_times':'not instrumented: HTTP latency is not storage latency','limitations':['Small sample, p99 often equals observed maximum; no p99.9 or SLO claims.','Closed loop has coordinated omission and does not measure maximum capacity.','HTTP elapsed includes client validation and connection/scheduling overhead.','Resource sampler executes inside cgroups; sampled peaks include sampling overhead.','History and database grow during create/write operations; only seeded cursor position is fixed.']}
(a.output/'results.json').write_text(json.dumps(report,indent=2))
lines=['# HTTP latency matrix','','Preliminary closed-loop measurements, not selected application budgets.','','| Operation | Clients | n | Errors | Successful RPS | p50 ms | p95 ms | p99 ms |','|---|---:|---:|---:|---:|---:|---:|---:|']
for row in table:
t=row['success_latency_ms'] or dict(p50=0,p95=0,p99=0);lines.append('| %s | %d | %d | %d | %.2f | %.2f | %.2f | %.2f |'%(row['operation'],row['clients'],row['requests'],row['requests']-row['successes'],row['successful_rps'],t['p50'],t['p95'],t['p99']))
lines+=['','Full conditions, warmup/error timings and CPU/RAM samples: results.json. HTTP times are not SQL times. Small n does not support stable tail estimates.']
(a.output/'TABLE.md').write_text('\n'.join(lines)+'\n')
failures=any(not r['success'] for r in samples) or bool(resource_errors) or any(v.get('oom_kill_count',0)>0 for v in resources.values())
print('FAIL' if failures else 'COMPLETE',flush=True)
return 1 if failures else 0
if __name__=='__main__':raise SystemExit(main())