#!/bin/bash
# run28r.sh <list> <passes> — run28.sh that resumes: a (pass, trial, cell) already in b28.jsonl is skipped.
# Spinel programs under threads/ractors/fork. For each pass: 3 trials interleaved
# (trial loop outermost). Cells: threads W=1,8; ractors and fork W=1,2,4,8. k (runs per task) from calib.jsonl,
# the same on every host. Each cell: lock check -> /proc/stat + slice snapshot -> one pinned container -> snapshot;
# foreign CPU on the pinned cores above 0.05 + 0.03*W cores -> discarded and re-run (max 5), never counted.
# The rest of the machine (the other 12 cores) above OTHER_MAX cores of CPU during the cell -> discarded, re-run after
# 30 s (max 120 waits): a busy neighbour slows allocation-heavy cells 10-14 % through shared memory (card 651, run A).
set -u
D=$HOME/rb651/sp; cd "$D"
GPU_MAX=5   # %, mean GPU utilization during the cell: the GPU shares LPDDR5X with the CPU (card 651: a serving GPU cost
             # memory-bound cells 2.5x). Utilization, not power: idle power differs by host (10.1 vs 14.1 W at 0 %)
OTHER_MAX=5   # cores of CPU on the 12 non-bench cores, mean over the cell
IMG=ruby@sha256:3251898a6b7ff1275a0dc279d401889c6c743c1fb3292fa3ce1a2e12fc2cd31d
LIST=$1; PASSES=$2; HOST=$(hostname)
OUT=$D/b28.jsonl; LOG=$D/b28.log
log() { echo "$(date +%T) $*" | tee -a "$LOG"; }
expand() { echo "$1" | awk -F, '{for(i=1;i<=NF;i++){n=split($i,r,"-"); if(n==1)print r[1]; else for(c=r[1];c<=r[2];c++)print c}}'; }
snap() {
  awk '/^cpu[0-9]/{c=substr($1,4); print c, $2+$3+$4+$7+$8+$9}' /proc/stat
  echo "slice $(awk '/usage_usec/{print $2}' /sys/fs/cgroup/bench651.slice/cpu.stat 2>/dev/null || echo 0)"
}
coreset() { case $1 in 1) echo 1;; 2) echo 1-2;; 4) echo 1-4;; 8) echo 1-4,10-13;; *) echo BAD;; esac; }   # Cortex-A725; cpu 0 left out
kof() { local c=$1; case $c in fasta|ao_render) c=${c}_rs;; io_wordcount_rs) c=io_wordcount;; esac   # same work per run: unpatched fasta/ao_render take their patch's k, io_wordcount_rs the original's
  jq -r --arg b "$c" 'select(.bm==$b) | .k' calib.jsonl; }

