#!/usr/bin/env bash
# The `--cfg m2v_gpu` device lane, in one command: what it is, that the shards cover it, and
# what each shard answered. Written for bash (not zsh, which does not word-split a bare
# parameter and so would read a term list as one word).
#
#   scripts/device-lane/device-lane --profile debug|release [options]
#
#   --profile debug|release  required, and recorded in the report. The two find different things:
#                            debug keeps the product's `debug_assert`s, release is what a timing-
#                            sensitive test needs. Neither profile's result stands for the other.
#   --out DIR                where the listings, the shard set, the logs and the report go
#                            (default $HOME/.cache/metal2vulkan-device-lane)
#   --filter EXPR            run a slice: a nextest filterset intersected with the lane. The
#                            report then marks the selection a slice, and its coverage is of that
#                            slice alone. An expression that narrows nothing stops the run
#   --list-only              derive the lane and prove the shard set, and open no device
#   --shards FILE            take a shard set instead of deriving one (a past run's shards.tsv);
#                            it is proved against the lane like a derived one
#   --max-shard N            the most tests a derived shard holds (default 150)
#   --jobs N                 nextest's test threads per shard (default 4)
#   --cfg-target DIR         the cfg build's target directory (default target/device-lane-gpu)
#   --plain-target DIR       the plain build's   (default target/device-lane-plain).
#                            `RUSTFLAGS` is part of a build's fingerprint, so the two legs cannot
#                            share one directory without rebuilding the workspace each time
#
# It exits 0 only when the coverage proof holds, every selected test ran or is `#[ignore]`d, and
# every shard passed. The lane is derived, never stored: a committed shard set would not grow a
# term for a test added under a new module, and would skip it in silence.
set -euo pipefail

here=$(cd "$(dirname "$0")" && pwd)
repo=$(git -C "$here" rev-parse --show-toplevel)
lane_py="$here/lane.py"

die() {
  echo "device-lane: $*" >&2
  exit 2
}

profile=
out="$HOME/.cache/metal2vulkan-device-lane"
filter=
list_only=
shards_given=
max_shard=150
jobs=4
cfg_target=
plain_target=

while [ $# -gt 0 ]; do
  case "$1" in
  --profile) profile=${2:-}; shift 2 ;;
  --out) out=${2:-}; shift 2 ;;
  --filter) filter=${2:-}; shift 2 ;;
  --list-only) list_only=yes; shift ;;
  --shards) shards_given=${2:-}; shift 2 ;;
  --max-shard) max_shard=${2:-}; shift 2 ;;
  --jobs) jobs=${2:-}; shift 2 ;;
  --cfg-target) cfg_target=${2:-}; shift 2 ;;
  --plain-target) plain_target=${2:-}; shift 2 ;;
  -h | --help) sed -n '2,/^set -euo/p' "$0" | sed 's/^# \{0,1\}//; $d'; exit 0 ;;
  *) die "unknown option $1 (--help lists them)" ;;
  esac
done

case "$profile" in
debug) profile_args= ;;
release) profile_args=--release ;;
*) die "--profile debug|release is required, and is recorded in the report" ;;
esac

[ -n "$cfg_target" ] || cfg_target="$repo/target/device-lane-gpu"
[ -n "$plain_target" ] || plain_target="$repo/target/device-lane-plain"
[ "$cfg_target" != "$plain_target" ] || die "the two legs need separate target directories"

# The hang tripwire: while it exists every GPU open in the validation crate is refused, so a
# sweep would spend its whole wall on refusals. A person removes it (docs/VALIDATION.md).
for tripwire in "$HOME/.cache/m2v-gpu/hang" /tmp/m2v-gpu.hang; do
  [ -e "$tripwire" ] && die "the hang tripwire $tripwire exists: read it, then a person removes it"
done

mkdir -p "$out"
echo $$ > "$out/run.pid"   # this run's pid, so an operator can end it without a shared pattern
echo "-" > "$out/current-shard"

report="$out/report.txt"
say() { printf '%s\n' "$*" | tee -a "$report"; }

: > "$report"
say "device lane: $(date '+%Y-%m-%d %H:%M:%S')"
dirt=$(git -C "$repo" status --porcelain | wc -l | tr -d " ")
[ "$dirt" -eq 0 ] && dirty= || dirty=" + $dirt uncommitted path(s)"
say "  revision        $(git -C "$repo" rev-parse --short HEAD)$dirty"
say "  profile         $profile"
say "  nextest         $(cargo nextest --version | head -1)"
say "  cfg target      $cfg_target"
say "  plain target    $plain_target"
say "  test threads    $jobs"
say "  selection       ${filter:-the whole device lane}"
say "  output          $out"
say ""

