#!/usr/bin/env python3
"""Linux service launcher latency proof. Run with sudo python3 measure.py HEAD_CHECKOUT BASE_CHECKOUT OUTPUT_ROOT.
Creates only a private dm-delay/loop/btrfs volume; never installs or changes a system service.
Requires installed checkout dependencies, node, dmsetup, btrfs-progs, losetup.
"""
import os,sys,time,json,subprocess as sp,pathlib,urllib.request,threading,ctypes,statistics,signal,shlex
head,base,root=map(pathlib.Path,sys.argv[1:]); out=root/time.strftime('run-%Y%m%d-%H%M%S'); out.mkdir()
def cmd(*args): return sp.check_output(args,text=True).strip()
node=cmd('node','-p','process.execPath'); image=out/'disk.img'; mount=out/'disk'; mount.mkdir(); name='t3-evidence-'+str(os.getpid()); loop=None; mapped=False; mounted=False
libc=ctypes.CDLL('libc.so.6'); results=[]
try:
 with open(image,'wb') as f: f.truncate(1024**3)
 loop=cmd('losetup','--find','--show',str(image)); cmd('mkfs.btrfs','-f','-K',loop); sectors=cmd('blockdev','--getsz',loop)
 cmd('dmsetup','create',name,'--table',f'0 {sectors} delay {loop} 0 0 {loop} 0 3000'); mapped=True
 dev='/dev/mapper/'+name; cmd('mount',dev,str(mount)); mounted=True; os.chown(mount,1000,1000)
 for side,checkout in [('before',base),('after',head)]:
  sha=cmd('git','-C',str(checkout),'rev-parse','HEAD')
  for run in range(1,4):
   home=out/f'{side}-{run}-home'; runtime_version=json.loads((checkout/'apps/server/package.json').read_text())['version']; version=home/'runtime/versions'/runtime_version; version.mkdir(parents=True)
   port=cmd(node,'-e',"const s=require('net').createServer();s.listen(0,'127.0.0.1',()=>{console.log(s.address().port);s.close()})")
   wrapper=version/'t3'; wrapper.write_text('#!/bin/sh\nexec '+shlex.quote(node)+' '+shlex.quote(str(checkout/'apps/server/src/bin.ts'))+' "$@" --port '+port+' --log-level debug --log-ws-events\n'); wrapper.chmod(0o755)
   (version/'.install-complete').write_text(runtime_version); (home/'runtime/service-state.json').write_text(json.dumps({'protocol':4,'activeVersion':runtime_version}))
   for p in [home,*home.rglob('*')]: os.chown(p,1000,1000)
   logfile=mount/f'{side}-{run}.log'; fd=os.open(logfile,os.O_CREAT|os.O_WRONLY|os.O_APPEND,0o600)
   env={**os.environ,'HOME':cmd('getent','passwd','1000').split(':')[5],'T3CODE_HOME':str(home),'T3CODE_DEV_SEED':'0'}
   proc=sp.Popen([node,str(checkout/'apps/server/src/bin.ts'),'__service-launcher'],cwd=checkout,env=env,stdout=fd,stderr=fd,user=1000,group=1000,start_new_session=True); os.close(fd)
   try:
    url='http://127.0.0.1:'+port+'/.well-known/t3/environment'
    for attempt in range(120):
     try:
      response=urllib.request.urlopen(url,timeout=1); response.read(); break
     except urllib.error.HTTPError as e:
      if e.code in (401,403,404): break
     except Exception: pass
     if proc.poll() is not None: raise RuntimeError('launcher exited: '+logfile.read_text()[-2000:])
     time.sleep(1)
    else: raise RuntimeError('server did not start')
    children=pathlib.Path(f'/proc/{proc.pid}/task/{proc.pid}/children').read_text().split(); pid=int(children[0]); fdlink=os.readlink(f'/proc/{pid}/fd/1'); fdtype='socket-backed-pipe' if fdlink.startswith('socket:') else ('pipe' if fdlink.startswith('pipe:') else 'regular-file')
    print(side,run,'server ready; stdout='+fdtype,flush=True)
    stop=time.monotonic()+60; samples=[]; blocked=[]
    def background():
     f=os.open(logfile,os.O_RDONLY)
     while time.monotonic()<stop:
      libc.sync_file_range(f,ctypes.c_longlong(0),ctypes.c_longlong(0),2)
      try:
       stack=pathlib.Path(f'/proc/{pid}/task/{pid}/stack').read_text()
       if 'btrfs' in stack: blocked.append({'syscall':pathlib.Path(f'/proc/{pid}/task/{pid}/syscall').read_text().split()[0],'stack':stack})
      except Exception: pass
      time.sleep(.2)
     os.close(f)
    worker=threading.Thread(target=background);worker.start()
    while time.monotonic()<stop:
     start=time.monotonic(); status=None; body=b''; error=None
     try:
      with urllib.request.urlopen(url,timeout=60) as response: status=response.status;body=response.read()
     except urllib.error.HTTPError as e: status=e.code;body=e.read()
     except Exception as e: error=type(e).__name__
     samples.append({'elapsedSeconds':round(start-(stop-60),3),'latencyMs':round((time.monotonic()-start)*1000,3),'status':status,'bytes':len(body),'error':error});time.sleep(.1)
    worker.join(); lat=[s['latencyMs'] for s in samples]
    result={'side':side,'run':run,'commit':sha,'durationSeconds':60,'stdout':fdtype,'requests':len(lat),'meanMs':statistics.mean(lat),'medianMs':statistics.median(lat),'p99Ms':sorted(lat)[int(len(lat)*.99)],'maxMs':max(lat),'over1s':sum(x>1000 for x in lat),'responses':list(set((s['status'],s['bytes'],s['error']) for s in samples)),'logBytes':logfile.stat().st_size,'blockedSamples':blocked,'samples':samples}
    results.append(result); (out/f'{side}-{run}.json').write_text(json.dumps(result,indent=2)); print(json.dumps({k:v for k,v in result.items() if k not in ['samples','blockedSamples']}),flush=True)
   finally:
    
    if proc.poll() is None: os.killpg(proc.pid,signal.SIGTERM)
    try: proc.wait(timeout=15)
    except sp.TimeoutExpired: os.killpg(proc.pid,signal.SIGKILL);proc.wait()
 (out/'measurement.json').write_text(json.dumps({'environment':{'os':'Linux x86_64','kernel':cmd('uname','-r'),'node':cmd(node,'--version'),'filesystem':'1 GiB btrfs over dm-delay, 3000 ms writes','output':'O_APPEND stdout and stderr, T3 home on normal disk'},'results':results},indent=2))
 print('OUTPUT',out,flush=True)
finally:
 if mounted: cmd('umount',str(mount))
 if mapped: cmd('dmsetup','remove',name)
 if loop: cmd('losetup','-d',loop)
