#!/bin/bash
# 端到端 A/B:SYMCC_BATCH_SHOWMAP=0(流式) vs =1(批量),profiled hybrid,量 showmap_dedup 相位实降幅。
set -u
cd /home/ubuntu/code/symcc
SC=/tmp/claude-1000/-home-ubuntu-code-symcc/ba111467-440e-48b7-88eb-2622f7533f6f/scratchpad
OUT=/tmp/batch_ab; rm -rf "$OUT"; mkdir -p "$OUT"

cleanup() {   # 只用精确进程名/带独特参数的模式,绝不匹配本脚本或聚合命令
  pkill -9 -x mpirun 2>/dev/null; pkill -9 -x orted 2>/dev/null
  pkill -9 -x base64 2>/dev/null; pkill -9 -x afl-showmap 2>/dev/null
  pkill -9 -f "mpi_fuzzing_helper.py -a fuzzer01" 2>/dev/null
  sleep 3
}

for BATCH in 0 1; do
  for NP in 8 32; do
    tag="b${BATCH}_np${NP}"; WP="$OUT/wp_$tag"; mkdir -p "$WP"
    echo "=== [$(date +%H:%M:%S)] RUN $tag : SYMCC_BATCH_SHOWMAP=$BATCH np=$NP ==="
    SYMCC_WORKER_PROFILE=1 SYMCC_WPROF_DIR="$WP" SYMCC_BATCH_SHOWMAP=$BATCH \
      python3 benchmark/run_benchmark.py --targets lava-base64 --np-list $NP \
        --rounds 1 --timeout 120 --hybrid --no-serial \
        --output "$OUT/out_$tag" > "$OUT/log_$tag.txt" 2>&1
    # 聚合该 run 的相位计时
    python3 - "$WP" "$tag" "$OUT" <<'PY'
import sys; sys.path.insert(0,"util")
import mpi_fuzzing_helper as m
wp,tag,out=sys.argv[1],sys.argv[2],sys.argv[3]
f=m.aggregate_phase_timing(wp)
line=f"{tag}: (无 phase 数据)"
if f:
    txt=open(f).read()
    mp=[l for l in txt.splitlines() if l.startswith("MEAN_PCT")]
    tot=[l for l in txt.splitlines() if l.startswith("TOTAL")]
    # phases 顺序: wait,bmsync,import,exec,showmap_dedup,send
    line=f"{tag}: MEAN_PCT[{mp[0] if mp else '?'}]  TOTAL[{tot[0] if tot else '?'}]"
open(f"{out}/summary.txt","a").write(line+"\n")
print("  "+line)
PY
    cleanup
  done
done
echo "=== 边覆盖对照(应持平,验证批量不损覆盖)==="
for tag in b0_np8 b1_np8 b0_np32 b1_np32; do
  cov=$(grep -hE ',hybrid,' "$OUT/out_$tag/benchmark_data.csv" 2>/dev/null | awk -F, '{print $9}')
  echo "  $tag: hybrid edge_cov=${cov}%"
done
echo "=== 相位小结 ==="; cat "$OUT/summary.txt"
echo "BATCH_AB_DONE"
