from ops import *
import sys
mode=sys.argv[1];assert mode in ('pose','mixed','mixed-resume','mixed-compact')
assert all(r['state']=='stopped' and not r.get('cleanup_pending') for r in api('/api/v1/streams')['streams'])
assert not inspect('contextra-ai-gateway-1')['State']['Running']
image=inspect('contextra-analytics-1')['Image']
save(mode+'-helper-manifest.json',dict(image=image,sha256={n:hashlib.sha256((HERE/n).read_bytes()).hexdigest()
    for n in ('trial.py','run.py','ops.py')},api_read_timeout_s=5))
code=Path('/tmp/codex/ltb1021/2026-09-27_result-queue-bc_r01/drift_reader.py').read_text()
code=code.replace('(3,8,9,10)','(3,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20)')
code=code.replace('<900','<2350').replace('20000','500000')
code=code.replace("if s.get('providerKey')!='pose':continue", "if s.get('providerKey') not in ('pose','fire','crowd'):continue")
code=code.replace("kind='frame',camera", "kind='frame',provider=s.get('providerKey'),camera")
auth=Path('/workspace/contextra-runtime-config/metadata-active/reader/reader-credentials.json')
assert not auth.is_symlink() and auth.stat().st_mode&0o077==0
path=HERE/(mode+'-redis.jsonl');pid=None;returncode=None
with path.open('x') as log,(HERE/(mode+'-reader.stderr')).open('x') as err:
    reader=subprocess.Popen(['docker','exec','-i','contextra-analytics-1','python3','-B','-c',code],stdin=subprocess.PIPE,stdout=log,stderr=err,text=True)
    try:
        reader.stdin.write(auth.read_text());reader.stdin.close();deadline=time.monotonic()+10
        while True:
            with path.open() as f:first=f.readline()
            if first:
                ready=json.loads(first);assert ready['kind']=='ready';pid=ready['pid'];break
            if reader.poll() is not None or time.monotonic()>deadline:raise RuntimeError('READER_STARTUP')
            time.sleep(.1)
        print('Collector ready; '+mode+' C trial begins',flush=True)
        trial=subprocess.Popen([sys.executable,str(HERE/'trial.py'),mode])
        try:returncode=trial.wait(timeout=2200)
        except subprocess.TimeoutExpired:
            trial.terminate();returncode=trial.wait(timeout=180)
    finally:
        if pid and reader.poll() is None:
            assert inspect('contextra-analytics-1')['Image']==image
            kill="import os,signal;from pathlib import Path;p="+str(pid)+";a=Path('/proc')/str(p)/'cmdline';assert a.exists() and b'contextra-drift-live-r01' in a.read_bytes();os.kill(p,signal.SIGTERM)"
            cmd(['docker','exec','contextra-analytics-1','python3','-B','-c',kill],timeout=5)
        reader.wait(timeout=10)
save(mode+'-reader-final.json',dict(reader_exit=reader.returncode,trial_exit=returncode,pid=pid,reaped=True))
raise SystemExit(returncode or reader.returncode)
