#!/usr/bin/env bash
# Cold final-base validation for vLLM.  The chosen quality-preserving profile
# is intentionally 128K: 3x256K with BF16 attention KV cannot fit on 24 GiB.
# This script creates new evidence only; it never overwrites earlier runs.
set -euo pipefail

root=/home/lab/bench/ornith/modular/vllm
id=full-int8-bf16-128k-final-250w
case="$root/cases/$id.json"
log="$root/final-acceptance-128k.log"

if test -e "$root/thermal-stop.json"; then
  echo 'Final vLLM validation blocked by thermal safety latch.' | tee -a "$log"
  exit 1
fi

for path in "$root/runs/$id" "$root/runs/$id/final-grid" \
            "$root/runs/$id/final-stability" "$root/runs/$id/final-throughput"; do
  if test -e "$path"; then
    echo "Refusing to overwrite existing evidence: $path" | tee -a "$log"
    exit 1
  fi
done

python3 - "$root/cases/full-int8-bf16-128k-250w.json" "$case" "$id" <<'PY'
import json, sys
source, destination, identifier = map(__import__('pathlib').Path, sys.argv[1:])
data = json.loads(source.read_text())
data['id'] = str(identifier)
destination.write_text(json.dumps(data, indent=2) + '\n')
PY

echo 'Starting frozen W8A16 + BF16-KV base at externally verified 250 W.' | tee -a "$log"
python3 "$root/candidate.py" "$case" 2>&1 | tee -a "$log"
python3 "$root/quality_gate.py" --out "$root/runs/$id/quality-final.json" 2>&1 | tee -a "$log"

python3 "$root/final_suite.py" --id "$id" --out final-grid \
  --lengths 4096,32768,131072 --concurrency 1,3 --repeats 5 \
  --task retrieval --max-output 256 --seed 4400 2>&1 | tee -a "$log"

python3 "$root/residency.py" --id "$id" --context 131072 \
  --out residency-final.json 2>&1 | tee -a "$log"

python3 "$root/final_suite.py" --id "$id" --out final-throughput \
  --lengths 4096 --concurrency 1,3 --repeats 5 \
  --task throughput --max-output 512 --seed 85009 2>&1 | tee -a "$log"

python3 "$root/final_suite.py" --id "$id" --out final-stability \
  --lengths 131072 --concurrency 3 --repeats 1 --duration 1800 \
  --task retrieval --max-output 256 --seed 72901 2>&1 | tee -a "$log"

echo 'FINAL VLLM 128K ACCEPTANCE COMPLETE; inspect individual evidence before promotion.' | tee -a "$log"
