#!/usr/bin/env python3 import json,os,subprocess,sys,time from pathlib import Path ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests')) from client import Client,Failure,check c=Client('http://localhost:8084');a,b,e,chat=c.bootstrap();original=(ROOT/'tests/fixtures/sample.png').read_bytes() upload=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=failover.png',201,actor=a,raw=original,headers={'Content-Type':'image/png'},schema='Attachment') alias=upload['headers']['X-Instance-Id'];ids=subprocess.check_output(['docker','compose','ps','-q','api'],cwd=ROOT,text=True).splitlines() matched=[id for id in ids if json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]['Config']['Hostname']==alias];check(len(matched)==1,'alias mapping') started=time.monotonic();failures=0 try: subprocess.run([str(ROOT/'scripts/stop-one.sh')],cwd=ROOT,env=dict(os.environ,TARGET_INSTANCE_ID=alias),check=True,stdout=subprocess.DEVNULL) while True: try:r=c.call('GET','/api/v1/attachments/'+upload['json']['id']+'/content',actor=b);break except Failure:failures+=1;check(time.monotonic()-started<10,'download recovery >10s');time.sleep(.1) check(r['bytes']==original and r['headers']['X-Instance-Id']!=alias,'download not preserved through another process') stopped=json.loads(subprocess.check_output(['docker','inspect',matched[0]],text=True))[0];check(not stopped['State']['Running'],'target not stopped') result={'upload_instance':alias,'stopped_container':stopped['Name'],'download_instance':r['headers']['X-Instance-Id'],'byte_equal':True,'first_recovery_seconds':time.monotonic()-started,'errors':failures} (ROOT/'evidence/attachment-failover.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: exact uploader stopped; another API returned identical original') finally:subprocess.run(['docker','compose','up','-d','--wait'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)