"""Interrupt only this benchmark, immediately after its next flushed batch record."""
import pathlib,os,signal,time,json,argparse
p=argparse.ArgumentParser();p.add_argument('--id',default='nf4-kv4-262k-c3-v2');p.add_argument('--out',default='full-grid');args=p.parse_args()
assert '/' not in args.id and '..' not in args.id
assert '/' not in args.out and '..' not in args.out
root=pathlib.Path('/home/lab/bench/ornith/modular/vllm/runs')/args.id/args.out
needle=str(root).encode(); candidates=[]
for p in pathlib.Path('/proc').glob('[0-9]*/cmdline'):
 try:
  cmd=p.read_bytes()
  if b'/shared/bench.py\x00' in cmd and needle in cmd:candidates.append(int(p.parent.name))
 except (OSError,PermissionError):pass
assert len(candidates)==1,candidates
pid=candidates[0]; file=root/'results.jsonl'; count=sum(1 for _ in file.open())
print('Waiting for next completed batch before interrupting benchmark PID',pid,flush=True)
while pathlib.Path(f'/proc/{pid}').exists():
 n=sum(1 for _ in file.open())
 if n>count:
  cmd=pathlib.Path(f'/proc/{pid}/cmdline').read_bytes();assert needle in cmd
  os.kill(pid,signal.SIGINT)
  print('Interrupted benchmark after',n,'recorded batches; server preserved.',flush=True)
  break
 time.sleep(.1)