# One listing of the workspace.
nextest_list() {
  target=$1
  flags=$2
  destination=$3
  shift 3
  ( cd "$repo" \
    && CARGO_TARGET_DIR="$target" \
       RUSTFLAGS="$flags" \
       cargo nextest list --workspace --all-features $profile_args \
         --run-ignored all --message-format json --list-type full "$@" ) \
    > "$destination" 2> "${destination%.json}.err"
}

say "listing the cfg build (--cfg m2v_gpu) ..."
nextest_list "$cfg_target" "--cfg m2v_gpu" "$out/cfg.json"
say "listing the plain build ..."
nextest_list "$plain_target" "" "$out/plain.json"

selection_args=
if [ -n "$filter" ]; then
  say "listing the slice in the cfg build ..."
  nextest_list "$cfg_target" "--cfg m2v_gpu" "$out/slice.json" -E "$filter"
  selection_args="--selection $out/slice.json"
fi

say ""
python3 "$lane_py" derive --cfg "$out/cfg.json" --plain "$out/plain.json" \
  --out "$out" --max-shard "$max_shard" $selection_args | tee -a "$report"

# A `--filter` that selects the whole lane selected nothing: stop rather than spend the lane's
# whole wall on a run whose report would then be read as a slice.
if [ -n "$filter" ] && [ "$(wc -l < "$out/selection.tsv")" -eq "$(wc -l < "$out/lane.tsv")" ]; then
  say ""
  say "STOPPED: --filter selected the whole lane, so it narrowed nothing. Check the expression."
  exit 2
fi

if [ -n "$shards_given" ]; then
  say ""
  say "shard set taken from $shards_given"
  cp "$shards_given" "$out/shards.tsv"
fi

say ""
proof=0
python3 "$lane_py" prove --out "$out" | tee -a "$report" || proof=$?
if [ "$proof" -ne 0 ]; then
  say ""
  say "STOPPED before opening a device: the shard set does not cover the selection."
  exit 1
fi

if [ -n "$list_only" ]; then
  say ""
  say "--list-only: no device was opened."
  exit 0
fi

say ""
say "running the shards: a build, then the run, each ..."
: > "$out/runs.tsv"
while IFS="$(printf '\t')" read -r name binary terms; do
  [ -n "$name" ] || continue
  expression=$(python3 "$lane_py" filterset --out "$out" --shard "$name")
  log="$out/shard-$name.log"
  printf '%s\n' "$name" > "$out/current-shard"
  { echo "=== shard $name ==="; echo "$expression"; date; } > "$log"
  # Both halves keep `--workspace --all-features`, although a shard's filterset names one binary
  # and `-p` would build less: `-p` resolves the workspace's features differently, so the binaries
  # it builds are not the ones the listing above built, and the first shard would rebuild the
  # dependency graph. One scope for the listing and both halves is what keeps the target warm.
  #
  # Build first. `--no-run` compiles exactly what the run below executes, so the run starts with
  # nothing to compile and its wall time is the tests' alone. Each shard builds again because a
  # sibling cargo on the same target directory can invalidate it between two shards, and that
  # rebuild is counted as build time.
  built=$(date +%s)
  status=0
  ( cd "$repo" \
    && CARGO_TARGET_DIR="$cfg_target" \
       RUSTFLAGS="--cfg m2v_gpu" \
       cargo nextest run --no-run --workspace --all-features $profile_args \
         --hide-progress-bar -E "$expression" ) >> "$log" 2>&1 || status=$?
  build_wall=$(( $(date +%s) - built ))
  if [ "$status" -ne 0 ]; then
    printf '%s\t%s\t%s\t%s\n' "$name" "$status" "$build_wall" 0 >> "$out/runs.tsv"
    say "  $name  BUILD FAILED exit=$status  ${build_wall}s (no device opened)"
    continue
  fi
  started=$(date +%s)
  ( cd "$repo" \
    && CARGO_TARGET_DIR="$cfg_target" \
       RUSTFLAGS="--cfg m2v_gpu" \
       cargo nextest run --workspace --all-features $profile_args \
         --no-fail-fast --hide-progress-bar --failure-output immediate-final \
         --success-output never -j "$jobs" -E "$expression" ) >> "$log" 2>&1 || status=$?
  wall=$(( $(date +%s) - started ))
  printf '%s\t%s\t%s\t%s\n' "$name" "$status" "$build_wall" "$wall" >> "$out/runs.tsv"
  say "  $name  exit=$status  build ${build_wall}s  run ${wall}s"
done < "$out/shards.tsv"
printf 'DONE\n' > "$out/current-shard"

tally=0
python3 "$lane_py" tally --out "$out" | tee -a "$report" || tally=$?
say ""
say "logs and listings: $out"
exit "$tally"
