Files
leleka/tools/kernel-ab/aa.sh
T
Pavlo RatushnyiandClaude Sonnet 5.5 dcb2f3dbbd feat(kernel-ab): C++ driver time mode, aa.sh A/A control (STRA-317)
kab time: monotonic ns + TSC slices with a dependent-add clock calibration before and
after each slice (tq_cpu_parity --bench method; slices whose clock moved >5 percent are
dropped, threshold from tq_cpu_parity.cpp:303), RESIDENT and STREAMED regimes, pinned
single-thread pool, 4096-aligned buffers, manifest and case input hashes, effective
environment. aa.sh: seeded schedule, N rounds of two fresh processes, per-round ratios
only. time_smoke.sh runs the acceptance commands. Only tools/kernel-ab/ is touched.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 20:40:44 +01:00

145 lines
8.4 KiB
Bash
Executable File

#!/usr/bin/env bash
# tools/kernel-ab/aa.sh - STRA-317 (S0.8a2): the C++ A/A control of the CPU kernel A/B timing.
#
# bash tools/kernel-ab/aa.sh D <case> <rounds> <seed> <cpu>
#
# D a KAB1 run directory written by `kab gen` (STRA-248); never written to (an extra file would make verify_manifest.py refuse it)
# case case id, e.g. 18-20-r1
# rounds number of rounds (30 for the A/A control of the plan)
# seed integer; writes the order schedule BEFORE the first run (balanced: half of the rounds "a first", half "b first", shuffled by the seed)
# cpu the logical CPU both processes are pinned to (a physical core whose SMT sibling is idle)
#
# One round = two FRESH `kab time` processes of the SAME binary, labelled a and b, run one after the other in the scheduled order,
# both pinned to <cpu>, STRATA_* / LELEKA_* scrubbed from their environment (the cell avx2 sets only STRATA_FORCE_AVX2=1). Per round
# and regime the ratio is median slice ns of b / median slice ns of a (the same statistic the Rust/C++ comparison uses). Only the
# ratios are written: NO verdict and no class (the A/A class is computed later by the S0.10b classifier, STRA-313).
#
# Output (default: next to D, never inside it): <dirname D>/aa-<basename D>-<case>-s<seed>/
# schedule.tsv written first: round<TAB>first (a|b)<TAB>pin<TAB>cell
# rounds/rNN-a.json, rNN-b.json the full `kab time` records
# ratios.tsv "#" comment lines (the column header is one of them), then EXACTLY <rounds> data lines:
# round first ratio_resident ratio_streamed median_ns_a_resident median_ns_b_resident median_ns_a_streamed median_ns_b_streamed
# kept_a_resident kept_b_resident kept_a_streamed kept_b_streamed dropped_total
#
# Environment: KAB (binary; default $E2E_ROOT/build/kernel-ab/kab) E2E_ROOT (default $HOME/work/leleka-e2e)
# AA_CELL avx512|avx2 (default avx512) AA_SLICES (default 50) AA_SLICE_MS (default: kab's 60) AA_OUT (output dir)
# PYTHON (default python3; stdlib only, offline arithmetic and JSON reading)
# CPU only, no GPU, nothing installed. Timing taken on a shared host is noisy and is not evidence by itself: each record carries the
# load average and the SMT sibling's busy fraction.
set -euo pipefail
if [ "$#" -ne 5 ]; then
echo "usage: bash tools/kernel-ab/aa.sh D <case> <rounds> <seed> <cpu>" >&2
exit 2
fi
d="${1%/}"; cas="$2"; rounds="$3"; seed="$4"; cpu="$5"
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo="$(cd "${here}/../.." && pwd)"
root="${E2E_ROOT:-${HOME}/work/leleka-e2e}"
kab="${KAB:-${root}/build/kernel-ab/kab}"
cell="${AA_CELL:-avx512}"
slices="${AA_SLICES:-50}"
py="${PYTHON:-python3}"
export PYTHONDONTWRITEBYTECODE=1
case "${rounds}" in ''|*[!0-9]*) echo "aa.sh: rounds must be a positive integer" >&2; exit 2;; esac
case "${seed}" in ''|*[!0-9]*) echo "aa.sh: seed must be a non-negative integer" >&2; exit 2;; esac
case "${cpu}" in ''|*[!0-9]*) echo "aa.sh: cpu must be a logical CPU number" >&2; exit 2;; esac
[ "${rounds}" -ge 1 ] || { echo "aa.sh: rounds must be >= 1" >&2; exit 2; }
case "${cell}" in avx512|avx2) ;; *) echo "aa.sh: AA_CELL must be avx512 or avx2" >&2; exit 2;; esac
[ -f "${d}/manifest.json" ] || { echo "aa.sh: ${d} has no manifest.json (not a complete KAB1 run directory)" >&2; exit 2; }
[ -f "${d}/case-${cas}.in" ] || { echo "aa.sh: ${d}/case-${cas}.in does not exist" >&2; exit 2; }
[ -x "${kab}" ] || { echo "aa.sh: ${kab} is not an executable (build with make -C tools/kernel-ab/cpp BUILD=...)" >&2; exit 2; }
dabs="$(cd "${d}" && pwd)"
out="${AA_OUT:-$(dirname "${dabs}")/aa-$(basename "${dabs}")-${cas}-s${seed}}"
case "${out}/" in "${repo}/"*) echo "aa.sh: output directory ${out} is inside the repository" >&2; exit 1;; esac
case "${out}/" in "${dabs}/"*) echo "aa.sh: output directory ${out} is inside the KAB1 run directory" >&2; exit 1;; esac
[ ! -e "${out}" ] || { echo "aa.sh: ${out} exists; remove it or set AA_OUT" >&2; exit 1; }
mkdir -p "${out}/rounds"
# ---- the schedule, written BEFORE the first run -------------------------------------------------------------------------------
"${py}" -I - "${rounds}" "${seed}" "${cpu}" "${cell}" > "${out}/schedule.tsv" <<'PY'
import sys
rounds, seed, cpu, cell = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3], sys.argv[4]
M = (1 << 64) - 1
state = seed & M
def nxt(): # SplitMix64: the same sequence on every host and Python version
global state
state = (state + 0x9E3779B97F4A7C15) & M
z = state
z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M
z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M
return z ^ (z >> 31)
order = ["a"] * ((rounds + 1) // 2) + ["b"] * (rounds // 2) # balanced
for i in range(len(order) - 1, 0, -1): # Fisher-Yates
j = nxt() % (i + 1)
order[i], order[j] = order[j], order[i]
print("# seed=%d rounds=%d (balanced: %d a-first, %d b-first)" % (seed, rounds, order.count("a"), order.count("b")))
print("round\tfirst\tpin\tcell")
for r, f in enumerate(order, 1):
print("%d\t%s\t%s\t%s" % (r, f, cpu, cell))
PY
echo "aa: schedule written to ${out}/schedule.tsv"
# ---- the scrubbed environment of the cell -------------------------------------------------------------------------------------
scrub=()
while IFS= read -r v; do scrub+=(-u "$v"); done < <(compgen -e | grep -E '^(STRATA_|LELEKA_)' || true)
cellenv=()
[ "${cell}" = "avx2" ] && cellenv=(STRATA_FORCE_AVX2=1)
extra=()
[ -z "${AA_SLICE_MS:-}" ] || extra=(--slice-ms "${AA_SLICE_MS}")
run_one() { # <round> <label>
local r label f
r="$(printf '%02d' "$1")"; label="$2"; f="${out}/rounds/r${r}-${label}.json"
env ${scrub[@]+"${scrub[@]}"} ${cellenv[@]+"${cellenv[@]}"} "${kab}" time --run-dir "${dabs}" --case "${cas}" --slices "${slices}" --pin "${cpu}" \
--out "${f}" ${extra[@]+"${extra[@]}"} > "${out}/rounds/r${r}-${label}.log" 2>&1 \
|| { echo "aa.sh: round ${r} process ${label} failed:" >&2; cat "${out}/rounds/r${r}-${label}.log" >&2; exit 1; }
}
while IFS=$'\t' read -r r first _; do
case "${r}" in '#'*|round) continue;; esac
second=b; [ "${first}" = "b" ] && second=a
run_one "${r}" "${first}"
run_one "${r}" "${second}"
printf 'aa: round %s done (%s first)\n' "${r}" "${first}"
done < "${out}/schedule.tsv"
# ---- the ratios (arithmetic only) -----------------------------------------------------------------------------------------------
"${py}" -I - "${out}" "${rounds}" "${cas}" "${cell}" "${cpu}" "${slices}" > "${out}/ratios.tsv" <<'PY'
import json, sys
out, rounds, cas, cell, cpu, slices = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6]
sched = {}
for line in open(out + "/schedule.tsv"):
if line.startswith("#") or line.startswith("round"):
continue
p = line.rstrip("\n").split("\t")
sched[int(p[0])] = p[1]
def regimes(path):
d = json.load(open(path))
r = {x["regime"]: x for x in d["regimes"]}
return d, r["RESIDENT"], r["STREAMED"]
print("# KAB1 A/A (C++ vs C++), STRA-317. ratio = median slice ns of process b / process a, per regime. NO verdict and no class here (S0.10b, STRA-313).")
print("# case=%s cell=%s pin=%s slices_per_regime=%s rounds=%d" % (cas, cell, cpu, slices, rounds))
print("# round\tfirst\tratio_resident\tratio_streamed\tmedian_ns_a_resident\tmedian_ns_b_resident\tmedian_ns_a_streamed\tmedian_ns_b_streamed\t"
"kept_a_resident\tkept_b_resident\tkept_a_streamed\tkept_b_streamed\tdropped_total")
for r in range(1, rounds + 1):
da, ra, sa = regimes("%s/rounds/r%02d-a.json" % (out, r))
db, rb, sb = regimes("%s/rounds/r%02d-b.json" % (out, r))
for x in (ra, rb, sa, sb):
if not x["slices_kept"]:
sys.exit("round %d: a regime has no kept slice" % r)
dropped = ra["dropped_count"] + rb["dropped_count"] + sa["dropped_count"] + sb["dropped_count"]
print("%d\t%s\t%.6f\t%.6f\t%.3f\t%.3f\t%.3f\t%.3f\t%d\t%d\t%d\t%d\t%d" % (
r, sched[r], rb["median_ns_per_call"] / ra["median_ns_per_call"], sb["median_ns_per_call"] / sa["median_ns_per_call"],
ra["median_ns_per_call"], rb["median_ns_per_call"], sa["median_ns_per_call"], sb["median_ns_per_call"],
ra["slices_kept"], rb["slices_kept"], sa["slices_kept"], sb["slices_kept"], dropped))
PY
n="$(grep -vc "^#" "${out}/ratios.tsv" || true)"
data="${n}"
[ "${data}" = "${rounds}" ] || { echo "aa.sh: ratios.tsv has ${data} data lines, expected ${rounds}" >&2; exit 1; }
echo "--- ratios.tsv (${data} per-round ratios; no verdict) ---"
cat "${out}/ratios.tsv"
echo "AA OK rounds=${data} out=${out}"