#!/usr/bin/env python3 """Grade-4 acceptance through the public LB; writes only synthetic test data.""" from concurrent.futures import ThreadPoolExecutor import json import os from pathlib import Path import subprocess import sys import threading import time import uuid ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT/'tests')) from client import Client, Failure, check, run from resilience import history STACK = os.environ.get('STACK_NAME', 'mtusi-lab3') def docker_json(*args): return json.loads(subprocess.check_output(['docker', *args], text=True)) def task_ids(): ids = subprocess.check_output(['docker','service','ps','--filter','desired-state=running','-q',STACK+'_api'], text=True).split() return {i for i in ids if docker_json('inspect',i)[0]['Status']['State']=='running'} def wait_ready(): subprocess.run([sys.executable, str(ROOT/'scripts/swarm.py'), 'wait'], check=True, stdout=subprocess.DEVNULL) time.sleep(3) # DNS and HAProxy rise interval def idempotency(c, alice, bob, eve, chat): key = uuid.uuid4().hex barrier = threading.Barrier(16) def send(_): local = Client(timeout=5) barrier.wait() return local.message(alice, chat, 'one concurrent effect', key=key) with ThreadPoolExecutor(max_workers=16) as pool: results = list(pool.map(send, range(16))) expected = results[0]['json'] check(all(r['json']==expected and r['status']==201 for r in results), 'concurrent replay changed result') instances = {r['headers']['X-Instance-Id'] for r in results} check(len(instances)>=2, 'same-key race did not reach two replicas') path = '/api/v1/chats/'+chat['id']+'/messages' c.call('POST', path, 409, actor=alice, body={'text':'changed'}, headers={'Idempotency-Key':key}) c.call('POST', path, 404, actor=eve, body={'text':expected['text']}, headers={'Idempotency-Key':key}) other = c.message(bob, chat, expected['text'], key=key)['json'] check(other['id']!=expected['id'], 'key leaked across users') second_chat = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Key scope','member_ids':[alice['id'],bob['id']]},schema='Chat')['json'] separate = c.message(alice,second_chat,expected['text'],key=key)['json'] check(separate['id']!=expected['id'], 'key leaked across chats') for bad in ['', 'x'*129, 'bad key', 'bad,key', 'bad/key']: c.call('POST', path, 400, actor=alice, body={'text':'invalid key'}, headers={'Idempotency-Key':bad}) c.message(alice,chat,'128 ASCII characters',key='x'*128) retry = uuid.uuid4().hex c.call('POST',path,400,actor=alice,body={'text':''},headers={'Idempotency-Key':retry}) c.message(alice,chat,'valid after invalid',key=retry) check(sum(m['id']==expected['id'] for m in history(c,bob,chat))==1, 'race created duplicate') # Revocation must be rechecked even for an already committed key. c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice) c.call('POST',path,401,actor=alice,body={'text':expected['text']},headers={'Idempotency-Key':key}) print('PASS: shared-key race on two replicas; replay/conflict/scope/validation/access/logout', flush=True) return {'parallel_requests':16, 'instances':sorted(instances), 'unique_message_ids':1} def exercise(action, target=None): c = Client(timeout=2) alice,bob,eve,chat = c.bootstrap() original_key = uuid.uuid4().hex original = c.message(alice,chat,'confirmed before '+action,key=original_key)['json'] before = task_ids() stop = threading.Event() events = [] confirmations = [] lock = threading.Lock() def worker(number): local = Client(timeout=2) key = uuid.uuid4().hex body = 'load-'+key while not stop.is_set(): started = time.monotonic() try: result = local.message(alice,chat,body,key=key) with lock: confirmations.append(result['json']) local.call('GET','/api/v1/users/me',actor=bob,schema='User') event = (started,time.monotonic(),result['json'],result['headers']['X-Instance-Id'],None) key = uuid.uuid4().hex body = 'load-'+key except Failure as exc: event = (started,time.monotonic(),None,None,str(exc)) with lock: events.append(event) time.sleep(.03) threads = [threading.Thread(target=worker,args=(i,)) for i in range(4)] for thread in threads: thread.start() time.sleep(2) env = dict(os.environ) if target: env['TARGET_INSTANCE_ID'] = target started = time.monotonic() proc = subprocess.Popen([sys.executable,str(ROOT/'scripts/swarm.py'),action],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) try: code = proc.wait(timeout=180) check(code==0, action+' command failed') completed = time.monotonic() time.sleep(15 if target else 5) finally: stop.set() for thread in threads: thread.join(timeout=10) if proc.poll() is None: proc.kill(); proc.wait() ended = time.monotonic() wait_ready() window = [e for e in events if e[0]>=started] successes = [e for e in window if e[2] is not None] failures = [e for e in window if e[2] is None] check(bool(successes), 'no writes during '+action) recovery = min(e[1] for e in successes if e[0]>=completed)-started if target else None if target: check(recovery<=10, 'failure recovery exceeded 10 seconds') check(target not in [e[3] for e in successes[-20:]], 'stopped instance returned') check(target not in task_ids(), 'old task still running') else: check(before.isdisjoint(task_ids()), 'rolling update did not replace every replica') replay = c.message(alice,chat,original['text'],key=original_key)['json'] check(replay==original, 'committed idempotency result lost after '+action) all_messages = history(c,bob,chat) by_id = {m['id']:m for m in all_messages} check(by_id.get(original['id'])==original, 'pre-action confirmation lost') check(all(by_id.get(m['id'])==m for m in confirmations), 'confirmation lost/changed') texts = [m['text'] for m in all_messages] check(len(texts)==len(set(texts)), 'uncertain retry created duplicate') times = [started]+sorted(e[1] for e in successes)+[ended] max_gap = max(b-a for a,b in zip(times,times[1:])) check(max_gap<=10, 'writes stalled for more than 10 seconds') report = {'action':action,'target':target,'duration_seconds':round(ended-started,3), 'successful_writes':len(successes),'failed_attempts':len(failures), 'successful_rps':round(len(successes)/(ended-started),3), 'first_recovery_seconds':round(recovery,3) if recovery is not None else None, 'max_success_gap_seconds':round(max_gap,3), 'instances_before':sorted(before),'instances_after':sorted(task_ids()), 'confirmed_messages_checked':len(confirmations)+1, 'duplicate_bodies':0} print(json.dumps(report),flush=True) return report def main(): wait_ready() c = Client() results = {'idempotency':idempotency(c,*c.bootstrap())} originals = sorted(task_ids()) check(len(originals)==2,'grade4 scenario expects exactly two API replicas') results['failovers'] = [exercise('stop-one',target) for target in originals] results['rolling_update'] = exercise('update') (ROOT/'evidence/swarm-grade4.json').write_text(json.dumps(results,indent=2)+'\n') print('PASS: each original replica stopped and replaced; rolling update under load; confirmations and sessions preserved') if __name__=='__main__': run(main)