#!/usr/bin/env bash
# job_ab201b.sh: branch half of the isolated A/B plus the streams 1-8 state test, box 201 card 0. The Triton cache holds
# only the launcher shim (read-only), so every GDN binary must come from the branch's AOT artifacts (aot_br via the boot-cache
# overlay) or the run fails. Main rounds interleaved again so the arms share a lock hold.
cd ~/gdn-commit; W=$HOME/gdn-commit; S=$HOME/small-row-main; IMG=local/arbi-serve:main-43d0876; SP=/opt/venv/lib/python3.12/site-packages
exec 9>/run/lock/arbi-gpu-0.lock; flock -w 21600 9 || exit 1
echo "lock held $(date -Is) root $(df --output=pcent / | tail -1)"
rm -rf bc_br tcache_shim; mkdir -p bc_br bc_main tcache_shim; cp -r aot_br bc_br/aot
for d in tcache_main/*/; do ls $d | grep -q "fused_sigmoid" || cp -r $d tcache_shim/; done; ls tcache_shim
run() { # NAME TREE TCACHE BC CMD
  docker run --rm --name "gdn-commit-$1" --gpus device=0 --ipc host --memory 12g --cpus 4 --user "$(id -u):$(id -g)" \
    -e TKV_NO_JIT=1 -e PYTHONUNBUFFERED=1 -e HOME=/tmp -e PYTHONPYCACHEPREFIX=/tmp/pycache -e TRITON_CACHE_DIR=/tcache \
    -e ARBI_BOOT_CACHE_DIR=/bc -e PYTHONPATH=/src \
    -v $S/stubs/nvcc:/usr/local/cuda-13.1/bin/nvcc:ro -v $S/stubs/fail:/usr/bin/ninja:ro \
    -v $W/src_$2/arbi_serve:$SP/arbi_serve:ro -v $W/$3:/tcache:ro -v $W/$4:/bc:ro -v $W/out:/out -v $W/scripts:/scripts:ro -v $W/src_$2:/src:ro -w /src \
    --entrypoint bash $IMG -c "$5"
}
rm -f out/ab201b.jsonl
run test gdnbr tcache_shim bc_br "python -m pytest tests/test_gdn_delta_rule_aot.py -m gpu -p no:cacheprovider -k folded_commit_matches -q 2>&1 | tail -15" > logs/ab201b_test.log 2>&1; echo "test rc=$? $(date -Is)"
for rnd in 0 1 2; do
  run abmain gdnmain tcache_main bc_main "python /scripts/bench_ab.py --arm main --round $rnd --out /out/ab201b.jsonl" >> logs/ab201b.log 2>&1; echo "main r$rnd rc=$?"
  run abbr gdnbr tcache_shim bc_br "python /scripts/bench_ab.py --arm branch --round $rnd --out /out/ab201b.jsonl" >> logs/ab201b.log 2>&1; echo "branch r$rnd rc=$?"
done
echo "job_ab201b done $(date -Is)"
