interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tools / m19r_qualify.sh

557 lines · 26347 bytes Raw Blame History
1#!/bin/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# m19r_qualify.sh -- M19R Gate 1/2 qualification. Permanent receipts are
18# written only on success.
19#
20# tools/m19r_qualify.sh --omega-candidate SHA --physics-candidate SHA
21# [--physics-dir DIR] [--record] [--quick]
22#
23# Needs the GB10 (runs the NVRM/M16/M19 silicon suites and nvidia-smi) and
24# takes /tmp/aien-gb10.lock for the whole build + test section.
25#
26# Checks, in order: both candidates are explicit full 40-hex SHAs equal to
27# HEAD of a clean tree; physics.lock names the physics candidate; clean
28# rebuild; physics suites (nvrm lifecycle, m16 requalify, m16 concurrent);
29# omegatool suites (m15, world lifecycle, m19, and unless --quick the M19R
30# soak); no libcuda linkage or CUDA symbols; hardware probe; evidence/ not
31# changed by the run; every observed gate PASS; exactly 18 passing
32# OMEGA_ACCEL_RESIDENT_ gates and a complete M19 observation; soak criteria
33# (passed, >= 100000 cycles, bytes churned > 2x physical memory, snapshots
34# start/end/post_destroy); candidates re-checked at the end.
35#
36# Output: <evidence-root>/<run-id>/run.json always (plus per-command logs,
37# command.txt, environment.json, stdout.log, stderr.log, verdict.json and a
38# final hashes.sha256); evidence root defaults to $OMEGA/qual-runs, outside
39# build/ which `make clean` removes (--evidence-root DIR to change); the run
40# directory must not exist yet (exit 2) and is never deleted by this script;
41# receipt-preview.json on a full run; with --record the permanent receipt
42# evidence/M19R/<receipt_digest>.json (created exclusively, mode 0444).
43# Exit 0 on PASS or QUICK_PASS, 1 on failure, 2 on bad arguments.
44#
45# The receipt digest is SHA-256 over the canonical JSON of the receipt body
46# (sorted keys, compact, Python json.dumps number/string forms), computed by
47# tools/json_canon.c. Shell + coreutils + git + jq (field reads, string
48# escaping) + that C helper. No Python.
49#
50# The functions below can be sourced (tools/test_m19r_qualify.sh does);
51# main only runs when the file is executed.
52
53M19R_OMEGA=$(cd -P "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
54M19R_PROG=$(basename "${BASH_SOURCE[0]}")
55M19R_CUDA_RE='libcuda(rt)?\.so|\b(cuInit|cuCtx|cuMem|cuStream|cudaMalloc)\b'
56M19R_ERR=
57
58# Records the failure reason; also in a file so failures inside $(...) survive.
59m19r_fail() {
60 M19R_ERR=$1
61 [ -z "${M19R_TMP:-}" ] || printf '%s' "$1" > "$M19R_TMP/error"
62 return 1
63}
64
65# Build tools/json_canon.om into a private directory (not build/, which the
66# qualification's `make clean` removes). Sets JSON_CANON.
67m19r_build_canon() {
68 M19R_TMP=$(mktemp -d "${TMPDIR:-/tmp}/m19r-qualify.XXXXXX") || return 1
69 JSON_CANON=$M19R_TMP/json_canon
70 "$M19R_OMEGA/seed/out/omc" < "$M19R_OMEGA/tools/json_canon.om" > "$JSON_CANON" && chmod +x "$JSON_CANON"
71}
72
73# JSON string literal for arbitrary text.
74m19r_jstr() { jq -n --arg s "$1" '$s'; }
75
76# Strip leading/trailing whitespace (Python str.strip()).
77m19r_strip() {
78 local s=$1
79 s=${s#"${s%%[![:space:]]*}"}
80 s=${s%"${s##*[![:space:]]}"}
81 printf '%s' "$s"
82}
83
84# m19r_cmd CWD LOG ARGS... -- run ARGS in CWD, stdout+stderr to LOG (or to a
85# scratch file when LOG is "-"), newlines normalised as Python text mode does.
86# With M19R_USE_ENV=1 the qualification environment is added. The captured
87# output file is left in M19R_OUT.
88m19r_cmd() {
89 local cwd=$1 log=$2 rc shown
90 shift 2
91 if [ "$log" = - ]; then
92 M19R_OUT=$M19R_TMP/cmd.out; shown=None
93 else
94 M19R_OUT=$log; shown=$log
95 fi
96 if [ "${M19R_USE_ENV:-0}" = 1 ]; then
97 (cd "$cwd" && exec env OMEGA_M19R_CANDIDATE="$M19R_OMEGA_CAND" OMEGA_QUAL_RECORD=1 \
98 PHYSICS_DIR="$M19R_PHYSICS" "$@" 9>&-) 2>&1 | sed -e 's/\r$//' | tr '\r' '\n' > "$M19R_OUT"
99 else
100 (cd "$cwd" && exec "$@" 9>&-) 2>&1 | sed -e 's/\r$//' | tr '\r' '\n' > "$M19R_OUT"
101 fi
102 rc=${PIPESTATUS[0]}
103 [ "$rc" -eq 0 ] || m19r_fail "$1 exited $rc; see $shown"
104}
105
106# m19r_git REPO ARGS... -- git output with surrounding whitespace stripped.
107m19r_git() {
108 local repo=$1
109 shift
110 m19r_cmd "$repo" - git "$@" || return 1
111 M19R_GIT=$(m19r_strip "$(cat "$M19R_OUT")")
112}
113
114m19r_sha_file() { sha256sum < "$1" | cut -d' ' -f1; }
115
116# m19r_must_candidate REPO SHA
117m19r_must_candidate() {
118 local repo=$1 supplied=$2 name
119 name=$(basename "$repo")
120 [[ $supplied =~ ^[0-9a-fA-F]{40}$ ]] || m19r_fail "candidate must be an explicit full 40-hex SHA" || return 1
121 m19r_git "$repo" rev-parse HEAD || return 1
122 [ "${M19R_GIT,,}" = "${supplied,,}" ] || m19r_fail "$name HEAD differs from supplied candidate" || return 1
123 m19r_git "$repo" status --porcelain --untracked-files=normal || return 1
124 [ -z "$M19R_GIT" ] || m19r_fail "$name candidate tree is dirty"
125}
126
127# m19r_write_immutable_receipt TARGET < receipt-json
128# Pretty form (indent 2, ASCII) written O_EXCL, mode 0444, fsync'd.
129m19r_write_immutable_receipt() {
130 local target=$1 pretty
131 mkdir -p "$(dirname "$target")" || m19r_fail "cannot create $(dirname "$target")" || return 1
132 pretty=$(mktemp "${M19R_TMP}/receipt.XXXXXX") || return 1
133 "$JSON_CANON" --pretty > "$pretty" || m19r_fail "receipt is not valid JSON" || return 1
134 "$JSON_CANON" --write-exclusive "$target" < "$pretty" 2> "$pretty.err" ||
135 m19r_fail "$(sed 's/^json_canon: //' "$pretty.err")"
136}
137
138# m19r_events FILE SUITE -- one "suite<TAB>id<TAB>status" line per observed
139# gate: first every "[PASS|FAIL] id" line (the id may follow on a later line
140# after only whitespace), then every "NAME_PASS:" line, FAIL when the word
141# FAIL appears on it.
142m19r_events() {
143 LC_ALL=C awk -v suite="$2" '
144 function gate(line, m, st, id) {
145 if (match(line, /^[ \t\v\f\r]*\[(PASS|FAIL)\][ \t\v\f\r]+[A-Za-z0-9_:-]+/)) {
146 m = substr(line, 1, RLENGTH)
147 sub(/^[ \t\v\f\r]+/, "", m)
148 st = substr(m, 2, 4)
149 id = substr(m, 7)
150 sub(/^[ \t\v\f\r]+/, "", id)
151 print suite "\t" id "\t" st
152 return 1
153 }
154 return 0
155 }
156 { lines[NR] = $0 }
157 END {
158 pending = ""
159 for (i = 1; i <= NR; i++) {
160 line = lines[i]
161 if (pending != "") {
162 if (line ~ /^[ \t\v\f\r]*$/) continue
163 if (match(line, /^[ \t\v\f\r]*[A-Za-z0-9_:-]+/)) {
164 id = substr(line, 1, RLENGTH)
165 sub(/^[ \t\v\f\r]+/, "", id)
166 print suite "\t" id "\t" pending
167 pending = ""
168 continue
169 }
170 pending = ""
171 }
172 if (gate(line)) continue
173 if (match(line, /^[ \t\v\f\r]*\[(PASS|FAIL)\][ \t\v\f\r]*$/))
174 pending = (index(line, "[PASS]") ? "PASS" : "FAIL")
175 }
176 for (i = 1; i <= NR; i++) {
177 line = lines[i]
178 if (line ~ /^[A-Z][A-Z0-9_]+_PASS:/) {
179 name = substr(line, 1, index(line, ":") - 1)
180 st = (line ~ /(^|[^A-Za-z0-9_])FAIL([^A-Za-z0-9_]|$)/) ? "FAIL" : "PASS"
181 print suite "\t" name "\t" st
182 }
183 }
184 }' "$1"
185}
186
187# JSON views of an events TSV (stdin).
188m19r_events_json() {
189 awk -F'\t' 'BEGIN { printf "[" } NR > 1 { printf "," }
190 { printf "{\"suite\":\"%s\",\"id\":\"%s\",\"status\":\"%s\"}", $1, $2, $3 }
191 END { printf "]" }'
192}
193m19r_event_ids_json() {
194 awk -F'\t' 'BEGIN { printf "[" } NR > 1 { printf "," }
195 { printf "\"%s:%s\"", $1, $2 } END { printf "]" }'
196}
197
198# m19r_observed_counts < events-tsv -> {"completed":N,"failed":N,"passed":N}
199m19r_observed_counts() {
200 awk -F'\t' '{ c++ } $3 == "PASS" { p++ } $3 == "FAIL" { f++ }
201 END { printf "{\"completed\":%d,\"failed\":%d,\"passed\":%d}", c, f, p }'
202}
203
204# m19r_require_passed < events-tsv
205m19r_require_passed() {
206 awk -F'\t' '{ n++ } $3 != "PASS" { bad = 1 } END { exit (n == 0 || bad) }' ||
207 m19r_fail "at least one observed gate failed"
208}
209
210# m19r_tagged_json FILE TAG -- the JSON after "TAG:" on every line that starts
211# with it, one per line; each must parse. Fails when there is none.
212m19r_tagged_json() {
213 local file=$1 tag=$2 lines line
214 lines=$(LC_ALL=C awk -v t="$tag:" 'index($0, t) == 1 { print substr($0, length(t) + 1) }' "$file")
215 [ -n "$lines" ] || m19r_fail "missing $tag observation" || return 1
216 while IFS= read -r line; do
217 printf '%s' "$line" | "$JSON_CANON" > /dev/null 2>&1 ||
218 m19r_fail "$tag observation is not valid JSON" || return 1
219 done <<< "$lines"
220 printf '%s\n' "$lines"
221}
222
223m19r_physics_binary() {
224 local physics=$1 output=$2 source=$3 headers
225 headers=$physics/third_party/nvidia-open-580.173.02
226 m19r_cmd "$physics" - gcc -std=gnu11 -O2 -Wall -Wextra -Werror \
227 -I "$physics/nvrm" -I "$physics/m16" \
228 -I "$headers/src/common/sdk/nvidia/inc" \
229 -I "$headers/kernel-open/common/inc" \
230 -I "$headers/kernel-open/nvidia-uvm" \
231 -I "$headers/src/nvidia/arch/nvalloc/unix/include" \
232 "$physics/nvrm/nvrm.c" "$physics/m16/m16_native.c" \
233 "$physics/$source" -o "$output"
234}
235
236m19r_historical() {
237 local list
238 m19r_git "$M19R_OMEGA" ls-files evidence || return 1
239 list=$M19R_GIT
240 if [ -z "$list" ]; then return 0; fi
241 (cd "$M19R_OMEGA" && printf '%s\n' "$list" | xargs -d '\n' sha256sum --) ||
242 m19r_fail "cannot hash historical evidence"
243}
244
245# Everything inside the Python original's try block. Sets R_* for run.json.
246m19r_qualify() {
247 local omega=$M19R_OMEGA physics=$M19R_PHYSICS run_dir=$M19R_RUN_DIR
248 local historical after binary binary_sha name source flag target rc
249 local hardware_raw driver_version hardware hardware_digest all_tsv m19_tsv
250 local m19 soak samples msg manifest manifest_digest counts body receipt_digest
251
252 m19r_must_candidate "$omega" "$M19R_OMEGA_CAND" || return 1
253 m19r_must_candidate "$physics" "$M19R_PHYSICS_CAND" || return 1
254 [ -r "$omega/physics.lock" ] ||
255 m19r_fail "cannot read $omega/physics.lock" || return 1
256 locked=$(m19r_strip "$(cat "$omega/physics.lock")")
257 [ "${locked,,}" = "${M19R_PHYSICS_CAND,,}" ] ||
258 m19r_fail "physics.lock differs from supplied physics candidate" || return 1
259 historical=$(m19r_historical) || return 1
260
261 exec 9> /tmp/aien-gb10.lock || m19r_fail "cannot open /tmp/aien-gb10.lock" || return 1
262 flock -x 9
263 m19r_locked_section
264 rc=$?
265 exec 9>&-
266 [ "$rc" -eq 0 ] || return 1
267
268 after=$(m19r_historical) || return 1
269 [ "$historical" = "$after" ] ||
270 m19r_fail "historical evidence changed during qualification" || return 1
271
272 all_tsv=$M19R_TMP/events.tsv
273 : > "$all_tsv"
274 for name in "${M19R_SUITES[@]}"; do
275 m19r_events "$run_dir/$name.log" "$name" >> "$all_tsv"
276 done
277 m19r_require_passed < "$all_tsv" || return 1
278 manifest="{\"commands\":[\"nvrm/lifecycle_gates\",\"m16/m16_requalify\",\"m16/m16_concurrent\",\"omega/m15\",\"omega/world_lifecycle\",\"omega/m19\",\"omega/m19r_soak\"],\"observed_test_ids\":$(m19r_event_ids_json < "$all_tsv")}"
279 manifest_digest=$(printf '%s' "$manifest" | "$JSON_CANON" --sha256) || return 1
280 m19=$(m19r_tagged_json "$run_dir/m19.log" M19_OBSERVED_JSON) || return 1
281 m19=$(printf '%s\n' "$m19" | tail -n 1)
282 m19_tsv=$(m19r_events "$run_dir/m19.log" m19 | awk -F'\t' 'index($2, "OMEGA_ACCEL_RESIDENT_") == 1')
283 if [ "$(printf '%s' "$m19_tsv" | grep -c .)" -ne 18 ] || printf '%s\n' "$m19_tsv" | awk -F'\t' '$3 != "PASS" { f = 1 } END { exit !f }'; then
284 m19r_fail "M19 printed gate results do not contain exactly 18 passing gates"; return 1
285 fi
286 msg=$(printf '%s' "$m19" | jq -r '
287 def k($n): if has($n) then .[$n] else error("'"'"'\($n)'"'"'") end;
288 try (if (k("m19_gates_completed") != 18)
289 or (k("m19_gates_passed") != k("m19_gates_completed"))
290 or (k("regression_gates_passed") != k("regression_gates_completed"))
291 then "M19 did not complete all 18 gates and regressions" else "" end)
292 catch (if type == "string" then . else "invalid M19 observation" end)') ||
293 m19r_fail "invalid M19 observation" || return 1
294 [ -z "$msg" ] || m19r_fail "$msg" || return 1
295 R_EVENTS=$(m19r_events_json < "$all_tsv")
296 R_M19=$m19
297 if [ "$M19R_QUICK" = 1 ]; then
298 R_STATUS=QUICK_PASS
299 return 0
300 fi
301
302 soak=$(m19r_tagged_json "$run_dir/m19r_soak.log" M19R_SOAK_JSON) || return 1
303 soak=$(printf '%s\n' "$soak" | tail -n 1)
304 samples=$(m19r_tagged_json "$run_dir/m19r_soak.log" M19R_RESOURCE_JSON) || return 1
305 samples="[$(printf '%s\n' "$samples" | paste -sd, -)]"
306 msg=$(jq -rn --argjson soak "$soak" --argjson samples "$samples" '
307 def k($o; $n): if ($o | has($n)) then $o[$n] else error("'"'"'\($n)'"'"'") end;
308 def falsy: . == null or . == false or . == 0 or . == "" or . == [] or . == {};
309 try (if (k($soak; "passed") | falsy) or (k($soak; "cycles") < 100000)
310 or (k($soak; "bytes_churned") <= 2 * k($soak; "physical_memory_bytes"))
311 or ($samples | length) != 3
312 then "long soak criterion failed"
313 elif [$samples[] | k(.; "phase")] != ["start", "end", "post_destroy"]
314 then "soak resource snapshots are incomplete"
315 else "" end)
316 catch (if type == "string" then . else "invalid soak observation" end)') ||
317 m19r_fail "invalid soak observation" || return 1
318 [ -z "$msg" ] || m19r_fail "$msg" || return 1
319
320 m19r_must_candidate "$omega" "$M19R_OMEGA_CAND" || return 1
321 m19r_must_candidate "$physics" "$M19R_PHYSICS_CAND" || return 1
322 [ -r "$omega/evidence/omega_accelerator_world_qualification_receipt.json" ] ||
323 m19r_fail "missing evidence/omega_accelerator_world_qualification_receipt.json" || return 1
324 counts=$(m19r_observed_counts < "$all_tsv")
325 local ts
326 ts=$(date -u +%Y-%m-%dT%H:%M:%S.%6N+00:00)
327 ts=${ts/.000000+/+}
328 body="{\"schema\":\"AIEN_M19R_QUALIFICATION_V1\",\"lineage\":\"M19_REPAIR_BASELINE\""
329 body+=",\"run_id\":$(m19r_jstr "$M19R_RUN_ID"),\"timestamp_utc\":\"$ts\""
330 body+=",\"candidate_git_commit\":\"${M19R_OMEGA_CAND,,}\""
331 body+=",\"physics_candidate_git_commit\":\"${M19R_PHYSICS_CAND,,}\""
332 body+=",\"candidate_trees_clean\":{\"omega\":true,\"physics\":true}"
333 body+=",\"candidate_binary_sha256\":\"$M19R_BINARY_SHA\""
334 body+=",\"test_manifest_sha256\":\"$manifest_digest\",\"test_manifest\":$manifest"
335 body+=",\"test_results\":$R_EVENTS"
336 body+=",\"observed_gate_results_count\":$(jq -n --argjson c "$counts" '$c.completed')"
337 body+=",\"observed_pass_count\":$(jq -n --argjson c "$counts" '$c.passed')"
338 body+=",\"observed_fail_count\":$(jq -n --argjson c "$counts" '$c.failed')"
339 body+=",\"m19_observations\":$m19,\"soak\":$soak,\"resource_samples\":$samples"
340 body+=",\"hardware_probe\":$M19R_HARDWARE,\"hardware_probe_sha256\":\"$M19R_HARDWARE_SHA\""
341 body+=",\"predecessor_qualification_sha256\":\"$(m19r_sha_file "$omega/evidence/omega_accelerator_world_qualification_receipt.json")\""
342 body+=",\"historical_evidence_sha256\":$(printf '%s\n' "$historical" | jq -Rn '[inputs | select(length > 0) | {key: .[66:], value: .[0:64]}] | from_entries')"
343 body+=",\"zero_libcuda_linkage\":true"
344 body+=",\"driver_handle_count_limitation\":\"No authoritative live-handle query is exposed by the current RM interface; driver-acknowledged RM alloc/free balance and process mappings are the strongest available observables.\"}"
345 receipt_digest=$(printf '%s' "$body" | "$JSON_CANON" --sha256) ||
346 m19r_fail "receipt body is not valid JSON" || return 1
347 local receipt="{\"receipt_digest\":\"$receipt_digest\",${body#\{}"
348 if [ "$M19R_RECORD" = 1 ]; then
349 target=$omega/evidence/M19R/$receipt_digest.json
350 printf '%s' "$receipt" | m19r_write_immutable_receipt "$target" || return 1
351 R_PERMANENT=$target
352 else
353 printf '%s' "$receipt" | "$JSON_CANON" --pretty > "$run_dir/receipt-preview.json" ||
354 m19r_fail "cannot write receipt preview" || return 1
355 fi
356 R_STATUS=PASS
357 R_DIGEST=$receipt_digest
358 R_SOAK=$soak
359 R_SAMPLES=$samples
360 return 0
361}
362
363# The build + test section, run while holding /tmp/aien-gb10.lock (fd 9).
364m19r_locked_section() {
365 local omega=$M19R_OMEGA physics=$M19R_PHYSICS run_dir=$M19R_RUN_DIR name source flag
366 M19R_SUITES=()
367 m19r_cmd "$omega" - make clean || return 1
368 mkdir -p "$run_dir" || m19r_fail "cannot create $run_dir" || return 1
369 M19R_USE_ENV=1 m19r_cmd "$omega" "$run_dir/build.log" make -j4 "PHYSICS_DIR=$physics" || return 1
370 [ -r "$omega/build/omegatool" ] || m19r_fail "missing $omega/build/omegatool" || return 1
371 M19R_BINARY_SHA=$(m19r_sha_file "$omega/build/omegatool")
372 for pair in nvrm_lifecycle:nvrm/lifecycle_gates.c m16_requalify:m16/m16_requalify.c \
373 m16_concurrent:m16/m16_concurrent.c; do
374 name=${pair%%:*}; source=${pair#*:}
375 m19r_physics_binary "$physics" "$run_dir/$name" "$source" || return 1
376 M19R_USE_ENV=1 m19r_cmd "$physics" "$run_dir/$name.log" "$run_dir/$name" || return 1
377 M19R_SUITES+=("$name")
378 done
379 for pair in m15:--run-m15-gates world_lifecycle:--run-world-lifecycle-gates m19:--run-m19-gates; do
380 name=${pair%%:*}; flag=${pair#*:}
381 M19R_USE_ENV=1 m19r_cmd "$omega" "$run_dir/$name.log" "$omega/build/omegatool" "$flag" || return 1
382 M19R_SUITES+=("$name")
383 done
384 if [ "$M19R_QUICK" != 1 ]; then
385 M19R_USE_ENV=1 m19r_cmd "$omega" "$run_dir/m19r_soak.log" "$omega/build/omegatool" --run-m19r-soak || return 1
386 M19R_SUITES+=(m19r_soak)
387 fi
388 m19r_cmd "$omega" "$run_dir/readelf.log" readelf -d "$omega/build/omegatool" || return 1
389 m19r_cmd "$omega" "$run_dir/nm.log" nm -u "$omega/build/omegatool" || return 1
390 if cat "$run_dir/readelf.log" "$run_dir/nm.log" | LC_ALL=C grep -qiE "$M19R_CUDA_RE"; then
391 m19r_fail "CUDA linkage or undefined symbol found"; return 1
392 fi
393 m19r_cmd "$omega" - nvidia-smi --query-gpu=pci.bus_id,pci.device_id,driver_version,name,uuid \
394 --format=csv,noheader || return 1
395 hardware_raw=$(m19r_strip "$(cat "$M19R_OUT")")
396 driver_version=$(cat /proc/driver/nvidia/version) ||
397 m19r_fail "cannot read /proc/driver/nvidia/version" || return 1
398 driver_version=$(m19r_strip "$driver_version")
399 M19R_HARDWARE="{\"nvidia_smi_raw\":$(m19r_jstr "$hardware_raw"),\"driver_proc_version\":$(m19r_jstr "$driver_version")}"
400 M19R_HARDWARE_SHA=$(printf '%s' "$M19R_HARDWARE" | "$JSON_CANON" --sha256) || return 1
401}
402
403m19r_usage() {
404 echo "usage: $M19R_PROG [-h] --omega-candidate OMEGA_CANDIDATE --physics-candidate PHYSICS_CANDIDATE [--physics-dir PHYSICS_DIR] [--evidence-root DIR] [--run-id ID] [--record] [--quick]"
405}
406
407m19r_argerror() {
408 m19r_usage >&2
409 echo "$M19R_PROG: error: $1" >&2
410 exit 2
411}
412
413# m19r_write_environment FILE -- who/where/what ran (environment.json).
414m19r_write_environment() {
415 local pshal
416 pshal=$(git -C "$M19R_PHYSICS" rev-parse HEAD 2> /dev/null) || pshal=unknown
417 jq -n --arg host "$(hostname)" --arg date "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
418 --arg omega "$(git -C "$M19R_OMEGA" rev-parse HEAD 2> /dev/null || echo unknown)" \
419 --arg physics "$pshal" --arg kernel "$(uname -r)" --arg user "$(id -un)" \
420 '{hostname: $host, date_utc: $date, omega_sha: $omega, physics_sha: $physics, uname_r: $kernel, user: $user}' > "$1"
421}
422
423# m19r_write_verdict RUN_DIR EXIT_CODE -- verdict.json from run.json and the
424# suite logs. failing_step is run.json's error text; failing_gate_or_exit is
425# the first observed FAIL gate (suite:id) in the logs, else "exit:<code>" for
426# a failed run, else null.
427m19r_write_verdict() {
428 local dir=$1 code=$2 status step= gate= log name
429 status=$(jq -r '.status' "$dir/run.json" 2> /dev/null) || status=
430 [ -n "$status" ] || status=UNKNOWN
431 step=$(jq -r '.error // empty' "$dir/run.json" 2> /dev/null)
432 for log in "$dir"/*.log; do
433 name=$(basename "$log" .log)
434 case $name in stdout|stderr|build) continue;; esac
435 gate=$(m19r_events "$log" "$name" | awk -F'\t' '$3 == "FAIL" { print $1 ":" $2; exit }')
436 [ -z "$gate" ] || break
437 done
438 [ -n "$gate" ] || { [ "$code" -eq 0 ] || gate="exit:$code"; }
439 jq -n --arg id "$(basename "$dir")" --arg status "$status" --arg step "$step" \
440 --arg gate "$gate" --argjson code "$code" \
441 '{run_id: $id, status: $status, failing_step: (if $step == "" then null else $step end),
442 failing_gate_or_exit: (if $gate == "" then null else $gate end), exit_code: $code}' > "$dir/verdict.json"
443}
444
445# m19r_seal RUN_DIR -- hashes.sha256 over every file except itself; files made
446# read-only.
447m19r_seal() {
448 (cd "$1" && find . -type f ! -name hashes.sha256 -print0 | LC_ALL=C sort -z |
449 xargs -0 sha256sum -- > hashes.sha256) || return 1
450 find "$1" -type f -exec chmod a-w {} +
451}
452
453m19r_main() {
454 local physics_dir= missing=() run_json evidence_root= run_id= argv
455 printf -v argv '%q ' "$M19R_PROG" "$@"
456 M19R_OMEGA_CAND= M19R_PHYSICS_CAND= M19R_RECORD=0 M19R_QUICK=0
457 local have_o=0 have_p=0
458 while [ $# -gt 0 ]; do
459 case $1 in
460 -h|--help) m19r_usage; exit 0;;
461 --omega-candidate=*) M19R_OMEGA_CAND=${1#*=}; have_o=1;;
462 --physics-candidate=*) M19R_PHYSICS_CAND=${1#*=}; have_p=1;;
463 --physics-dir=*) physics_dir=${1#*=};;
464 --evidence-root=*) evidence_root=${1#*=};;
465 --run-id=*) run_id=${1#*=};;
466 --omega-candidate|--physics-candidate|--physics-dir|--evidence-root|--run-id)
467 [ $# -ge 2 ] || m19r_argerror "argument $1: expected one argument"
468 case $1 in
469 --omega-candidate) M19R_OMEGA_CAND=$2; have_o=1;;
470 --physics-candidate) M19R_PHYSICS_CAND=$2; have_p=1;;
471 --physics-dir) physics_dir=$2;;
472 --evidence-root) evidence_root=$2;;
473 --run-id) run_id=$2;;
474 esac
475 shift;;
476 --record) M19R_RECORD=1;;
477 --quick) M19R_QUICK=1;;
478 *) m19r_argerror "unrecognized arguments: $1";;
479 esac
480 shift
481 done
482 [ "$have_o" = 1 ] || missing+=(--omega-candidate)
483 [ "$have_p" = 1 ] || missing+=(--physics-candidate)
484 if [ ${#missing[@]} -gt 0 ]; then
485 local IFS=,
486 m19r_argerror "the following arguments are required: $(printf '%s' "${missing[*]}" | sed 's/,/, /g')"
487 fi
488 if [ "$M19R_RECORD" = 1 ] && [ "$M19R_QUICK" = 1 ]; then
489 m19r_argerror "--quick cannot emit a permanent receipt"
490 fi
491 M19R_PHYSICS=$(realpath -m "${physics_dir:-$(dirname "$M19R_OMEGA")/physics}")
492
493 # Evidence lives outside what `make clean` removes ($OUT_DIR, default build/).
494 evidence_root=$(realpath -m "${evidence_root:-$M19R_OMEGA/qual-runs}")
495 local out_dir
496 out_dir=$(realpath -m "$M19R_OMEGA/${OUT_DIR:-build}")
497 case $evidence_root/ in
498 "$out_dir"/*|"$M19R_OMEGA"/build/*) m19r_argerror "evidence root $evidence_root is inside the cleaned build directory";;
499 esac
500 case $out_dir/ in
501 "$evidence_root"/*) m19r_argerror "evidence root $evidence_root would be removed by make clean";;
502 esac
503 case $run_id in */*|.|..) m19r_argerror "invalid --run-id";; esac
504
505 m19r_build_canon || { echo "M19R qualification failed: cannot build tools/json_canon.c" >&2; exit 1; }
506 trap 'rm -rf "$M19R_TMP"' EXIT
507
508 M19R_RUN_ID=${run_id:-$(date -u +%Y%m%dT%H%M%SZ)-$(od -An -N6 -tx1 /dev/urandom | tr -d ' \n')}
509 M19R_RUN_DIR=$evidence_root/$M19R_RUN_ID
510 mkdir -p "$evidence_root" || exit 1
511 if ! mkdir "$M19R_RUN_DIR" 2> /dev/null; then
512 echo "$M19R_PROG: error: run directory $M19R_RUN_DIR already exists or cannot be created; run directories are never reused" >&2
513 exit 2
514 fi
515 printf '%s\n' "$argv" > "$M19R_RUN_DIR/command.txt"
516 m19r_write_environment "$M19R_RUN_DIR/environment.json" || exit 1
517
518 # Whole-run stdout/stderr go to the console and to the run directory.
519 local p1 p2
520 exec 3>&1 4>&2
521 exec > >(tee "$M19R_RUN_DIR/stdout.log" >&3)
522 p1=$!
523 exec 2> >(tee "$M19R_RUN_DIR/stderr.log" >&4)
524 p2=$!
525
526 R_STATUS=FAILED R_ERROR= R_PERMANENT= R_DIGEST= R_EVENTS= R_M19= R_SOAK= R_SAMPLES=
527 local rc=0
528 rm -f "$M19R_TMP/error"
529 if ! m19r_qualify; then
530 rc=1
531 R_STATUS=FAILED
532 [ ! -s "$M19R_TMP/error" ] || M19R_ERR=$(cat "$M19R_TMP/error")
533 R_ERROR=$M19R_ERR
534 echo "M19R qualification failed: $M19R_ERR" >&2
535 fi
536 run_json="{\"run_id\":$(m19r_jstr "$M19R_RUN_ID"),\"commands\":[],\"status\":\"$R_STATUS\""
537 [ "$rc" = 0 ] || run_json+=",\"error\":$(m19r_jstr "$R_ERROR")"
538 [ -z "$R_PERMANENT" ] || run_json+=",\"permanent_receipt\":$(m19r_jstr "$R_PERMANENT")"
539 [ -z "$R_DIGEST" ] || run_json+=",\"receipt_digest\":\"$R_DIGEST\""
540 if [ "$rc" = 0 ]; then
541 run_json+=",\"events\":$R_EVENTS,\"m19\":$R_M19"
542 [ -z "$R_SOAK" ] || run_json+=",\"soak\":$R_SOAK,\"resource_samples\":$R_SAMPLES"
543 fi
544 run_json+="}"
545 printf '%s' "$run_json" | "$JSON_CANON" --pretty > "$M19R_RUN_DIR/run.json" || rc=1
546 echo "M19R run evidence: $M19R_RUN_DIR/run.json"
547 exec 1>&3 2>&4 3>&- 4>&-
548 wait "$p1" "$p2" 2> /dev/null
549 m19r_write_verdict "$M19R_RUN_DIR" "$rc" || rc=1
550 m19r_seal "$M19R_RUN_DIR" || rc=1
551 exit "$rc"
552}
553
554if [ "${BASH_SOURCE[0]}" = "$0" ]; then
555 set -u
556 m19r_main "$@"
557fi