interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / scripts / bench / headstart-aien.sh

904 lines · 47390 bytes Raw Blame History
1#!/usr/bin/env bash
2# SPDX-License-Identifier: Apache-2.0
3# Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# Headstart M0 (#532): reproducible stable-toolchain build baselines for the
18# AIEN monorepo. Measurement only: this script never edits Cargo.toml,
19# rust-toolchain.toml, CI, compiler flags or the caller's checkout.
20#
21# Usage:
22# scripts/bench/headstart-aien.sh [stage ...]
23# Stages (default: setup timings cold incr cleanup):
24# setup create a detached git worktree of HS_COMMIT under HS_WORK, warm
25# the cargo registry (cargo fetch --locked), write manifest.json
26# timings one cold `cargo build --workspace --timings`, extract unit data
27# and the observed critical path (timings/)
28# cold interleaved rounds of the cold scenarios (A/A on cold check)
29# incr 10-step body-only and interface-changing edit series on
30# `cargo check --workspace --all-targets`, reverted and verified
31# summary rebuild summary.json from samples.jsonl
32# cleanup remove the benchmark worktree and its target directory
33# Headstart M5 (#536) A/B stages, for one toolchain run with two arm
34# environments (HS_ARM_ENV_OFF, HS_ARM_ENV_ON, both required):
35# ab interleaved cold check/build/test --no-run, arm OFF vs ON, plus
36# an A/A pair (arms A and B, both with the OFF environment);
37# optional extra cold builds at HS_AB_JOBS job counts
38# abincr the incr edit series with OFF and ON on separate target dirs,
39# both arms built after every edit
40# abverify correctness: normalized diagnostics, exit codes and test
41# results of OFF vs ON, plus one ON build with HS_VERIFY_ENV_ON
42# (writes verify.json)
43#
44# Environment (defaults in brackets): HS_COMMIT [HEAD of this checkout],
45# HS_WORK [$HOME/workspace/headstart-m0-<short>], HS_OUT
46# [benchmarks/data/headstart/baseline-<date>-<short>], HS_SAMPLES [5],
47# HS_LOAD_MAX [2], HS_WAIT_CAP_S [600], HS_MON_INTERVAL_S [3],
48# HS_QUIETLOCK [1], HS_QUIETLOCK_BIN [quietlock], HS_QUIET_WAIT_CAP_S [3600],
49# HS_MAX_RERUNS [2], HS_SLOW_COLD_S [1200], HS_INCR_STEPS [10],
50# HS_INCR_SERIES [2], HS_BODY_FILE, HS_BODY_ANCHOR, HS_IFACE_FILE,
51# HS_EDIT_REASON. Toolchain and A/B knobs: HS_CARGO [cargo], HS_RUSTC
52# [unset: cargo picks rustc], HS_ARM_ENV_OFF, HS_ARM_ENV_ON (space-separated
53# KEY=VALUE words), HS_AB_JOBS [empty], HS_AB_JOBS_SAMPLES [3],
54# HS_VERIFY_TEST_PKGS [spark-harness], HS_VERIFY_ENV_ON [empty]. Quiet-flag
55# hold: HS_HOLD [0], HS_HOLD_OWNER [headstart-runner], HS_HOLD_MINUTES [5],
56# HS_HOLD_REASON [headstart timing sample]. HS_KEEP_LOG [0] keeps full logs.
57# See benchmarks/headstart/README.md.
58set -euo pipefail
59
60SELF_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
61REPO=${HS_REPO:-$(git -C "$SELF_DIR" rev-parse --show-toplevel)}
62SUMMARIZE="$SELF_DIR/headstart-summarize.sh"
63
64HS_COMMIT=$(git -C "$REPO" rev-parse "${HS_COMMIT:-HEAD}")
65SHORT=${HS_COMMIT:0:7}
66HS_WORK=${HS_WORK:-$HOME/workspace/headstart-m0-$SHORT}
67HS_DATE=${HS_DATE:-$(date -u +%Y%m%d)}
68HS_OUT=${HS_OUT:-$REPO/benchmarks/data/headstart/baseline-$HS_DATE-$SHORT}
69HS_SAMPLES=${HS_SAMPLES:-5}
70HS_LOAD_MAX=${HS_LOAD_MAX:-2}
71HS_WAIT_CAP_S=${HS_WAIT_CAP_S:-600}
72HS_MON_INTERVAL_S=${HS_MON_INTERVAL_S:-3}
73HS_MAX_RERUNS=${HS_MAX_RERUNS:-2}
74HS_SLOW_COLD_S=${HS_SLOW_COLD_S:-1200}
75HS_INCR_STEPS=${HS_INCR_STEPS:-10}
76HS_INCR_SERIES=${HS_INCR_SERIES:-2}
77HS_QUIETLOCK=${HS_QUIETLOCK:-1}
78HS_QUIETLOCK_BIN=${HS_QUIETLOCK_BIN:-quietlock}
79HS_QUIET_WAIT_CAP_S=${HS_QUIET_WAIT_CAP_S:-3600}
80# Per-sample hold of the quiet flag (HS_HOLD=1): take it after the queue wait,
81# keep it through the load wait and the timed command, release it after.
82HS_HOLD=${HS_HOLD:-0}
83HS_HOLD_OWNER=${HS_HOLD_OWNER:-headstart-runner}
84HS_HOLD_MINUTES=${HS_HOLD_MINUTES:-5}
85HS_HOLD_REASON=${HS_HOLD_REASON:-headstart timing sample}
86# Edit targets (repo-relative paths). The anchor is a fixed string that must
87# match exactly one line, the opening line of a function body.
88HS_BODY_FILE=${HS_BODY_FILE:-}
89HS_BODY_ANCHOR=${HS_BODY_ANCHOR:-}
90HS_IFACE_FILE=${HS_IFACE_FILE:-}
91HS_EDIT_REASON=${HS_EDIT_REASON:-}
92# Toolchain under test. HS_CARGO replaces the leading `cargo` of every
93# scenario command; HS_RUSTC, when set, is exported as RUSTC to each sample.
94HS_CARGO=${HS_CARGO:-cargo}
95HS_RUSTC=${HS_RUSTC:-}
96HS_AB_JOBS=${HS_AB_JOBS:-}
97HS_AB_JOBS_SAMPLES=${HS_AB_JOBS_SAMPLES:-3}
98HS_VERIFY_TEST_PKGS=${HS_VERIFY_TEST_PKGS:-spark-harness}
99HS_VERIFY_ENV_ON=${HS_VERIFY_ENV_ON:-}
100
101SRC="$HS_WORK/src"
102TARGET="$HS_WORK/target"
103RAWLOG="$HS_WORK/logs"
104SAMPLES="$HS_OUT/samples.jsonl"
105MANIFEST="$HS_OUT/manifest.json"
106RUN_ID=${HS_RUN_ID:-headstart-m0-$HS_DATE-$SHORT}
107TIME_BIN=/usr/bin/time
108MON_PID=""
109EDITED_FILE=""
110HOLD_PID=""
111HOLD_FILE=""
112
113say() { printf '[headstart %s] %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
114die() { say "ABORT: $*"; exit 1; }
115
116# Release a per-sample quiet-flag hold (see hold_acquire): removing the want
117# file ends the held waiter, and quietlock releases the flag when it exits.
118hold_release() {
119 [ -n "$HOLD_PID" ] || return 0
120 rm -f "$HOLD_FILE.want"
121 wait "$HOLD_PID" 2>/dev/null || true
122 HOLD_PID=""
123 rm -f "$HOLD_FILE"
124}
125
126cleanup_on_exit() {
127 local rc=$?
128 [ -n "$MON_PID" ] && kill "$MON_PID" 2>/dev/null || true
129 hold_release
130 if [ -n "$EDITED_FILE" ] && [ -d "$SRC" ]; then
131 git -C "$SRC" checkout -- "$EDITED_FILE" 2>/dev/null || true
132 say "reverted in-flight edit of $EDITED_FILE"
133 fi
134 exit "$rc"
135}
136trap cleanup_on_exit EXIT
137trap 'exit 130' INT TERM
138
139need() { command -v "$1" >/dev/null 2>&1 || die "missing required tool: $1"; }
140need git; need jq; need awk; need sed; need "$HS_CARGO"; need pgrep; need sha256sum
141
142now_ns() { date +%s%N; }
143secs_between() { awk -v a="$1" -v b="$2" 'BEGIN { printf "%.3f", (b - a) / 1e9 }'; }
144loadavg_json() { awk '{ printf "[%s,%s,%s]", $1, $2, $3 }' /proc/loadavg; }
145load1() { awk '{ print $1 }' /proc/loadavg; }
146mem_avail_kb() { awk '/^MemAvailable:/ { print $2 }' /proc/meminfo; }
147
148# PIDs of this runner and every descendant (our own cargo/rustc).
149own_pids() {
150 ps -e -o pid=,ppid= | awk -v root="$$" '
151 { parent[$1] = $2; pids[NR] = $1 }
152 END {
153 own[root] = 1; changed = 1
154 while (changed) { changed = 0
155 for (i in pids) { p = pids[i]; if (!(p in own) && (parent[p] in own)) { own[p] = 1; changed = 1 } } }
156 for (p in own) print p
157 }'
158}
159
160# Foreign rustc/cargo/clippy-driver/rustdoc processes as a JSON array of
161# "pid:comm:crate" strings. Excludes our process tree and anything whose
162# command line mentions our work directory.
163foreign_json() {
164 local own line pid comm crate out=()
165 own=" $(own_pids | tr '\n' ' ') "
166 while read -r pid; do
167 [ -n "$pid" ] || continue
168 case "$own" in *" $pid "*) continue ;; esac
169 comm=$(cat "/proc/$pid/comm" 2>/dev/null || true)
170 [ -n "$comm" ] || continue
171 line=$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null || true)
172 case "$line" in *"$HS_WORK"*) continue ;; esac
173 crate=$(printf '%s' "$line" | sed -n 's/.*--crate-name \([^ ]*\).*/\1/p')
174 # A compiler process counts only when it compiles a crate; this skips
175 # idle probes such as an orphaned `rustc --version`.
176 [ "$comm" != cargo ] && [ -z "$crate" ] && continue
177 out+=("$pid:$comm:${crate:--}")
178 done < <(pgrep -x 'rustc|cargo|clippy-driver|rustdoc' || true)
179 if [ ${#out[@]} -eq 0 ]; then echo '[]'; else printf '%s\n' "${out[@]}" | head -40 | jq -R . | jq -cs .; fi
180}
181
182# Respect the host's shared quiet flag (`quietlock check` exits non-zero while
183# another job holds it for a quiet measurement). Capped at HS_QUIET_WAIT_CAP_S
184# so a stale flag cannot hang the run; a capped wait is logged and the sample
185# is marked contaminated. Prints "<waited_s> <capped> <checked>", where
186# checked is false when the check is disabled or quietlock is not installed.
187quietlock_available() { [ "$HS_QUIETLOCK" = 1 ] && command -v "$HS_QUIETLOCK_BIN" >/dev/null 2>&1; }
188wait_quietlock() {
189 local start waited
190 start=$(date +%s)
191 if ! quietlock_available; then echo "0 false false"; return; fi
192 while ! "$HS_QUIETLOCK_BIN" check >/dev/null 2>&1; do
193 waited=$(( $(date +%s) - start ))
194 if [ "$waited" -ge "$HS_QUIET_WAIT_CAP_S" ]; then
195 say "quiet flag still held after ${waited}s (cap ${HS_QUIET_WAIT_CAP_S}s): proceeding, sample marked contaminated"
196 echo "$waited true true"; return
197 fi
198 sleep 5
199 done
200 echo "$(( $(date +%s) - start )) false true"
201}
202
203# hold_acquire: with HS_HOLD=1, take the quiet flag for one sample with
204# `quietlock hold`. The held command is a small waiter that writes the hold id
205# to $HOLD_FILE, then waits until hold_release removes $HOLD_FILE.want (or
206# this runner dies). A refusal (exit 75: someone took the flag after our
207# queue wait) queues again behind the holder, within HS_QUIET_WAIT_CAP_S.
208# Sets HOLD_HELD (true|false), HOLD_ID, HOLD_S and HOLD_REFUSED; it must not
209# run in a subshell, because the waiter has to outlive this call.
210hold_acquire() {
211 local start rc waited
212 HOLD_HELD=false; HOLD_ID=""; HOLD_S=0; HOLD_REFUSED=0
213 [ "$HS_HOLD" = 1 ] && quietlock_available || return 0
214 start=$(date +%s)
215 HOLD_FILE="$RAWLOG/.quiet-hold.$$"
216 while :; do
217 rm -f "$HOLD_FILE"; : > "$HOLD_FILE.want"
218 "$HS_QUIETLOCK_BIN" hold --owner "$HS_HOLD_OWNER" --minutes "$HS_HOLD_MINUTES" --reason "$HS_HOLD_REASON" -- \
219 sh -c 'printf "%s\n" "${QUIETLOCK_HOLD:-unknown}" > "$1"
220 while [ -e "$2" ] && kill -0 "$3" 2>/dev/null; do sleep 0.2; done' \
221 hold-waiter "$HOLD_FILE" "$HOLD_FILE.want" "$$" >> "$RAWLOG/quietlock-hold.log" 2>&1 &
222 HOLD_PID=$!
223 while [ ! -s "$HOLD_FILE" ] && kill -0 "$HOLD_PID" 2>/dev/null; do sleep 0.1; done
224 if [ -s "$HOLD_FILE" ]; then
225 HOLD_HELD=true; HOLD_ID=$(head -1 "$HOLD_FILE"); HOLD_S=$(( $(date +%s) - start )); return 0
226 fi
227 rc=0; wait "$HOLD_PID" || rc=$?
228 HOLD_PID=""; rm -f "$HOLD_FILE.want"
229 HOLD_S=$(( $(date +%s) - start ))
230 if [ "$rc" -ne 75 ]; then
231 say "quietlock hold failed (exit $rc, see $RAWLOG/quietlock-hold.log): sample runs unheld, marked contaminated"
232 return 0
233 fi
234 HOLD_REFUSED=$((HOLD_REFUSED + 1))
235 if [ "$HOLD_S" -ge "$HS_QUIET_WAIT_CAP_S" ]; then
236 say "quiet flag hold refused $HOLD_REFUSED times in ${HOLD_S}s (cap ${HS_QUIET_WAIT_CAP_S}s): sample runs unheld, marked contaminated"
237 return 0
238 fi
239 sleep 1
240 wait_quietlock > /dev/null
241 done
242}
243
244# Files rustc leaves in the worktree root when it panics (internal compiler
245# error). harvest_ice <tail file> appends each report's head (the panic lines,
246# up to the backtrace) to the tail file, removes the reports so the next
247# sample starts clean, and prints how many there were.
248harvest_ice() {
249 local out=$1 n=0 f
250 for f in "$SRC"/rustc-ice-*.txt; do
251 [ -e "$f" ] || continue
252 n=$((n + 1))
253 { printf '== %s (head, up to the backtrace) ==\n' "${f##*/}"
254 awk '/^stack backtrace:/ { exit } NR > 12 { exit } { print }' "$f" | LC_ALL=C tr -cd '\11\12\15\40-\176'
255 } >> "$out"
256 rm -f "$f"
257 done
258 echo "$n"
259}
260
261# Wait until 1-minute loadavg < HS_LOAD_MAX, at most HS_WAIT_CAP_S seconds.
262# Prints "<waited_s> <capped:true|false>".
263wait_quiet() {
264 local start waited
265 start=$(date +%s)
266 while awk -v l="$(load1)" -v m="$HS_LOAD_MAX" 'BEGIN { exit !(l >= m) }'; do
267 waited=$(( $(date +%s) - start ))
268 if [ "$waited" -ge "$HS_WAIT_CAP_S" ]; then echo "$waited true"; return; fi
269 sleep 5
270 done
271 echo "$(( $(date +%s) - start )) false"
272}
273
274# Parse a /usr/bin/time -v report into JSON.
275time_v_json() {
276 local f=$1
277 if [ ! -s "$f" ]; then echo '{"available":false,"reason":"no /usr/bin/time report"}'; return; fi
278 awk -F': ' '
279 /Maximum resident set size/ { rss = $2 }
280 /Percent of CPU this job got/ { cpu = $2; sub(/%/, "", cpu) }
281 /User time \(seconds\)/ { usr = $2 }
282 /System time \(seconds\)/ { sys = $2 }
283 /Elapsed \(wall clock\) time/ { el = $NF }
284 /Exit status/ { ex = $2 }
285 END {
286 if (cpu == "?" || cpu == "") cpu = "null"
287 printf "{\"available\":true,\"max_rss_kb\":%s,\"cpu_percent\":%s,\"user_s\":%s,\"sys_s\":%s,\"elapsed\":\"%s\",\"exit_status\":%s,\"max_rss_scope\":\"ru_maxrss of the waited cargo tree: the largest single process, not a sum (getrusage(2))\"}",
288 (rss == "" ? "null" : rss), cpu, (usr == "" ? "null" : usr), (sys == "" ? "null" : sys), el, (ex == "" ? "null" : ex)
289 }' "$f"
290}
291
292ensure_clean() {
293 local where=$1
294 git -C "$SRC" diff --quiet || die "worktree not clean after $where: $(git -C "$SRC" diff --stat | tail -1)"
295 git -C "$SRC" diff --cached --quiet || die "worktree index not clean after $where"
296}
297
298# Environment words for an arm: HS_ARM_ENV_<arm> (space-separated
299# KEY=VALUE), empty when unset. Arms A and B of the M0 stages have none.
300arm_env() { local v="HS_ARM_ENV_$1"; printf '%s' "${!v:-}"; }
301
302# run_sample <scenario> <arm> <kind> <round> <step> <aa_pair|-> <prep> -- cargo args...
303# prep: "cold" removes the target dir before each attempt, "warm" keeps it.
304# CUR_TARGET (set by a stage) overrides the target dir; CUR_ENV_EXTRA adds
305# environment words after the arm's; HS_KEEP_LOG=1 keeps the full log in
306# $RAWLOG/<sample id>.log for the stage to parse.
307run_sample() {
308 local scenario=$1 arm=$2 kind=$3 round=$4 step=$5 aa=$6 prep=$7
309 shift 8
310 local cmd=("$@") cmdline attempt=0 final tgt=${CUR_TARGET:-$TARGET}
311 cmdline="${cmd[*]}"
312 local runcmd=("${cmd[@]}") envw=() extra=() envline
313 [ "${runcmd[0]}" = cargo ] && runcmd[0]=$HS_CARGO
314 [ -n "$HS_RUSTC" ] && envw+=("RUSTC=$HS_RUSTC")
315 read -ra extra <<< "$(arm_env "$arm") ${CUR_ENV_EXTRA:-}"
316 envw+=("${extra[@]}")
317 envline="${envw[*]}"
318 while :; do
319 attempt=$((attempt + 1))
320 local sid="${scenario}-${arm}-r${round}-s${step}-a${attempt}"
321 [ "$prep" = cold ] && rm -rf "$tgt"
322 local wq waited capped lb la fstart fend mon t0 t1 rc wall tv tf log tail_rel contaminated maxseen ticks memb
323 local qw qwait qcapped qchecked reasons ice
324 qw=$(wait_quietlock); read -r qwait qcapped qchecked <<< "$qw"
325 hold_acquire
326 wq=$(wait_quiet); waited=${wq% *}; capped=${wq#* }
327 lb=$(loadavg_json); memb=$(mem_avail_kb)
328 fstart=$(foreign_json)
329 mon="$RAWLOG/$sid.mon"; : > "$mon"
330 ( while sleep "$HS_MON_INTERVAL_S"; do foreign_json >> "$mon"; done ) &
331 MON_PID=$!
332 tf="$RAWLOG/$sid.time"; log="$RAWLOG/$sid.log"; rm -f "$tf"
333 say "sample $sid: ${cmdline} (waited ${waited}s, load $lb)"
334 t0=$(now_ns)
335 set +e
336 if [ -x "$TIME_BIN" ]; then
337 (cd "$SRC" && CARGO_TARGET_DIR="$tgt" env "${envw[@]}" "$TIME_BIN" -v -o "$tf" "${runcmd[@]}") > "$log" 2>&1
338 else
339 (cd "$SRC" && CARGO_TARGET_DIR="$tgt" env "${envw[@]}" "${runcmd[@]}") > "$log" 2>&1
340 fi
341 rc=$?
342 set -e
343 t1=$(now_ns)
344 fend=$(foreign_json)
345 kill "$MON_PID" 2>/dev/null || true; wait "$MON_PID" 2>/dev/null || true; MON_PID=""
346 hold_release
347 la=$(loadavg_json)
348 wall=$(secs_between "$t0" "$t1")
349 if [ -x "$TIME_BIN" ]; then tv=$(time_v_json "$tf"); else tv='{"available":false,"reason":"/usr/bin/time not found"}'; fi
350 ticks=$(wc -l < "$mon")
351 maxseen=$( { echo "$fstart"; cat "$mon"; echo "$fend"; } | jq -s 'map(length) | max')
352 reasons=$(jq -cn --argjson s "$fstart" --argjson e "$fend" --slurpfile m "$mon" \
353 --argjson lc "$capped" --argjson qc "$qcapped" --arg hr "$HS_HOLD" --argjson hh "$HOLD_HELD" \
354 '[ (if ($s | length) > 0 then "foreign_at_start" else empty end),
355 (if any($m[]; length > 0) then "foreign_during" else empty end),
356 (if ($e | length) > 0 then "foreign_at_end" else empty end),
357 (if $lc then "load_wait_capped" else empty end),
358 (if $qc then "quiet_flag_wait_capped" else empty end),
359 (if $hr == "1" and ($hh | not) then "quiet_hold_not_taken" else empty end) ]')
360 contaminated=false; [ "$reasons" != '[]' ] && contaminated=true
361 tail_rel="logs/$sid.tail.log"
362 local nt=30; [ "$rc" -ne 0 ] && nt=80
363 : > "$HS_OUT/$tail_rel"
364 # A failure's cause can sit far above the last lines (cargo prints its
365 # manifest warnings last), so failed samples keep the error lines first.
366 if [ "$rc" -ne 0 ]; then
367 { echo '== error lines (first 30 of the full log) =='
368 grep -m 30 -E "^error|panicked at|internal compiler error|^thread '|^note: (please attach|compiler flags|we would appreciate)" "$log" || true
369 echo "== last $nt lines =="
370 } | LC_ALL=C tr -cd '\11\12\15\40-\176' >> "$HS_OUT/$tail_rel"
371 fi
372 tail -n "$nt" "$log" | LC_ALL=C tr -cd '\11\12\15\40-\176' >> "$HS_OUT/$tail_rel"
373 ice=$(harvest_ice "$HS_OUT/$tail_rel")
374 final=true
375 if [ "$contaminated" = true ] && [ "$attempt" -le "$HS_MAX_RERUNS" ]; then final=false; fi
376 jq -cn \
377 --arg run_id "$RUN_ID" --arg sid "$sid" --arg scenario "$scenario" --arg arm "$arm" \
378 --arg kind "$kind" --argjson round "$round" --argjson step "$step" --argjson attempt "$attempt" \
379 --arg aa "$aa" --arg prep "$prep" --arg cmdline "$cmdline" --arg cwd "$SRC" --arg target "$tgt" \
380 --arg envline "$envline" --arg cargo_bin "$HS_CARGO" \
381 --arg started "$(date -u -d "@$((t0 / 1000000000))" +%Y-%m-%dT%H:%M:%SZ)" \
382 --argjson wall "$wall" --argjson tv "$tv" --argjson rc "$rc" \
383 --argjson lb "$lb" --argjson la "$la" --argjson waited "$waited" --argjson capped "$capped" \
384 --argjson qwait "$qwait" --argjson qcapped "$qcapped" --argjson qchecked "$qchecked" \
385 --argjson fend "$fend" --argjson reasons "$reasons" --argjson memb "${memb:-null}" --argjson fstart "$fstart" --argjson maxseen "$maxseen" \
386 --argjson ticks "$ticks" --argjson contaminated "$contaminated" --argjson final "$final" \
387 --arg tail "$tail_rel" --arg edit "${HS_CUR_EDIT:-}" --argjson ice "$ice" \
388 --arg hr "$HS_HOLD" --argjson hh "$HOLD_HELD" --arg hid "$HOLD_ID" --argjson hs "$HOLD_S" --argjson hrf "$HOLD_REFUSED" \
389 --slurpfile mon <(cat "$mon") \
390 '{schema: "headstart-sample/v1", run_id: $run_id, sample_id: $sid, scenario: $scenario, arm: $arm,
391 kind: $kind, round: $round, step: $step, attempt: $attempt,
392 aa_pair: (if $aa == "-" then null else $aa end), prep: $prep, edit: (if $edit == "" then null else $edit end),
393 command: $cmdline, cwd: $cwd, cargo_target_dir: $target, started_at: $started,
394 cargo_bin: $cargo_bin, env_words: $envline,
395 wall_s: $wall, time_v: $tv, exit_status: $rc, ok: ($rc == 0),
396 loadavg_before: $lb, loadavg_after: $la,
397 quiet_flag_checked: $qchecked, quiet_flag_wait_s: $qwait, quiet_flag_wait_capped: $qcapped,
398 quiet_hold: {requested: ($hr == "1"), held: $hh, id: (if $hid == "" then null else $hid end),
399 acquire_s: $hs, refused: $hrf},
400 load_wait_s: $waited, load_wait_capped: $capped,
401 mem_available_kb_before: $memb,
402 foreign: {at_start: $fstart, at_end: $fend, monitor_ticks: $ticks, max_seen: $maxseen,
403 seen: ([$fstart[], ($mon[] | .[]), $fend[]] | unique | .[0:40])},
404 contaminated: $contaminated, contamination_reasons: $reasons, ice_reports: $ice,
405 final: $final, log_tail: $tail}' >> "$SAMPLES"
406 [ "${HS_KEEP_LOG:-0}" = 1 ] || rm -f "$log"
407 LAST_LOG=$log
408 say " -> rc=$rc wall=${wall}s contaminated=$contaminated final=$final"
409 LAST_WALL=$wall
410 LAST_RC=$rc
411 [ "$final" = true ] && break
412 done
413}
414
415# ---------------------------------------------------------------- stages
416
417stage_setup() {
418 say "setup: commit $HS_COMMIT, work $HS_WORK, out $HS_OUT"
419 [ -x "$TIME_BIN" ] || say "WARNING: $TIME_BIN not found; max RSS and CPU% will be recorded as unavailable"
420 case "$HS_WORK/" in "$REPO/"*) die "HS_WORK must be outside the checkout ($REPO)";; esac
421 mkdir -p "$HS_WORK" "$RAWLOG" "$HS_OUT/logs" "$HS_OUT/timings"
422 if [ ! -d "$SRC/.git" ] && [ ! -f "$SRC/.git" ]; then
423 git -C "$REPO" worktree add --detach "$SRC" "$HS_COMMIT" >&2
424 fi
425 [ "$(git -C "$SRC" rev-parse HEAD)" = "$HS_COMMIT" ] || die "worktree HEAD is not $HS_COMMIT"
426 ensure_clean setup
427 local df_line t0 t1 frc
428 df_line=$(df -h "$HS_WORK" | tail -1)
429 say "disk: $df_line"
430 t0=$(now_ns)
431 set +e
432 (cd "$SRC" && "$HS_CARGO" fetch --locked) > "$RAWLOG/fetch.log" 2>&1
433 frc=$?
434 set -e
435 t1=$(now_ns)
436 [ "$frc" -eq 0 ] || die "cargo fetch --locked failed (rc=$frc), see $RAWLOG/fetch.log"
437 local rustc_vv cargo_v cpu_models cfgs
438 rustc_vv=$(cd "$SRC" && "${HS_RUSTC:-rustc}" -vV)
439 cargo_v=$(cd "$SRC" && "$HS_CARGO" -V)
440 cpu_models=$(lscpu 2>/dev/null | awk -F': *' '/^Model name/ { print $2 }' | jq -R . | jq -cs .)
441 cfgs=$(for f in "$HOME/.cargo/config.toml" "$HOME/.cargo/config" "$SRC/.cargo/config.toml" "$SRC/.cargo/config"; do
442 if [ -e "$f" ]; then echo "$f"; fi; done | jq -R . | jq -cs .)
443 jq -n \
444 --arg run_id "$RUN_ID" --arg commit "$HS_COMMIT" --arg short "$SHORT" \
445 --arg origin "$(git -C "$REPO" remote get-url origin 2>/dev/null || echo unknown)" \
446 --arg src "$SRC" --arg target "$TARGET" --arg rustc_vv "$rustc_vv" --arg cargo_v "$cargo_v" \
447 --arg toolchain_file "$(cat "$SRC/rust-toolchain.toml" 2>/dev/null || echo '<absent>')" \
448 --arg arch "$(uname -m)" --arg kernel "$(uname -r)" --argjson nproc "$(nproc)" \
449 --argjson memtotal "$(awk '/^MemTotal:/ { print $2 }' /proc/meminfo)" --argjson memavail "$(mem_avail_kb)" \
450 --argjson cpu_models "$cpu_models" --argjson cfgs "$cfgs" --arg df "$df_line" \
451 --arg date "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --argjson fetch_s "$(secs_between "$t0" "$t1")" \
452 --arg rustflags "${RUSTFLAGS-<unset>}" --arg wrapper "${RUSTC_WRAPPER-<unset>}" \
453 --arg jobs_env "${CARGO_BUILD_JOBS-<unset>}" --arg incr_env "${CARGO_INCREMENTAL-<unset>}" \
454 --argjson time_v "$([ -x "$TIME_BIN" ] && echo true || echo false)" \
455 --argjson samples "$HS_SAMPLES" --argjson loadmax "$HS_LOAD_MAX" --argjson waitcap "$HS_WAIT_CAP_S" \
456 --argjson mon "$HS_MON_INTERVAL_S" --argjson reruns "$HS_MAX_RERUNS" --argjson slow "$HS_SLOW_COLD_S" \
457 '{schema: "headstart-manifest/v1", run_id: $run_id, created_at: $date,
458 source: {commit: $commit, short: $short, origin: $origin, worktree: $src,
459 worktree_kind: "git worktree add --detach (outside the caller checkout)"},
460 toolchain: {rustc_vV: $rustc_vv, cargo_V: $cargo_v, rust_toolchain_toml: $toolchain_file,
461 cargo_config_files: $cfgs,
462 env: {RUSTFLAGS: $rustflags, RUSTC_WRAPPER: $wrapper, CARGO_BUILD_JOBS: $jobs_env, CARGO_INCREMENTAL: $incr_env}},
463 host: {arch: $arch, kernel: $kernel, nproc: $nproc, cpu_models: $cpu_models,
464 mem_total_kb: $memtotal, mem_available_kb_at_setup: $memavail, disk_at_setup: $df},
465 build: {features: "default (no --features / --all-features / --no-default-features flags)",
466 profiles: {check: "dev", build: "dev", "test --no-run": "test (inherits dev)"},
467 target_dir: $target, jobs: "cargo default (-j not passed, CARGO_BUILD_JOBS as recorded) = nproc",
468 cold_definition: "CARGO_TARGET_DIR removed before every cold attempt; ~/.cargo/registry and ~/.cargo/git kept warm",
469 registry_cache: {state: "warm", how: "cargo fetch --locked ran once in setup before any sample", fetch_wall_s: $fetch_s}},
470 protocol: {samples_per_scenario: $samples, load1_max: $loadmax, load_wait_cap_s: $waitcap,
471 foreign_monitor_interval_s: $mon, max_reruns_when_contaminated: $reruns,
472 slow_cold_threshold_s: $slow,
473 foreign_definition: "cargo processes, or rustc / clippy-driver / rustdoc processes with --crate-name (an actual compile), outside this runner process tree and whose command line does not mention the benchmark work dir",
474 contaminated_definition: "any of: a foreign process at sample start, at any monitor tick or in the end-of-sample snapshot; the load wait hit its cap; the quiet-flag wait hit its cap (see contamination_reasons)",
475 time_v_available: $time_v},
476 scenarios: [], stages: []}' > "$MANIFEST"
477 record_binaries
478 say "manifest written: $MANIFEST"
479}
480
481# sha256 of the cargo and rustc under test. rustc is a small launcher; the
482# compiler itself is lib/librustc_driver-*.so in its sysroot, so that is
483# digested too.
484record_binaries() {
485 local cbin rbin sysroot drv files=()
486 cbin=$(command -v "$HS_CARGO")
487 rbin=$(command -v "${HS_RUSTC:-rustc}")
488 sysroot=$(cd "$SRC" && "${HS_RUSTC:-rustc}" --print sysroot 2>/dev/null || true)
489 files=("$cbin" "$rbin")
490 for drv in "$sysroot"/lib/librustc_driver-*.so; do [ -e "$drv" ] && files+=("$drv"); done
491 manifest_add '.toolchain.binaries = {cargo: $c, rustc: $r, sysroot: $s,
492 sha256: ($sums | split("\n") | map(select(length > 0) | split(" ") | {key: .[1], value: .[0]}) | from_entries),
493 arm_env: {OFF: $off, ON: $on}, verify_env_on: $ver,
494 note: "with HS_RUSTC unset, rustc is the rustup proxy and sysroot the toolchain selected by rust-toolchain.toml"}' \
495 --arg c "$cbin" --arg r "$rbin" --arg s "$sysroot" --arg sums "$(sha256sum "${files[@]}")" \
496 --arg off "$(arm_env OFF)" --arg on "$(arm_env ON)" --arg ver "$HS_VERIFY_ENV_ON"
497}
498
499manifest_add() { # manifest_add <jq filter> [jq args...]
500 local filter=$1; shift
501 local tmp="$MANIFEST.tmp"
502 jq "$@" "$filter" "$MANIFEST" > "$tmp" && mv "$tmp" "$MANIFEST"
503}
504
505stage_begin() {
506 manifest_add '.stages += [{stage: $s, started_at: $t, script: "scripts/bench/headstart-aien.sh"}]' \
507 --arg s "$1" --arg t "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
508}
509stage_end() {
510 manifest_add '(.stages[] | select(.stage == $s and .ended_at == null)) |= . + {ended_at: $t}' \
511 --arg s "$1" --arg t "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
512 # Which samples (all stages so far) ran under a per-sample quiet-flag hold.
513 if [ -s "$SAMPLES" ]; then
514 manifest_add '.protocol.quiet_hold += {
515 samples_held: [$x[] | select(.quiet_hold.held == true) | .sample_id],
516 samples_unheld: [$x[] | select(.quiet_hold.held != true) | .sample_id]}' \
517 --slurpfile x "$SAMPLES"
518 fi
519}
520scenario_add() { # scenario_add <id> <kind> <command>
521 manifest_add 'if any(.scenarios[]; .id == $id) then . else .scenarios += [{id: $id, kind: $k, command: $c, cwd: "worktree root"}] end' \
522 --arg id "$1" --arg k "$2" --arg c "$3"
523}
524
525require_setup() {
526 [ -s "$MANIFEST" ] || die "no manifest at $MANIFEST; run the setup stage first"
527 [ -d "$SRC" ] || die "no worktree at $SRC; run the setup stage first"
528 [ "$(git -C "$SRC" rev-parse HEAD)" = "$HS_COMMIT" ] || die "worktree HEAD moved"
529 mkdir -p "$RAWLOG" "$HS_OUT/logs" "$HS_OUT/timings"
530 local qa=false; quietlock_available && qa=true
531 manifest_add '.protocol.quiet_flag = ((.protocol.quiet_flag // {first_stage: $s}) + {
532 enabled: ($q == "1"), tool: $bin, available: $qa, respected: ($q == "1" and $qa),
533 wait_cap_s: $cap,
534 how: "before each sample, wait while `quietlock check` reports the host quiet flag held by another job, at most wait_cap_s; a capped wait is logged and marks the sample contaminated; per-sample quiet_flag_checked / quiet_flag_wait_s / quiet_flag_wait_capped"})' \
535 --arg q "$HS_QUIETLOCK" --arg s "$CUR_STAGE" --arg bin "$HS_QUIETLOCK_BIN" \
536 --argjson qa "$qa" --argjson cap "$HS_QUIET_WAIT_CAP_S"
537 manifest_add '.protocol.quiet_hold = ((.protocol.quiet_hold // {}) + {
538 enabled: ($h == "1"), owner: $o, minutes: $m, reason: $r,
539 how: "with enabled, each sample runs: the quiet_flag queue wait, then `quietlock hold --owner <owner> --minutes <minutes> --reason <reason>` around the load wait and the timed command, released before the next sample; a refused hold queues again (within wait_cap_s); a hold not taken marks the sample contaminated (quiet_hold_not_taken). Per-sample quiet_hold {requested, held, id, acquire_s, refused}; samples_held / samples_unheld list sample ids"})' \
540 --arg h "$HS_HOLD" --arg o "$HS_HOLD_OWNER" --argjson m "$HS_HOLD_MINUTES" --arg r "$HS_HOLD_REASON"
541}
542
543stage_timings() {
544 require_setup; stage_begin timings
545 local c=(cargo build --workspace --timings)
546 scenario_add timings_build_ws timings "${c[*]}"
547 run_sample timings_build_ws A timings 1 0 - cold -- "${c[@]}"
548 ensure_clean timings
549 local html="$TARGET/cargo-timings/cargo-timing.html"
550 if [ "$LAST_RC" -eq 0 ] && [ -s "$html" ]; then
551 "$SUMMARIZE" timings "$html" > "$HS_OUT/timings/units.json"
552 "$SUMMARIZE" critical "$HS_OUT/timings/units.json" "$(nproc)" > "$HS_OUT/timings/critical-path.json"
553 local host
554 host=$(cd "$SRC" && rustc -vV | sed -n 's/^host: //p')
555 (cd "$SRC" && cargo metadata --format-version 1 --filter-platform "$host" --locked --offline) > "$RAWLOG/metadata.json"
556 "$SUMMARIZE" graph "$RAWLOG/metadata.json" > "$HS_OUT/timings/graph.json"
557 "$SUMMARIZE" replay "$HS_OUT/timings/units.json" "$HS_OUT/timings/graph.json" "$(nproc)" > "$HS_OUT/timings/replay.json"
558 say "replay estimate: $(jq -c '{baseline_model_end_s, no_rmeta_wait_model_end_s, realistic_saving_s, model_error_pct}' "$HS_OUT/timings/replay.json")"
559 sed -n 's#.*<td>Max concurrency:</td><td>\(.*\)</td>.*#\1#p; s#.*<td>Total time:</td><td>\(.*\)</td>.*#\1#p' "$html" \
560 | jq -R . | jq -s '{max_concurrency: .[0], total_time: .[1], source: "cargo-timing.html summary table"}' \
561 > "$HS_OUT/timings/report-header.json"
562 gzip -9 -c "$html" > "$HS_OUT/timings/cargo-timing.html.gz"
563 say "critical path: $(jq -r '[.observed.chain[].name] | join(" -> ")' "$HS_OUT/timings/critical-path.json")"
564 else
565 say "timings build failed (rc=$LAST_RC); no critical path extracted"
566 fi
567 stage_end timings
568}
569
570stage_cold() {
571 require_setup; stage_begin cold
572 local ids=(cold_check_ws cold_build_ws cold_test_norun_ws cold_build_spark_harness cold_build_spark_supervisor cold_build_aien_runtime)
573 declare -A cmd=(
574 [cold_check_ws]="cargo check --workspace --all-targets"
575 [cold_build_ws]="cargo build --workspace"
576 [cold_test_norun_ws]="cargo test --workspace --no-run"
577 [cold_build_spark_harness]="cargo build -p spark-harness"
578 [cold_build_spark_supervisor]="cargo build -p spark-supervisor"
579 [cold_build_aien_runtime]="cargo build -p aien-runtime"
580 )
581 local id; for id in "${ids[@]}"; do scenario_add "$id" cold "${cmd[$id]}"; done
582 local n=$HS_SAMPLES round=1
583 while [ "$round" -le "$n" ]; do
584 # A/A: cold_check_ws runs as arms A and B, first and middle of the round,
585 # with the arm order swapped every round. Other scenarios sit between.
586 local first=A second=B
587 [ $((round % 2)) -eq 0 ] && { first=B; second=A; }
588 local order=("cold_check_ws:$first" cold_build_ws cold_build_spark_harness cold_test_norun_ws "cold_check_ws:$second" cold_build_spark_supervisor cold_build_aien_runtime)
589 local item sid arm words
590 for item in "${order[@]}"; do
591 sid=${item%%:*}; arm=A; aa=-
592 if [ "$sid" = cold_check_ws ]; then arm=${item#*:}; aa=cold_check_ws; fi
593 read -ra words <<< "${cmd[$sid]}"
594 run_sample "$sid" "$arm" cold "$round" 0 "$aa" cold -- "${words[@]}"
595 ensure_clean "$sid round $round"
596 case "$sid" in
597 *_ws)
598 if [ "$round" -eq 1 ] && [ "$n" -gt 3 ] && [ "$LAST_RC" -eq 0 ] \
599 && awk -v w="$LAST_WALL" -v s="$HS_SLOW_COLD_S" 'BEGIN { exit !(w > s) }'; then
600 n=3
601 say "cold workspace sample took ${LAST_WALL}s (> ${HS_SLOW_COLD_S}s): reducing to 3 rounds"
602 manifest_add '.protocol.samples_reduced = {to: 3, reason: $r}' \
603 --arg r "$sid took ${LAST_WALL}s in round 1, above slow_cold_threshold_s"
604 fi ;;
605 esac
606 done
607 "$SUMMARIZE" samples "$SAMPLES" > "$HS_OUT/summary.json"
608 round=$((round + 1))
609 done
610 manifest_add '.protocol.cold_rounds_run = $n' --argjson n "$n"
611 stage_end cold
612}
613
614apply_edit() { # apply_edit body|iface <k>
615 local kind=$1 k=$2 f n
616 if [ "$kind" = body ]; then
617 f=$HS_BODY_FILE
618 git -C "$SRC" checkout -- "$f"
619 n=$(grep -nF -- "$HS_BODY_ANCHOR" "$SRC/$f" | cut -d: -f1 || true)
620 [ "$(printf '%s\n' "$n" | grep -c .)" -eq 1 ] || die "body anchor must match exactly one line in $f"
621 sed -i "${n}a\\ let _headstart_m0_probe = std::hint::black_box(${k}u64);" "$SRC/$f"
622 HS_CUR_EDIT="body: $f line $((n + 1)) inserted 'let _headstart_m0_probe = std::hint::black_box(${k}u64);'"
623 else
624 f=$HS_IFACE_FILE
625 git -C "$SRC" checkout -- "$f"
626 printf '\n/// Headstart M0 benchmark probe (never committed).\npub fn headstart_m0_probe_%s() -> u64 {\n %s\n}\n' "$k" "$k" >> "$SRC/$f"
627 HS_CUR_EDIT="iface: $f appended 'pub fn headstart_m0_probe_${k}() -> u64'"
628 fi
629 EDITED_FILE=$f
630 ! git -C "$SRC" diff --quiet || die "edit $kind step $k produced no change"
631}
632
633revert_edit() {
634 [ -n "$EDITED_FILE" ] && git -C "$SRC" checkout -- "$EDITED_FILE"
635 EDITED_FILE=""; HS_CUR_EDIT=""
636}
637
638stage_incr() {
639 require_setup; stage_begin incr
640 [ -n "$HS_BODY_FILE" ] && [ -n "$HS_BODY_ANCHOR" ] && [ -n "$HS_IFACE_FILE" ] \
641 || die "set HS_BODY_FILE, HS_BODY_ANCHOR and HS_IFACE_FILE (see README)"
642 [ -f "$SRC/$HS_BODY_FILE" ] || die "no such file in worktree: $HS_BODY_FILE"
643 [ -f "$SRC/$HS_IFACE_FILE" ] || die "no such file in worktree: $HS_IFACE_FILE"
644 manifest_add '.incremental = {command: "cargo check --workspace --all-targets", steps: $s, series_per_kind: $n,
645 order: "body series, iface series, repeated (ABAB); untimed-for-stats settle check after every revert",
646 body: {file: $bf, anchor: $ba, edit: "insert `let _headstart_m0_probe = std::hint::black_box(<k>u64);` after the anchor line; previous step reverted first"},
647 iface: {file: $if, edit: "append `pub fn headstart_m0_probe_<k>() -> u64 { <k> }` (new pub item, new name every step); previous step reverted first"},
648 reason: $why}' \
649 --argjson s "$HS_INCR_STEPS" --argjson n "$HS_INCR_SERIES" --arg bf "$HS_BODY_FILE" \
650 --arg ba "$HS_BODY_ANCHOR" --arg if "$HS_IFACE_FILE" --arg why "$HS_EDIT_REASON"
651 local c=(cargo check --workspace --all-targets)
652 scenario_add incr_prime prime "${c[*]}"
653 scenario_add incr_noop_check incremental "${c[*]}"
654 scenario_add incr_body_check incremental "${c[*]}"
655 scenario_add incr_iface_check incremental "${c[*]}"
656 scenario_add incr_settle settle "${c[*]}"
657 run_sample incr_prime A prime 0 0 - warm -- "${c[@]}"
658 [ "$LAST_RC" -eq 0 ] || die "prime check failed; incremental scenarios cannot run"
659 local i; for i in 1 2 3; do run_sample incr_noop_check A incremental 0 "$i" - warm -- "${c[@]}"; done
660 ensure_clean "noop"
661 local series kind k settle_step
662 for series in $(seq 1 "$HS_INCR_SERIES"); do
663 settle_step=0
664 for kind in body iface; do
665 settle_step=$((settle_step + 1))
666 for k in $(seq 1 "$HS_INCR_STEPS"); do
667 apply_edit "$kind" "$((series * 100 + k))"
668 run_sample "incr_${kind}_check" A incremental "$series" "$k" - warm -- "${c[@]}"
669 done
670 revert_edit
671 ensure_clean "incr_${kind} series $series"
672 # step 1 = settle after the body series, 2 = after the iface series
673 run_sample incr_settle A settle "$series" "$settle_step" - warm -- "${c[@]}"
674 done
675 done
676 ensure_clean incr
677 "$SUMMARIZE" samples "$SAMPLES" > "$HS_OUT/summary.json"
678 stage_end incr
679}
680
681# ------------------------------------------------ M5 (#536) A/B stages
682# One toolchain, two arm environments. A sample of arm X runs with the words
683# of HS_ARM_ENV_X in its environment and its own target dir ($TARGET-X), so
684# the arms never share build state.
685
686require_ab_arms() {
687 [ -n "$(arm_env OFF)" ] && [ -n "$(arm_env ON)" ] \
688 || die "set HS_ARM_ENV_OFF and HS_ARM_ENV_ON (the A/B stages need both arm environments)"
689 [ "$(arm_env OFF)" != "$(arm_env ON)" ] || die "HS_ARM_ENV_OFF and HS_ARM_ENV_ON are identical"
690}
691
692ab_sample() { # ab_sample <scenario> <arm> <kind> <round> <step> <aa|-> <prep> <target suffix> -- cmd...
693 local scenario=$1 arm=$2 kind=$3 round=$4 step=$5 aa=$6 prep=$7 suffix=$8
694 shift 9
695 CUR_TARGET="$TARGET-$suffix"
696 run_sample "$scenario" "$arm" "$kind" "$round" "$step" "$aa" "$prep" -- "$@"
697 CUR_TARGET=""
698}
699
700stage_ab() {
701 require_setup; require_ab_arms; stage_begin ab
702 # The A/A pair runs twice with the OFF environment: the noise floor of the
703 # very toolchain and environment that the ON arm is compared against.
704 HS_ARM_ENV_A=$(arm_env OFF); HS_ARM_ENV_B=$HS_ARM_ENV_A
705 declare -A cmd=(
706 [ab_cold_check_ws]="cargo check --workspace --all-targets"
707 [ab_cold_build_ws]="cargo build --workspace"
708 [ab_cold_test_norun_ws]="cargo test --workspace --no-run"
709 [ab_aa_check_ws]="cargo check --workspace --all-targets"
710 )
711 local id j
712 for id in ab_cold_check_ws ab_cold_build_ws ab_cold_test_norun_ws ab_aa_check_ws; do scenario_add "$id" ab "${cmd[$id]}"; done
713 for j in $HS_AB_JOBS; do
714 case "$j" in *[!0-9]*|"") die "HS_AB_JOBS must list positive integers, got '$j'";; esac
715 cmd[ab_cold_build_ws_j$j]="cargo build --workspace -j $j"
716 scenario_add "ab_cold_build_ws_j$j" ab "${cmd[ab_cold_build_ws_j$j]}"
717 done
718 manifest_add '.protocol.ab = {arms: {OFF: $off, ON: $on, A: $off, B: $off},
719 rounds: $n, jobs_rounds: $jn, jobs: $jobs,
720 order: "per round: check X, build Y, test-no-run X, A/A first, check Y, build X, test-no-run Y, A/A second; round 1 X=OFF Y=ON first=A, swapped every round; job-count builds after the main rounds, OFF/ON order swapped every round",
721 target_dirs: "each arm has its own CARGO_TARGET_DIR (<target>-<arm>), removed before every cold attempt"}' \
722 --arg off "$(arm_env OFF)" --arg on "$(arm_env ON)" --argjson n "$HS_SAMPLES" \
723 --argjson jn "$HS_AB_JOBS_SAMPLES" --arg jobs "$HS_AB_JOBS"
724 local round x y a b item sid arm aa words
725 for round in $(seq 1 "$HS_SAMPLES"); do
726 x=OFF; y=ON; a=A; b=B
727 [ $((round % 2)) -eq 0 ] && { x=ON; y=OFF; a=B; b=A; }
728 for item in "ab_cold_check_ws:$x" "ab_cold_build_ws:$y" "ab_cold_test_norun_ws:$x" "ab_aa_check_ws:$a" \
729 "ab_cold_check_ws:$y" "ab_cold_build_ws:$x" "ab_cold_test_norun_ws:$y" "ab_aa_check_ws:$b"; do
730 sid=${item%%:*}; arm=${item#*:}; aa=-
731 [ "$sid" = ab_aa_check_ws ] && aa=ab_aa_check_ws
732 read -ra words <<< "${cmd[$sid]}"
733 ab_sample "$sid" "$arm" ab "$round" 0 "$aa" cold "$arm" -- "${words[@]}"
734 ensure_clean "$sid $arm round $round"
735 done
736 "$SUMMARIZE" samples "$SAMPLES" > "$HS_OUT/summary.json"
737 done
738 for j in $HS_AB_JOBS; do
739 for round in $(seq 1 "$HS_AB_JOBS_SAMPLES"); do
740 x=OFF; y=ON; [ $((round % 2)) -eq 0 ] && { x=ON; y=OFF; }
741 read -ra words <<< "${cmd[ab_cold_build_ws_j$j]}"
742 for arm in "$x" "$y"; do
743 ab_sample "ab_cold_build_ws_j$j" "$arm" ab "$round" 0 - cold "$arm" -- "${words[@]}"
744 ensure_clean "ab_cold_build_ws_j$j $arm round $round"
745 done
746 done
747 "$SUMMARIZE" samples "$SAMPLES" > "$HS_OUT/summary.json"
748 done
749 rm -rf "$TARGET-OFF" "$TARGET-ON" "$TARGET-A" "$TARGET-B"
750 stage_end ab
751}
752
753stage_abincr() {
754 require_setup; require_ab_arms; stage_begin abincr
755 [ -n "$HS_BODY_FILE" ] && [ -n "$HS_BODY_ANCHOR" ] && [ -n "$HS_IFACE_FILE" ] \
756 || die "set HS_BODY_FILE, HS_BODY_ANCHOR and HS_IFACE_FILE (see README)"
757 [ -f "$SRC/$HS_BODY_FILE" ] || die "no such file in worktree: $HS_BODY_FILE"
758 [ -f "$SRC/$HS_IFACE_FILE" ] || die "no such file in worktree: $HS_IFACE_FILE"
759 manifest_add '.ab_incremental = {command: "cargo check --workspace --all-targets", steps: $s, series_per_kind: $n,
760 order: "prime OFF then ON (each on its own fresh target dir), 3 no-op checks per arm, then body and iface series as in incr; after every edit both arms check the same source, OFF first on odd steps and ON first on even steps; settle check per arm after every revert",
761 body: {file: $bf, anchor: $ba}, iface: {file: $if}, reason: $why,
762 failure_rule: "a failed ON (or OFF) check is recorded with its exit status and log tail and the series continues; it is never counted as a time"}' \
763 --argjson s "$HS_INCR_STEPS" --argjson n "$HS_INCR_SERIES" --arg bf "$HS_BODY_FILE" \
764 --arg ba "$HS_BODY_ANCHOR" --arg if "$HS_IFACE_FILE" --arg why "$HS_EDIT_REASON"
765 local c=(cargo check --workspace --all-targets) arm id
766 for id in abincr_prime abincr_noop_check abincr_body_check abincr_iface_check abincr_settle; do
767 scenario_add "$id" abincr "${c[*]}"
768 done
769 for arm in OFF ON; do
770 rm -rf "$TARGET-incr-$arm"
771 ab_sample abincr_prime "$arm" prime 0 0 - warm "incr-$arm" -- "${c[@]}"
772 if [ "$arm" = OFF ] && [ "$LAST_RC" -ne 0 ]; then die "OFF prime check failed; the A/B incremental stage cannot run"; fi
773 done
774 local i; for i in 1 2 3; do
775 for arm in OFF ON; do ab_sample abincr_noop_check "$arm" incremental 0 "$i" - warm "incr-$arm" -- "${c[@]}"; done
776 done
777 ensure_clean "abincr noop"
778 local series kind k settle_step order
779 for series in $(seq 1 "$HS_INCR_SERIES"); do
780 settle_step=0
781 for kind in body iface; do
782 settle_step=$((settle_step + 1))
783 for k in $(seq 1 "$HS_INCR_STEPS"); do
784 apply_edit "$kind" "$((series * 100 + k))"
785 order="OFF ON"; [ $((k % 2)) -eq 0 ] && order="ON OFF"
786 for arm in $order; do
787 ab_sample "abincr_${kind}_check" "$arm" incremental "$series" "$k" - warm "incr-$arm" -- "${c[@]}"
788 done
789 done
790 revert_edit
791 ensure_clean "abincr_${kind} series $series"
792 for arm in OFF ON; do
793 ab_sample abincr_settle "$arm" settle "$series" "$settle_step" - warm "incr-$arm" -- "${c[@]}"
794 done
795 done
796 done
797 ensure_clean abincr
798 "$SUMMARIZE" samples "$SAMPLES" > "$HS_OUT/summary.json"
799 rm -rf "$TARGET-incr-OFF" "$TARGET-incr-ON"
800 stage_end abincr
801}
802
803# Diagnostics normalized for event order: compiler-message records reduced to
804# level, code, message and primary spans, then sorted (a multiset compare).
805norm_diagnostics() {
806 { grep '^{' "$1" || true; } | jq -c 'select(.reason == "compiler-message") | .message
807 | {level, code: (.code.code // null), message,
808 spans: [.spans[] | select(.is_primary) | {file_name, line_start, column_start}]}' | LC_ALL=C sort
809}
810
811stage_abverify() {
812 require_setup; require_ab_arms; stage_begin abverify
813 local vd="$HS_OUT/verify" arm pkgs=() p
814 mkdir -p "$vd"
815 for p in $HS_VERIFY_TEST_PKGS; do pkgs+=(-p "$p"); done
816 [ ${#pkgs[@]} -gt 0 ] || die "HS_VERIFY_TEST_PKGS is empty"
817 local check=(cargo check --workspace --all-targets --message-format=json)
818 local test=(cargo test "${pkgs[@]}" --lib --bins --tests -- --test-threads=1)
819 scenario_add verify_check_json verify "${check[*]}"
820 scenario_add verify_test verify "${test[*]}"
821 declare -A crc trc
822 HS_KEEP_LOG=1
823 for arm in OFF ON; do
824 rm -rf "$TARGET-verify-$arm"
825 ab_sample verify_check_json "$arm" verify 1 0 - cold "verify-$arm" -- "${check[@]}"
826 crc[$arm]=$LAST_RC
827 norm_diagnostics "$LAST_LOG" > "$vd/diagnostics-$arm.jsonl"
828 { grep '^{' "$LAST_LOG" || true; } | jq -r '.reason' | LC_ALL=C sort | uniq -c | awk '{ print $2, $1 }' > "$vd/message-reasons-$arm.txt"
829 ensure_clean "verify check $arm"
830 ab_sample verify_test "$arm" verify 1 0 - warm "verify-$arm" -- "${test[@]}"
831 trc[$arm]=$LAST_RC
832 { grep -E '^test result:|^error' "$LAST_LOG" || true; } | sed 's/; finished in .*//' > "$vd/test-results-$arm.txt"
833 ensure_clean "verify test $arm"
834 done
835 local vrc=null venv="$HS_VERIFY_ENV_ON"
836 if [ -n "$venv" ]; then
837 scenario_add verify_build_extra verify "cargo build --workspace (ON arm plus HS_VERIFY_ENV_ON)"
838 CUR_ENV_EXTRA=$venv
839 rm -rf "$TARGET-verify-ONX"
840 ab_sample verify_build_extra ON verify 1 0 - cold "verify-ONX" -- cargo build --workspace
841 CUR_ENV_EXTRA=""
842 vrc=$LAST_RC
843 ensure_clean "verify build extra"
844 fi
845 HS_KEEP_LOG=0
846 rm -f "$RAWLOG"/verify_*.log
847 rm -rf "$TARGET-verify-OFF" "$TARGET-verify-ON" "$TARGET-verify-ONX"
848 local d_off d_on
849 d_off=$(sha256sum < "$vd/diagnostics-OFF.jsonl" | cut -d' ' -f1)
850 d_on=$(sha256sum < "$vd/diagnostics-ON.jsonl" | cut -d' ' -f1)
851 jq -n --argjson coff "${crc[OFF]}" --argjson con "${crc[ON]}" --argjson toff "${trc[OFF]}" --argjson ton "${trc[ON]}" \
852 --arg doff "$d_off" --arg don "$d_on" \
853 --argjson noff "$(wc -l < "$vd/diagnostics-OFF.jsonl")" --argjson non "$(wc -l < "$vd/diagnostics-ON.jsonl")" \
854 --rawfile troff "$vd/test-results-OFF.txt" --rawfile tron "$vd/test-results-ON.txt" \
855 --argjson vrc "$vrc" --arg venv "$venv" --arg pk "$HS_VERIFY_TEST_PKGS" \
856 '($troff | split("\n") | map(select(length > 0))) as $tl_off
857 | ($tron | split("\n") | map(select(length > 0))) as $tl_on
858 | {schema: "headstart-verify/v1",
859 check_command: "cargo check --workspace --all-targets --message-format=json",
860 test_command: ("cargo test -p " + ($pk | split(" ") | join(" -p ")) + " --lib --bins --tests -- --test-threads=1 (no doctests: they run rustdoc, which the toolchain under test may not ship)"),
861 normalization: "compiler-message records reduced to {level, code, message, primary spans}, sorted; test result lines with the timing suffix removed",
862 arms: {OFF: {check_exit: $coff, diagnostics: $noff, diagnostics_sha256: $doff, test_exit: $toff, test_results: $tl_off},
863 ON: {check_exit: $con, diagnostics: $non, diagnostics_sha256: $don, test_exit: $ton, test_results: $tl_on}},
864 check_exit_equal: ($coff == $con), diagnostics_equal: ($doff == $don),
865 test_exit_equal: ($toff == $ton), test_results_equal: ($tl_off == $tl_on),
866 verify_build: (if $venv == "" then null else {env: $venv, command: "cargo build --workspace", exit: $vrc} end)}
867 | .verdict = (if .check_exit_equal and .diagnostics_equal and .test_exit_equal and .test_results_equal
868 and (.verify_build == null or .verify_build.exit == 0)
869 and $coff == 0 and $toff == 0 then "match" else "MISMATCH" end)' > "$HS_OUT/verify.json"
870 say "verify: $(jq -c '{verdict, check_exit_equal, diagnostics_equal, test_exit_equal, test_results_equal, verify_build}' "$HS_OUT/verify.json")"
871 stage_end abverify
872}
873
874stage_summary() {
875 "$SUMMARIZE" samples "$SAMPLES" > "$HS_OUT/summary.json"
876 say "summary written: $HS_OUT/summary.json"
877}
878
879stage_cleanup() {
880 say "cleanup: removing $TARGET (and per-arm $TARGET-*) and worktree $SRC"
881 rm -rf "$TARGET" "$TARGET"-*
882 if [ -d "$SRC" ]; then
883 ensure_clean cleanup
884 git -C "$REPO" worktree remove --force "$SRC"
885 fi
886 rm -rf "$RAWLOG"
887 rmdir "$HS_WORK" 2>/dev/null || true
888 [ -s "$MANIFEST" ] && manifest_add '.cleanup = {at: $t, removed: [$w]}' \
889 --arg t "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg w "$HS_WORK"
890 return 0
891}
892
893CUR_STAGE=""
894STAGES=("$@")
895[ ${#STAGES[@]} -gt 0 ] || STAGES=(setup timings cold incr cleanup)
896mkdir -p "$HS_OUT"
897for s in "${STAGES[@]}"; do
898 case "$s" in
899 setup|timings|cold|incr|ab|abincr|abverify|summary|cleanup) CUR_STAGE=$s; "stage_$s" ;;
900 *) die "unknown stage: $s" ;;
901 esac
902done
903[ -s "$SAMPLES" ] && "$SUMMARIZE" samples "$SAMPLES" > "$HS_OUT/summary.json"
904say "done: ${STAGES[*]}"