cell() { # pass trial cpuset label args...
  local pass=$1 trial=$2 set_=$3 label=$4 w fmax try a b t0 t1 rc o m nf=0 nb=0; shift 4
  w=$(expand "$set_" | wc -l); fmax=$(echo "0.05 + 0.03 * $w" | bc)
  while true; do
    $HOME/rb651/lock.sh check >/dev/null || { log "FAIL lock lost before $label"; exit 3; }
    gp=$(mktemp); nvidia-smi --query-gpu=utilization.gpu,power.draw --format=csv,noheader,nounits -lms 1000 > "$gp" 2>/dev/null & gpid=$!
    a=$(snap); t0=$(date +%s.%N)
    o=$(docker run --rm --cgroup-parent=bench651.slice --cpuset-cpus="$set_" -v "$D":/b -w /b "$IMG" \
          timeout 900 ruby --yjit bm28.rb "$@" 2>>"$D/b28.err"); rc=$?
    t1=$(date +%s.%N); b=$(snap)
    kill $gpid 2>/dev/null; wait $gpid 2>/dev/null; gpu=$(awk -F', ' '{u+=$1; w+=$2; n++} END{if(n) printf "%.1f", u/n; else print "null"}' "$gp"); gpw=$(awk -F', ' '{w+=$2; n++} END{if(n) printf "%.1f", w/n; else print "null"}' "$gp"); rm -f "$gp"
    if [ $rc -ne 0 ] || [ -z "$o" ]; then log "FAIL $label exit=$rc"; exit 4; fi
    m=$({ echo "$a" | sed 's/^/A /'; echo "$b" | sed 's/^/B /'; } | awk -v set=" $(expand "$set_" | tr '\n' ' ')" -v dur=$(echo "$t1 - $t0" | bc) '
      $1=="A"{a[$2]=$3} $1=="B"{b[$2]=$3}
      END{ for(c in b){ if(c=="slice") continue; d=(b[c]-a[c])/100.0; if(index(set" ", " "c" ")) s+=d; else o+=d }
           sl=(b["slice"]-a["slice"])/1e6; f=(s-sl)/dur; if(f<0)f=0
           printf "{\"foreign_on_set\":%.3f,\"other_cores\":%.2f,\"ours\":%.2f,\"dur_s\":%.1f}", f, o/dur, sl/dur, dur }')
    if [ "$(echo "$m" | jq --argjson F "$fmax" '.foreign_on_set > $F')" = true ]; then
      nf=$((nf+1)); log "DISCARD $label foreign try $nf $m"; [ $nf -ge 5 ] && { log "FAIL $label: foreign load on 5 tries"; exit 5; }; sleep 5; continue
    fi
    m=$(echo "$m" | jq -c --argjson g "$gpu" --argjson w "$gpw" '. + {gpu_util: $g, gpu_w: $w}')
    if [ "$gpu" = null ]; then log "FAIL $label: no GPU samples"; exit 9; fi
    if [ "$(echo "$m" | jq --argjson G "$GPU_MAX" '.gpu_util > $G')" = true ]; then
      nb=$((nb+1)); log "DISCARD-GPU $label wait $nb $m"; [ $nb -ge 120 ] && { log "FAIL $label: machine busy for 120 waits"; exit 8; }; sleep 30; continue
    fi
    if [ "$(echo "$m" | jq --argjson O "$OTHER_MAX" '.other_cores > $O')" = true ]; then
      nb=$((nb+1)); log "DISCARD-BUSY $label wait $nb $m"; [ $nb -ge 120 ] && { log "FAIL $label: machine busy for 120 waits"; exit 8; }; sleep 30; continue
    fi
    echo "$o" | jq -c --argjson l "$m" --arg label "$label" --argjson pass "$pass" --argjson trial "$trial" --arg set "$set_" --arg host "$HOST" \
      '. + {load: $l, cell: $label, pass: $pass, trial: $trial, cpuset: $set, host: $host, discards: {foreign: '"$nf"', busy: '"$nb"'}}' >> "$OUT"
    return 0
  done
}

log "start (resume) list=$LIST passes=$PASSES host=$HOST image=$IMG gov_cpu1=$(cat /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor) a725_max=$(cat /sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_max_freq)"
for p in $(seq 1 "$PASSES"); do
  # YJIT steadiness gate before every pass (the X925 bimodality): 6 processes on cpu 1, spread must be < 10 % (see below)
  ys=$(for i in 1 2 3 4 5 6; do docker run --rm --cgroup-parent=bench651.slice --cpuset-cpus=1 "$IMG" ruby --yjit -e 'def fib(n) = n < 2 ? n : fib(n-1)+fib(n-2); 64.times { fib(22) }; t=Process.clock_gettime(Process::CLOCK_MONOTONIC); 64.times { fib(22) }; puts Process.clock_gettime(Process::CLOCK_MONOTONIC)-t'; done | sort -n | tr '\n' ' ')
  # The gate exists for YJIT's bimodality (on the X925 cores processes run 5-14x apart). It fails when the slowest of
  # 6 processes is more than 1.10x the fastest; one noisy process (a 2.4 % outlier, card 651) is not bimodality.
  spread=$(echo "$ys" | awk '{print ($NF-$1)/$1*100}')
  log "pass $p yjit gate: $ys spread ${spread}%"
  [ "$(echo "$spread < 10" | bc -l)" = 1 ] || { log "FAIL yjit gate pass $p"; exit 6; }
  for t in 1 2 3; do
    for b in $(cat "$LIST"); do
      f=benchmark/bm_$b.rb; k=$(kof "$b"); [ -n "$k" ] || { log "FAIL no k for $b in calib.jsonl"; exit 7; }
      for m in threads ractors fork; do for w in 1 2 4 8; do
        [ $m = threads ] && { [ $w = 2 ] || [ $w = 4 ]; } && continue
        if [ -s "$OUT" ] && jq -e --arg c "bm28 $b $m $w" --argjson p $p --argjson t $t 'select(.cell==$c and .pass==$p and .trial==$t)' "$OUT" >/dev/null; then continue; fi
        cell $p $t "$(coreset $w)" "bm28 $b $m $w" "$f" $m $w $k
      done; done
    done
    log "pass $p trial $t done: $(wc -l < "$OUT") rows"
  done
done
log "DONE"
