"""Run from a directory containing route.ts and install-instrumentation.py.
Usage: python3 measure.py --base CHECKOUT --head CHECKOUT --node NODE --out OUTPUT
Installs identical scratch instrumentation; launches production CLI HTTP servers.
Each sample has its own on-disk database, one untimed size=0 warmup, and a fresh
synthetic parent for the timed sample. Only the orchestrator dispatch is timed.
No test runner, mocks, real accounts, or copied data are used.
"""
import argparse, datetime, json, os, pathlib, platform, statistics, subprocess, time, urllib.request
p=argparse.ArgumentParser();p.add_argument('--base',required=True);p.add_argument('--head',required=True);p.add_argument('--node',required=True);p.add_argument('--out',required=True);p.add_argument('--samples',type=int,default=7);a=p.parse_args()
out=pathlib.Path(a.out)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ');out.mkdir(parents=True)
roots={'base':pathlib.Path(a.base).resolve(),'head':pathlib.Path(a.head).resolve()}
for root in roots.values(): subprocess.run(['python3',str(pathlib.Path(__file__).parent/'install-instrumentation.py'),str(root)],check=True)
meta={'platform':platform.system()+' '+platform.release()+' '+platform.machine(),'node':subprocess.check_output([a.node,'--version'],text=True).strip(),'commits':{s:subprocess.check_output(['git','rev-parse','HEAD'],cwd=r,text=True).strip() for s,r in roots.items()},'samplesPerSize':a.samples,'timed':'orchestrator.dispatch(message.dispatch to completed child, user, start_immediately)','providerEffects':'parked identically; no provider work in measured operation','instrumentation':'SQL capture enabled on both; parent SELECTs re-run and counted outside timed interval'}
(out/'environment.json').write_text(json.dumps(meta,indent=2))
results=[]
def post(size):
 req=urllib.request.Request('http://127.0.0.1:14785/__followup_bench',data=json.dumps({'size':size}).encode(),headers={'Content-Type':'application/json'})
 with urllib.request.urlopen(req,timeout=120) as r: return json.load(r)
for sample in range(a.samples):
 for size in [0,2000,15000]:
  for side in (['base','head'] if sample%2==0 else ['head','base']):
   name=f'{side}-{size}-{sample+1}';home=out/name;home.mkdir();log=open(home/'server.private.log','w')
   env=os.environ.copy();env['T3CODE_DEV_SEED']='0'
   proc=subprocess.Popen([a.node,'apps/server/src/bin.ts','serve','--host','127.0.0.1','--port','14785','--dev-url','http://127.0.0.1:14786','--base-dir',str(home/'home')],cwd=roots[side],env=env,stdout=log,stderr=subprocess.STDOUT)
   try:
    for attempt in range(240):
     if proc.poll() is not None: raise RuntimeError(f'{name}: server exited; inspect private log')
     try:
      urllib.request.urlopen('http://127.0.0.1:14785/.well-known/t3/environment',timeout=1).close();break
     except Exception:time.sleep(.25)
    else:raise RuntimeError('server readiness deadline')
    warm=post(0)
    if 'error' in warm:raise RuntimeError(warm['error'])
    data=post(size)
    if 'error' in data:raise RuntimeError(data['error'])
    for key in ['ownershipPreserved','providerTurnPreserved','originalTaskCompleted','followupCreated']:
     if not data[key]:raise RuntimeError(f'{name}: {key} failed')
    data.update(side=side,sample=sample+1,sha=meta['commits'][side]);results.append(data)
    (out/'measurements.json').write_text(json.dumps(results,indent=2))
    print(f'{side:4} N={size:5} sample={sample+1}: {data["dispatchMs"]:.2f} ms; ownership/binding/task OK',flush=True)
   finally:
    proc.terminate()
    try:proc.wait(timeout=20)
    except subprocess.TimeoutExpired:proc.kill();proc.wait()
    log.close()
summary=[]
for size in [0,2000,15000]:
 row={'history':size}
 for side in ['base','head']:
  ds=[d for d in results if d['side']==side and d['size']==size];ts=[d['dispatchMs'] for d in ds]
  counts={}
  for table in ['runs','run_attempts','provider_turns']:
   counts[table]=[sum(q['rows'] for q in d['reads'] if 'SELECT payload_json' in q['query'] and 'FROM orchestration_v2_projection_'+table+'\n' in q['query']) for d in ds]
  row[side]={'medianMs':statistics.median(ts),'minMs':min(ts),'maxMs':max(ts),'samplesMs':ts,'parentPayloadRows':counts}
 row['medianGainMs']=row['base']['medianMs']-row['head']['medianMs'];row['largestSpreadMs']=max(row[s]['maxMs']-row[s]['minMs'] for s in ['base','head']);row['gainExceedsSpread']=row['medianGainMs']>row['largestSpreadMs'];summary.append(row)
(out/'summary.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary,indent=2));print('OUTPUT',out)
