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 / bench / inference_cost / driver.sh

981 lines · 47260 bytes Raw Blame History
1#!/bin/sh
2# SPDX-License-Identifier: Apache-2.0
3# Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4#
5# bench/inference_cost/driver.sh -- tokens per verified program, Omega vs C vs Python vs Rust.
6#
7# driver.sh --check-tasks every reference verifies and every mutant is rejected, per language
8# driver.sh --self-test scorer, JSON edge and --run-model end to end against fake_model.om
9# driver.sh --run-model --endpoint URL --model NAME [--langs om,c,py,rs] [--arms plain,feedback]
10# [--attempts K] [--temperature T] [--max-tokens N] [--out DIR]
11#
12# Plain-text records only (attempt wire version 2, read by scorer.om); JSON exists only at the
13# HTTP edge (chat.om). Token counts are the endpoint's reported usage, never estimated.
14# Exit: 0 done, 1 a check failed, 2 usage, 3 NOT_RUN (no endpoint, HTTP or protocol failure,
15# missing toolchain or compiler pin mismatch).
16
17set -eu
18
19SCRIPT_DIR=$(CDPATH='' cd "$(dirname "$0")" && pwd)
20REPO_DIR=$(CDPATH='' cd "$SCRIPT_DIR/../.." && pwd)
21TASKS_DIR="$SCRIPT_DIR/tasks"
22BUILD_DIR="$REPO_DIR/build/inference_cost"
23BIN_DIR="$BUILD_DIR/bin"
24OMC="${OMC:-$REPO_DIR/seed/out/omc}"
25PIN_FILE="$REPO_DIR/seed/out/omc.sha256"
26ALL_LANGS="om c py rs"
27BUSY_WAIT_S="${BENCH_BUSY_WAIT_S:-1800}"
28BUSY_SLEEP_S="${BENCH_BUSY_SLEEP_S:-2}"
29# Memory ceiling, in bytes, of every sandboxed compile and run: the kernel enforces it on the whole
30# process tree as MemoryMax (swap 0) of a transient cgroup scope (systemd-run --user --scope).
31# 536870912 (512 MiB) is 5.33 times the heaviest measured reference (rustc, 100696064 bytes; README
32# "Memory ceiling"). BENCH_MEM_MAX_BYTES may set 67108864..4294967296; run.txt records the value.
33MEM_MAX_DEFAULT=536870912
34MEM_MAX="${BENCH_MEM_MAX_BYTES:-$MEM_MAX_DEFAULT}"
35
36say() { printf '%s\n' "$*"; }
37die() { printf 'driver.sh: %s\n' "$*" >&2; exit 2; }
38not_run() { say "NOT_RUN: $*"; exit 3; }
39
40usage() {
41 sed -n '7,11p' "$0" | sed 's/^# \{0,1\}//' >&2
42 exit 2
43}
44
45now_ms() { date +%s%3N; }
46
47# task_set_sha256 DIR: one digest over every file under DIR/tasks and DIR/prompts (paths relative to
48# DIR in C-locale order, sha256sum lines), so a run names the exact tasks and prompts it was given
49task_set_sha256() {
50 [ -d "$1/tasks" ] && [ -d "$1/prompts" ] || die "no tasks/ and prompts/ under $1"
51 (cd "$1" && find tasks prompts -type f | LC_ALL=C sort | xargs sha256sum) | sha256sum | awk '{print $1}'
52}
53
54# ---- compiler pin and tools
55
56check_pin() {
57 [ -f "$PIN_FILE" ] || not_run "omc pin file $PIN_FILE missing"
58 [ -f "$OMC" ] || not_run "omc not found at $OMC"
59 pin=$(awk 'NR==1{print $1}' "$PIN_FILE")
60 actual=$(sha256sum "$OMC" | awk '{print $1}')
61 [ "$pin" = "$actual" ] || not_run "omc sha256 $actual does not match the pin $pin ($PIN_FILE)"
62}
63
64need_tool() {
65 command -v "$1" >/dev/null 2>&1 || not_run "$1 is not installed"
66}
67
68need_lang_tools() {
69 need_tool timeout
70 for l in $1; do
71 case $l in
72 c) need_tool cc ;;
73 py) need_tool python3 ;;
74 rs) need_tool rustc ;;
75 om) ;;
76 *) die "unknown language '$l' (om c py rs)" ;;
77 esac
78 done
79}
80
81om_build() { # out_name, then the .om files to compose after the om2 line
82 name=$1
83 shift
84 if ! { printf 'om2\n'; cat "$@"; } | "$OMC" > "$BIN_DIR/$name.tmp" 2> "$BIN_DIR/$name.err"; then
85 cat "$BIN_DIR/$name.err" >&2
86 die "omc refused $name"
87 fi
88 chmod +x "$BIN_DIR/$name.tmp"
89 mv "$BIN_DIR/$name.tmp" "$BIN_DIR/$name"
90}
91
92build_tools() {
93 check_pin
94 mkdir -p "$BIN_DIR"
95 om_build scorer "$SCRIPT_DIR/scorer.om"
96 om_build chat "$REPO_DIR/seed/json/json.om" "$REPO_DIR/seed/json/jsonw.om" "$SCRIPT_DIR/chat.om"
97 om_build fake_model "$REPO_DIR/seed/json/json.om" "$REPO_DIR/seed/json/jsonw.om" \
98 "$REPO_DIR/seed/net/http.om" "$REPO_DIR/seed/net/notls.om" "$SCRIPT_DIR/fake_model.om"
99}
100
101# ---- task spec (version 2): name, param NAME TYPE lines, ret TYPE; types u32 i32 u64
102
103spec_name() { awk '$1=="name"{print $2; exit}' "$1"; }
104spec_ret() { awk '$1=="ret"{print $2; exit}' "$1"; }
105spec_params() { awk '$1=="param"{print $2, $3}' "$1"; }
106
107ty_om() { case $1 in u32) say uint ;; i32) say int ;; u64) say ulong ;; *) die "bad spec type $1" ;; esac; }
108ty_c() { case $1 in u32) say uint32_t ;; i32) say int32_t ;; u64) say uint64_t ;; *) die "bad spec type $1" ;; esac; }
109ty_rs() { case $1 in u32|i32|u64) say "$1" ;; *) die "bad spec type $1" ;; esac; }
110
111signature() { # lang spec
112 name=$(spec_name "$2")
113 ret=$(spec_ret "$2")
114 params=$(spec_params "$2")
115 case $1 in
116 om)
117 s="fn $name"
118 while read -r pn pt; do s="$s $pn $(ty_om "$pt")"; done <<EOF
119$params
120EOF
121 say "$s to $(ty_om "$ret")" ;;
122 c)
123 s=""
124 while read -r pn pt; do s="${s:+$s, }$(ty_c "$pt") $pn"; done <<EOF
125$params
126EOF
127 say "$(ty_c "$ret") $name($s)" ;;
128 py)
129 s=""
130 while read -r pn pt; do s="${s:+$s, }$pn"; done <<EOF
131$params
132EOF
133 say "def $name($s)" ;;
134 rs)
135 s=""
136 while read -r pn pt; do s="${s:+$s, }$pn: $(ty_rs "$pt")"; done <<EOF
137$params
138EOF
139 say "fn $name($s) -> $(ty_rs "$ret")" ;;
140 esac
141}
142
143lang_title() { case $1 in om) say Omega ;; c) say C ;; py) say Python ;; rs) say Rust ;; esac; }
144lang_fence() { case $1 in om) say omega ;; c) say c ;; py) say python ;; rs) say rust ;; esac; }
145
146# ---- the stdin driver appended after a candidate: inputs.txt in, one decimal per case out
147
148gen_main() { # lang spec
149 name=$(spec_name "$2")
150 ret=$(spec_ret "$2")
151 params=$(spec_params "$2")
152 i=0
153 args=""
154 case $1 in
155 om)
156 printf '\nfn main to int\nbench_load\nbxn = bench_cases\nfor bxi ulong bxn\n'
157 while read -r pn pt; do
158 printf 'bxa%d = %s bench_arg\n' "$i" "$(ty_om "$pt")"
159 args="$args bxa$i"
160 i=$((i + 1))
161 done <<EOF
162$params
163EOF
164 printf 'bxr = %s%s\n' "$name" "$args"
165 case $ret in
166 u32) say 'bench_putu ulong bxr' ;;
167 i32) say 'bench_puti long bxr' ;;
168 u64) say 'bench_putu bxr' ;;
169 esac
170 printf 'end\nret 0\nend\n' ;;
171 c)
172 printf '\nint main(void) {\n char bench_w[64];\n unsigned long long bench_n, bench_i;\n'
173 printf ' if (scanf("%%63s %%63s %%63s %%llu", bench_w, bench_w, bench_w, &bench_n) != 4) return 92;\n'
174 printf ' for (bench_i = 0; bench_i < bench_n; bench_i++) {\n'
175 while read -r pn pt; do
176 printf ' if (scanf("%%63s", bench_w) != 1) return 92;\n'
177 case $pt in
178 u64) printf ' %s bench_a%d = (%s)strtoull(bench_w, 0, 10);\n' "$(ty_c "$pt")" "$i" "$(ty_c "$pt")" ;;
179 *) printf ' %s bench_a%d = (%s)strtoll(bench_w, 0, 10);\n' "$(ty_c "$pt")" "$i" "$(ty_c "$pt")" ;;
180 esac
181 args="${args:+$args, }bench_a$i"
182 i=$((i + 1))
183 done <<EOF
184$params
185EOF
186 printf ' %s bench_r = %s(%s);\n' "$(ty_c "$ret")" "$name" "$args"
187 case $ret in
188 i32) printf ' printf("%%lld\\n", (long long)bench_r);\n' ;;
189 *) printf ' printf("%%llu\\n", (unsigned long long)bench_r);\n' ;;
190 esac
191 printf ' }\n return 0;\n}\n' ;;
192 py)
193 k=$(printf '%s\n' "$params" | awk 'NF==2{n++} END{print n+0}')
194 printf '\n\nimport sys as _bench_sys\n\n\ndef _bench_main():\n'
195 printf ' t = _bench_sys.stdin.read().split()\n n = int(t[3])\n p = 4\n o = []\n'
196 printf ' for _ in range(n):\n a = [int(x) for x in t[p:p + %d]]\n p += %d\n' "$k" "$k"
197 printf ' r = %s(*a)\n if type(r) is not int:\n _bench_sys.exit(94)\n' "$name"
198 printf ' o.append("%%d\\n" %% r)\n _bench_sys.stdout.write("".join(o))\n\n\n_bench_main()\n' ;;
199 rs)
200 printf '\nfn main() {\n use std::io::Read;\n let mut bench_s = String::new();\n'
201 printf ' std::io::stdin().read_to_string(&mut bench_s).unwrap();\n'
202 printf ' let bench_t: Vec<&str> = bench_s.split_whitespace().collect();\n'
203 printf ' let bench_n: usize = bench_t[3].parse().unwrap();\n let mut bench_p = 4;\n'
204 printf ' let mut bench_o = String::new();\n for _ in 0..bench_n {\n'
205 while read -r pn pt; do
206 printf ' let bench_a%d: %s = bench_t[bench_p].parse().unwrap();\n bench_p += 1;\n' "$i" "$(ty_rs "$pt")"
207 args="${args:+$args, }bench_a$i"
208 i=$((i + 1))
209 done <<EOF
210$params
211EOF
212 printf ' let bench_r: %s = %s(%s);\n' "$(ty_rs "$ret")" "$name" "$args"
213 printf ' bench_o.push_str(&format!("{}\\n", bench_r));\n }\n print!("{}", bench_o);\n}\n' ;;
214 esac
215}
216
217# Candidate execution has no host root, home, network or inherited environment. Only
218# system runtime libraries and the single executable/source are exposed read-only;
219# stdin carries inputs, and the host compares stdout against the oracle afterward.
220# Never fall back to direct execution if bubblewrap cannot establish its namespaces.
221# Every compile and run also lives in a cgroup scope whose MemoryMax is MEM_MAX (swap 0):
222# the kernel OOM-kills inside the scope instead of letting a candidate exhaust the host.
223
224# The scope's first process restores the caller's stderr (fd 5; systemd-run's own errors went to a
225# file), marks that the scope started, checks that its own cgroup carries exactly the ceiling and no
226# swap (else it writes memory_ceiling_unavailable on fd 4 and runs nothing), runs the command, then
227# writes the scope's peak bytes and OOM-kill count on fd 4 (beside bwrap's namespace JSON).
228MEMCAP_SH='exec 2>&5 5>&-
229: > "$2" || exit 125
230g=/sys/fs/cgroup$(sed -n "s/^0:://p" /proc/self/cgroup)
231if [ "$(cat "$g/memory.max" 2>/dev/null)" != "$1" ] || [ "$(cat "$g/memory.swap.max" 2>/dev/null)" != 0 ]; then
232 printf "memory_ceiling_unavailable max=%s\n" "$(cat "$g/memory.max" 2>/dev/null)" >&4
233 exit 125
234fi
235shift 2
236"$@"
237rc=$?
238printf "memory_peak_bytes %s\nmemory_oom_kills %s\n" "$(cat "$g/memory.peak")" "$(sed -n "s/^oom_kill //p" "$g/memory.events")" >&4
239exit $rc'
240
241# mem_scope command...: run it in a transient scope with the memory ceiling. When systemd-run fails
242# before the scope started (observed 2026-11-11 under load: "Failed to start transient scope unit:
243# Transport endpoint is not connected"), nothing has run and nothing read stdin, so it is tried again,
244# 5 times in all, 1 s apart; then systemd-run's error goes to stderr and its status is returned.
245mem_scope() {
246 XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR:-/run/user/$(id -u)}
247 export XDG_RUNTIME_DIR
248 mkdir -p "$BUILD_DIR"
249 ms_dir=$(mktemp -d "$BUILD_DIR/scope.XXXXXX") || return 125
250 ms_try=1
251 while :; do
252 ms_rc=0
253 systemd-run --user --scope --quiet --collect -p MemoryMax="$MEM_MAX" -p MemorySwapMax=0 \
254 -p OOMPolicy=continue -- sh -c "$MEMCAP_SH" memcap "$MEM_MAX" "$ms_dir/started" "$@" \
255 5>&2 2> "$ms_dir/err" || ms_rc=$?
256 [ ! -e "$ms_dir/started" ] && [ "$ms_try" -lt 5 ] || break
257 ms_try=$((ms_try + 1))
258 sleep 1
259 done
260 [ -e "$ms_dir/started" ] || cat "$ms_dir/err" >&2
261 rm -rf "$ms_dir"
262 return "$ms_rc"
263}
264
265sandbox_note() { # key file: the key's last value, an empty line when absent or the file is missing
266 if [ -f "$2" ]; then awk -v k="$1" '$1==k{v=$2} END{print v}' "$2"; else printf '\n'; fi
267}
268
269sandbox() { # mode candidate_file
270 sb_mode=$1
271 sb_file=$2
272 # Only the trusted shell can write readiness; fd 3 is closed before candidate code.
273 # bwrap's fd 4 namespace JSON is useful telemetry, not proof mount/setup succeeded.
274 sb_start='for fd in /proc/self/fd/*; do
275 fd=${fd##*/}
276 case $fd in
277 0|1|2|3) ;;
278 *[!0-9]*) exit 125 ;;
279 *) eval "exec ${fd}>&-" || exit 125 ;;
280 esac
281 done
282 printf "ready\n" >&3 || exit 125
283 exec 3>&-
284 exec "$@"'
285 set -- bwrap --unshare-all --unshare-user --disable-userns --die-with-parent --new-session --clearenv --info-fd 4 \
286 --setenv PATH /usr/bin --setenv LC_ALL C \
287 --ro-bind /usr/lib /usr/lib --symlink usr/lib /lib \
288 --dir /usr/bin --ro-bind "$(readlink -f "$(command -v bash)")" /usr/bin/sh \
289 --ro-bind "$(readlink -f "$(command -v python3)")" /usr/bin/python3 --symlink usr/bin /bin \
290 --proc /proc --dev /dev --tmpfs /tmp --dir /work --chdir /work \
291 --ro-bind "$sb_file" /work/candidate
292 set -- mem_scope "$@" # memory ceiling
293 # Compiler-only system headers/tools; never mount home, /tmp or the checkout.
294 case $sb_mode in
295 c|rs)
296 set -- "$@" --ro-bind /usr/include /usr/include \
297 --ro-bind /usr/libexec /usr/libexec \
298 --ro-bind "$(readlink -f "$(command -v cc)")" /usr/bin/cc \
299 --ro-bind "$(readlink -f "$(command -v as)")" /usr/bin/as \
300 --ro-bind "$(readlink -f "$(command -v ld)")" /usr/bin/ld \
301 --ro-bind "$(readlink -f "$(command -v cat)")" /usr/bin/cat ;;
302 esac
303 case $sb_mode in
304 om)
305 "$@" --ro-bind "$OMC" /compiler --remount-ro / /usr/bin/sh -c "$sb_start" ready /compiler ;;
306 c)
307 "$@" --remount-ro / /usr/bin/sh -c "$sb_start" ready /usr/bin/sh -c 'cc -O2 -x c -include stdint.h -include stdio.h -include stdlib.h -o /tmp/bin /work/candidate -lm && cat /tmp/bin' ;;
308 py)
309 "$@" --remount-ro / /usr/bin/sh -c "$sb_start" ready /usr/bin/python3 -I -c \
310 'import py_compile; py_compile.compile("/work/candidate", cfile="/tmp/candidate.pyc", doraise=True)' ;;
311 rs)
312 sb_root=$(rustc --print sysroot) || not_run "cannot resolve Rust sysroot"
313 "$@" --ro-bind "$sb_root/bin/rustc" /toolchain/bin/rustc \
314 --ro-bind "$sb_root/lib" /toolchain/lib --setenv LD_LIBRARY_PATH /toolchain/lib \
315 --remount-ro / /usr/bin/sh -c "$sb_start" ready /usr/bin/sh -c '/toolchain/bin/rustc --sysroot /toolchain -O --edition 2021 -A warnings --crate-name bench -o /tmp/bin /work/candidate && cat /tmp/bin' ;;
316 run)
317 if [ "$sb_file" = /dev/null ]; then
318 "$@" --remount-ro / /usr/bin/sh -c "$sb_start" ready /usr/bin/python3 -I -c 'pass'
319 elif [ "${sb_file##*.}" = py ]; then
320 "$@" --remount-ro / /usr/bin/sh -c "$sb_start" ready /usr/bin/python3 -I /work/candidate
321 else
322 "$@" --remount-ro / /usr/bin/sh -c "$sb_start" ready /work/candidate
323 fi ;;
324 *) die "unknown sandbox mode" ;;
325 esac
326}
327
328check_sandbox() {
329 need_tool bwrap
330 need_tool timeout
331 need_tool python3
332 # The sandbox-only shell needs numeric fd redirections above 9 (dash does not).
333 need_tool bash
334 need_tool systemd-run
335 case $MEM_MAX in
336 ''|*[!0-9]*) die "BENCH_MEM_MAX_BYTES must be a byte count from 67108864 to 4294967296" ;;
337 esac
338 [ "$MEM_MAX" -ge 67108864 ] && [ "$MEM_MAX" -le 4294967296 ] ||
339 die "BENCH_MEM_MAX_BYTES must be a byte count from 67108864 to 4294967296"
340 # The ceiling must take effect (scope created, MemoryMax and swap 0 read back) before any candidate.
341 cs_out=$(mem_scope true 4>&1 >/dev/null 2>&1) && [ -n "$(printf '%s\n' "$cs_out" | awk '$1=="memory_oom_kills"')" ] ||
342 not_run "the memory ceiling (cgroup scope MemoryMax=$MEM_MAX, swap 0) cannot be applied; no candidate was run"
343 # Exercise the actual namespace setup, not merely bwrap's presence in PATH.
344 sandbox run /dev/null 3>/dev/null 4>/dev/null >/dev/null 2>&1 ||
345 not_run "bubblewrap sandbox is unavailable; no candidate was run"
346}
347
348run_candidate() { # file command [args...]
349 # GNU timeout owns a process group; bubblewrap also owns a PID namespace.
350 # TERM gets a short grace period, then KILL tears down every descendant.
351 timeout --kill-after=1s 10s sh "$SCRIPT_DIR/driver.sh" --sandbox run "$1"
352}
353
354# sandbox_gone SANDBOX_JSON: after a compile or run returns, its PID namespace (bubblewrap's
355# "child-pid", the namespace init) must be gone. Teardown after a deadline kill finishes
356# asynchronously (observed 2026-11-11: the init still answered kill -0 right after timeout returned,
357# 1 of 15 tries, gone 1 s later), so wait up to 5 s; a namespace still alive then is NOT_RUN.
358sandbox_gone() {
359 sg_pid=$(awk '/"child-pid"/{gsub(/[^0-9]/, ""); print}' "$1" 2>/dev/null)
360 [ -n "$sg_pid" ] || return 0
361 sg_i=0
362 while kill -0 "$sg_pid" 2>/dev/null; do
363 [ "$sg_i" -lt 100 ] || not_run "sandbox namespace init $sg_pid still alive 5 s after its compile or run ended"
364 sleep 0.05
365 sg_i=$((sg_i + 1))
366 done
367}
368
369# ---- evaluate one candidate: sets COMP_RC, RUN_RC and VERIFIED; the work dir holds src, err.txt,
370# out.txt. A compiler refusal (COMP_RC != 0) is never verified and its output is never run (#910).
371# sh has no locals: every name set here starts with ev_.
372
373evaluate() { # lang task_dir candidate work
374 ev_l=$1
375 ev_t=$2
376 ev_c=$3
377 ev_w=$4
378 rm -rf "$ev_w"
379 mkdir -p "$ev_w"
380 ev_s="$ev_t/spec.txt"
381 COMP_RC=0
382 case $ev_l in
383 om)
384 # om2 diag: the human "omc: line N: error K" plus an "omc-diag 1 ..." record on refusal.
385 { printf 'om2 diag\n'; sed '1{/^om2\( .*\)\{0,1\}$/d;}' "$ev_c"; printf '\n'; cat "$SCRIPT_DIR/io.om"; gen_main om "$ev_s"; } > "$ev_w/src.om"
386 timeout --kill-after=1s 10s sh "$SCRIPT_DIR/driver.sh" --sandbox om "$ev_w/src.om" < "$ev_w/src.om" > "$ev_w/bin" 2> "$ev_w/err.txt" 3> "$ev_w/compile.ready" 4> "$ev_w/compile.sandbox" || COMP_RC=$? ;;
387 c)
388 { cat "$ev_c"; gen_main c "$ev_s"; } > "$ev_w/src.c"
389 timeout --kill-after=1s 10s sh "$SCRIPT_DIR/driver.sh" --sandbox c "$ev_w/src.c" > "$ev_w/bin" 2> "$ev_w/err.txt" 3> "$ev_w/compile.ready" 4> "$ev_w/compile.sandbox" || COMP_RC=$? ;;
390 py)
391 { cat "$ev_c"; gen_main py "$ev_s"; } > "$ev_w/src.py"
392 timeout --kill-after=1s 10s sh "$SCRIPT_DIR/driver.sh" --sandbox py "$ev_w/src.py" > "$ev_w/compile.out" 2> "$ev_w/err.txt" 3> "$ev_w/compile.ready" 4> "$ev_w/compile.sandbox" || COMP_RC=$? ;;
393 rs)
394 { cat "$ev_c"; gen_main rs "$ev_s"; } > "$ev_w/src.rs"
395 timeout --kill-after=1s 10s sh "$SCRIPT_DIR/driver.sh" --sandbox rs "$ev_w/src.rs" > "$ev_w/bin" 2> "$ev_w/err.txt" 3> "$ev_w/compile.ready" 4> "$ev_w/compile.sandbox" || COMP_RC=$? ;;
396 esac
397 sandbox_gone "$ev_w/compile.sandbox"
398 ev_k=$(sandbox_note memory_oom_kills "$ev_w/compile.sandbox")
399 if [ "$(cat "$ev_w/compile.ready")" != ready ]; then
400 [ -z "$(sandbox_note memory_ceiling_unavailable "$ev_w/compile.sandbox")" ] ||
401 not_run "the memory ceiling could not be applied to the compiler sandbox; no unbounded fallback"
402 not_run "bubblewrap could not start the compiler sandbox; no unsandboxed fallback"
403 fi
404 MEM_KILL=none
405 # A compile the ceiling killed never counts as compiled, whatever its exit status.
406 if [ "${ev_k:-0}" -gt 0 ]; then
407 MEM_KILL=compile
408 [ "$COMP_RC" -ne 0 ] || COMP_RC=137
409 fi
410 VERIFIED=0
411 RUN_RC=-
412 if [ "$COMP_RC" -eq 0 ]; then
413 RUN_RC=0
414 if [ "$ev_l" = py ]; then
415 run_candidate "$ev_w/src.py" < "$ev_t/inputs.txt" > "$ev_w/out.txt" 2> "$ev_w/run.err" 3> "$ev_w/run.ready" 4> "$ev_w/run.sandbox" || RUN_RC=$?
416 else
417 chmod +x "$ev_w/bin"
418 run_candidate "$ev_w/bin" < "$ev_t/inputs.txt" > "$ev_w/out.txt" 2> "$ev_w/run.err" 3> "$ev_w/run.ready" 4> "$ev_w/run.sandbox" || RUN_RC=$?
419 fi
420 sandbox_gone "$ev_w/run.sandbox"
421 ev_k=$(sandbox_note memory_oom_kills "$ev_w/run.sandbox")
422 if [ "$(cat "$ev_w/run.ready")" != ready ]; then
423 [ -z "$(sandbox_note memory_ceiling_unavailable "$ev_w/run.sandbox")" ] ||
424 not_run "the memory ceiling could not be applied to the candidate sandbox; no unbounded fallback"
425 not_run "bubblewrap could not start the candidate sandbox; no unsandboxed fallback"
426 fi
427 # A run in which the ceiling killed any process is a failed attempt, whatever it printed.
428 [ "${ev_k:-0}" -eq 0 ] || MEM_KILL=run
429 if [ "$RUN_RC" -eq 0 ] && [ "$MEM_KILL" = none ] && tail -n +3 "$ev_t/expected.txt" | cmp -s - "$ev_w/out.txt"; then
430 VERIFIED=1
431 fi
432 fi
433}
434
435# ---- --check-tasks
436
437task_ids() { for d in "$TASKS_DIR"/task*/; do basename "$d"; done; }
438
439check_tasks() {
440 check_sandbox
441 need_lang_tools "$ALL_LANGS"
442 cwork="$BUILD_DIR/check"
443 rm -rf "$cwork"
444 bad=0
445 ntask=$(task_ids | wc -l)
446 for lang in $ALL_LANGS; do
447 rok=0
448 mok=0
449 mwrong=0
450 fails=""
451 for tid in $(task_ids); do
452 tdir="$TASKS_DIR/$tid"
453 evaluate "$lang" "$tdir" "$tdir/reference.$lang" "$cwork/$lang-$tid-ref"
454 if [ "$COMP_RC" -eq 0 ] && [ "$VERIFIED" -eq 1 ]; then
455 rok=$((rok + 1))
456 else
457 fails="$fails $tid:reference(comp_rc=$COMP_RC,run_rc=$RUN_RC)"
458 fi
459 evaluate "$lang" "$tdir" "$tdir/mutant.$lang" "$cwork/$lang-$tid-mut"
460 if [ "$COMP_RC" -eq 0 ] && [ "$VERIFIED" -eq 0 ]; then
461 mok=$((mok + 1))
462 [ "$RUN_RC" != 0 ] || mwrong=$((mwrong + 1))
463 else
464 fails="$fails $tid:mutant(comp_rc=$COMP_RC,verified=$VERIFIED)"
465 fi
466 done
467 say "check $lang: references $rok/$ntask verified, mutants $mok/$ntask compiled and rejected ($mwrong by wrong output, $((mok - mwrong)) by a nonzero exit)"
468 if [ -n "$fails" ]; then
469 say "check $lang: FAIL$fails"
470 bad=1
471 fi
472 done
473 return $bad
474}
475
476# ---- --run-model
477
478user_prompt() { # lang task_dir
479 cat "$2/statement.txt"
480 printf '\n%s signature: %s\n' "$(lang_title "$1")" "$(signature "$1" "$2/spec.txt")"
481 printf 'Reply with only this function (and any helper functions it needs) in one fenced code block. No main function, no input or output.\n'
482}
483
484add_msg() { # conv_dir role file
485 n=$(( $(ls "$1" | wc -l) / 2 + 1 ))
486 f=$(printf '%s/%02d' "$1" "$n")
487 say "$2" > "$f.role"
488 cat "$3" > "$f.txt"
489}
490
491build_wire() { # conv_dir
492 printf 'version 1\nmodel %s\nmax_tokens %s\ntemperature %s\nmessages %d\n' \
493 "$MODEL" "$MAXTOK" "$TEMP" $(( $(ls "$1" | wc -l) / 2 ))
494 for f in "$1"/*.txt; do
495 printf 'msg %s %d\n' "$(cat "${f%.txt}.role")" $(( $(wc -c < "$f") ))
496 cat "$f"
497 printf '\n'
498 done
499}
500
501feedback() { # lang work -> the feedback message on stdout
502 if [ "$COMP_RC" -ne 0 ]; then
503 case $1 in
504 om) d=$(grep -m 1 '^omc: line' "$2/err.txt" || true)
505 r=$(grep -m 1 '^omc-diag 1' "$2/err.txt" || true)
506 d="$d${r:+
507$r}" ;;
508 c) d=$(grep 'error' "$2/err.txt" | head -n 3 | sed "s|$2/||g") ;;
509 rs) d=$(grep -E '^(error| *--> )' "$2/err.txt" | head -n 6 | sed "s|$2/||g") ;;
510 py) d=$(grep -E 'line [0-9]+|Error' "$2/err.txt" | head -n 3 | sed "s|$2/||g") ;;
511 esac
512 [ -n "$d" ] || d=$(tail -n 3 "$2/err.txt" | sed "s|$2/||g")
513 printf 'Your code did not compile. Compiler output:\n%s\n' "$(printf '%s' "$d" | head -c 600)"
514 if [ "$MEM_KILL" = compile ]; then
515 printf 'The compiler was killed for using more than %s bytes of memory on your code.\n' "$MEM_MAX"
516 fi
517 if [ "$1" = om ]; then
518 printf 'Line 1 of the compiled unit is the line "om2 diag" put before your code.\n'
519 fi
520 elif [ "$MEM_KILL" = run ]; then
521 printf 'Your code was killed for using more than %s bytes of memory on hidden tests.\n' "$MEM_MAX"
522 else
523 printf 'Your code compiled but returned wrong results on hidden tests (exit status %s).\n' "$RUN_RC"
524 fi
525 printf 'Reply with the corrected complete function in one fenced code block.\n'
526}
527
528meta() { awk -v k="$1" '$1==k{print $2; exit}' "$2"; }
529
530claim_output() { # output directory; a persistent marker gives one invocation ownership
531 OUT=$1
532 while :; do
533 case $OUT in /) die "--out must be a fresh directory" ;;
534 */) OUT=${OUT%/} ;; *) break ;; esac
535 done
536 [ ! -L "$OUT" ] || die "--out must not be a symbolic link"
537 if [ -e "$OUT" ]; then
538 [ -d "$OUT" ] || die "--out must be a directory"
539 co_entries=$(find -H "$OUT" -mindepth 1 -maxdepth 1 -print -quit) ||
540 die "--out cannot be inspected"
541 [ -z "$co_entries" ] || die "--out must be empty; existing runs are never reused"
542 fi
543 mkdir -p "$OUT"
544 [ ! -L "$OUT" ] || die "--out must not be a symbolic link"
545 mkdir "$OUT/.inference-cost-owner" 2>/dev/null ||
546 die "--out is already claimed; existing runs are never reused"
547 co_entries=$(find -H "$OUT" -mindepth 1 -maxdepth 1 ! -name .inference-cost-owner -print -quit) ||
548 die "--out cannot be inspected"
549 if [ -n "$co_entries" ]; then
550 rmdir "$OUT/.inference-cost-owner"
551 die "--out must be empty; existing runs are never reused"
552 fi
553}
554
555# post_chat ATTEMPT_DIR TASK LANG: POST ATTEMPT_DIR/request.json; sets CODE, T0 and T1 (start and end
556# of the request that was answered), BUSY_N and BUSY_MS. HTTP 503 means the endpoint is busy (the live
557# server generates one reply at a time and answers a concurrent request with 503): the same request
558# is sent again every BUSY_SLEEP_S seconds until another status comes back, and the run is NOT_RUN
559# once BUSY_WAIT_S seconds have passed since the first send (BENCH_BUSY_WAIT_S=0: no retry). A 503
560# carries no usage, so it adds no tokens, and the attempt's wall time starts at the answered request.
561post_chat() {
562 pc_start=$(now_ms)
563 BUSY_N=0
564 while :; do
565 T0=$(now_ms)
566 CODE=$(curl -sS --max-time 600 -o "$1/response.json" -w '%{http_code}' \
567 -H 'Content-Type: application/json' -H "X-Bench-Task: $2" -H "X-Bench-Lang: $3" \
568 --data-binary @"$1/request.json" "$ENDPOINT/v1/chat/completions" 2> "$1/curl.err") ||
569 not_run "HTTP failure for $2 $3 $arm attempt $att: $(cat "$1/curl.err")"
570 T1=$(now_ms)
571 [ "$CODE" = 503 ] || break
572 BUSY_N=$((BUSY_N + 1))
573 [ $((T1 - pc_start)) -lt $((BUSY_WAIT_S * 1000)) ] ||
574 not_run "HTTP 503 (endpoint busy) for $2 $3 $arm attempt $att: $BUSY_N refusals over $((T1 - pc_start)) ms (BENCH_BUSY_WAIT_S=$BUSY_WAIT_S)"
575 sleep "$BUSY_SLEEP_S"
576 done
577 BUSY_MS=$((T0 - pc_start))
578}
579
580run_model() {
581 ENDPOINT=""
582 MODEL=""
583 LANGS="om,c,py,rs"
584 ARMS="plain,feedback"
585 ATTEMPTS=3
586 TEMP=0.2
587 MAXTOK=4096
588 OUT=""
589 while [ $# -gt 0 ]; do
590 case $1 in
591 --endpoint) ENDPOINT=${2:-}; shift 2 ;;
592 --model) MODEL=${2:-}; shift 2 ;;
593 --langs) LANGS=${2:-}; shift 2 ;;
594 --arms) ARMS=${2:-}; shift 2 ;;
595 --attempts) ATTEMPTS=${2:-}; shift 2 ;;
596 --temperature) TEMP=${2:-}; shift 2 ;;
597 --max-tokens) MAXTOK=${2:-}; shift 2 ;;
598 --out) OUT=${2:-}; shift 2 ;;
599 *) die "unknown --run-model option '$1'" ;;
600 esac
601 done
602 [ -n "$ENDPOINT" ] || not_run "no --endpoint given; no model was contacted"
603 [ -n "$MODEL" ] || die "--model NAME is required"
604 case $MODEL in *[!A-Za-z0-9._:/@+-]*) die "--model must be one word of [A-Za-z0-9._:/@+-]" ;; esac
605 case $ATTEMPTS in ''|*[!0-9]*|0) die "--attempts must be a positive integer" ;; esac
606 case $MAXTOK in ''|*[!0-9]*|0) die "--max-tokens must be a positive integer" ;; esac
607 case $LANGS in ''|,*|*,|*,,*|*[!a-z,]*) die "--langs requires a nonempty comma-separated language list" ;; esac
608 case $ARMS in ''|,*|*,|*,,*|*[!a-z,]*) die "--arms requires a nonempty comma-separated arm list" ;; esac
609 case $BUSY_WAIT_S in ''|*[!0-9]*) die "BENCH_BUSY_WAIT_S must be a nonnegative integer" ;; esac
610 case $BUSY_SLEEP_S in ''|*[!0-9]*) die "BENCH_BUSY_SLEEP_S must be a nonnegative integer" ;; esac
611 langs=$(printf '%s' "$LANGS" | tr ',' ' ')
612 arms=$(printf '%s' "$ARMS" | tr ',' ' ')
613 for a in $arms; do case $a in plain|feedback) ;; *) die "unknown arm '$a' (plain feedback)" ;; esac; done
614 need_lang_tools "$langs"
615 need_tool curl
616 check_sandbox
617 ENDPOINT=${ENDPOINT%/}
618 [ -n "$OUT" ] || OUT="$BUILD_DIR/run-$(date -u +%Y%m%dT%H%M%SZ)-$$"
619 claim_output "$OUT"
620 {
621 say "version 1"
622 say "endpoint $ENDPOINT"
623 say "model_requested $MODEL"
624 say "langs $langs"
625 say "arms $arms"
626 say "attempts $ATTEMPTS"
627 say "temperature $TEMP"
628 say "max_tokens $MAXTOK"
629 say "omc_sha256 $(sha256sum "$OMC" | awk '{print $1}')"
630 say "task_set_sha256 $(task_set_sha256 "$SCRIPT_DIR")"
631 say "memory_max_bytes $MEM_MAX"
632 say "started $(date -u +%Y-%m-%dT%H:%M:%SZ)"
633 } > "$OUT/run.txt"
634 : > "$OUT/rows.txt"
635 say "# task lang arm attempt http_code model_reported prompt_tokens completion_tokens total_tokens http_ms" > "$OUT/calls.txt"
636 say "# task lang arm attempt busy_503 busy_wait_ms (busy_wait_s $BUSY_WAIT_S busy_sleep_s $BUSY_SLEEP_S)" > "$OUT/busy.txt"
637 say "# task lang arm attempt compile_peak_bytes run_peak_bytes ceiling_kill (memory_max_bytes $MEM_MAX; ceiling_kill none|compile|run)" > "$OUT/memory.txt"
638 for lang in $langs; do
639 for arm in $arms; do
640 for tid in $(task_ids); do
641 tdir="$TASKS_DIR/$tid"
642 base="$OUT/$lang/$arm/$tid"
643 conv="$base/conv"
644 mkdir -p "$conv"
645 user_prompt "$lang" "$tdir" > "$base/user.txt"
646 add_msg "$conv" system "$SCRIPT_DIR/prompts/system-$lang.txt"
647 add_msg "$conv" user "$base/user.txt"
648 att=1
649 while [ "$att" -le "$ATTEMPTS" ]; do
650 a="$base/a$att"
651 mkdir -p "$a"
652 build_wire "$conv" > "$a/request.wire"
653 "$BIN_DIR/chat" req < "$a/request.wire" > "$a/request.json" ||
654 not_run "could not encode the request for $tid $lang $arm attempt $att (chat req rc $?)"
655 post_chat "$a" "$tid" "$lang"
656 code=$CODE
657 t0=$T0
658 t1=$T1
659 [ "$code" = 200 ] || not_run "HTTP $code for $tid $lang $arm attempt $att"
660 "$BIN_DIR/chat" resp < "$a/response.json" > "$a/meta.txt" 3> "$a/candidate.$lang" ||
661 not_run "unusable response for $tid $lang $arm attempt $att (chat resp rc $?): no usage, an error object or no choices"
662 p=$(meta prompt_tokens "$a/meta.txt")
663 c=$(meta completion_tokens "$a/meta.txt")
664 t=$(meta total_tokens "$a/meta.txt")
665 m=$(meta model "$a/meta.txt")
666 evaluate "$lang" "$tdir" "$a/candidate.$lang" "$a/eval"
667 t2=$(now_ms)
668 first=0
669 [ "$att" -ne 1 ] || first=1
670 say "$tid $lang $arm $att $first $COMP_RC $VERIFIED $((t2 - t0)) $p $c $t" >> "$OUT/rows.txt"
671 say "$tid $lang $arm $att $code $m $p $c $t $((t1 - t0))" >> "$OUT/calls.txt"
672 say "$tid $lang $arm $att $BUSY_N $BUSY_MS" >> "$OUT/busy.txt"
673 say "$tid $lang $arm $att $(sandbox_note memory_peak_bytes "$a/eval/compile.sandbox" | sed 's/^$/-/') $(sandbox_note memory_peak_bytes "$a/eval/run.sandbox" | sed 's/^$/-/') $MEM_KILL" >> "$OUT/memory.txt"
674 [ "$VERIFIED" -eq 0 ] || break
675 if [ "$arm" = feedback ] && [ "$att" -lt "$ATTEMPTS" ]; then
676 { printf '```%s\n' "$(lang_fence "$lang")"; cat "$a/candidate.$lang"; printf '\n```\n'; } > "$a/assistant.txt"
677 feedback "$lang" "$a/eval" > "$a/feedback.txt"
678 add_msg "$conv" assistant "$a/assistant.txt"
679 add_msg "$conv" user "$a/feedback.txt"
680 fi
681 att=$((att + 1))
682 done
683 done
684 done
685 done
686 { say "version 2"; say "attempts $(wc -l < "$OUT/rows.txt")"; cat "$OUT/rows.txt"; } > "$OUT/attempts.txt"
687 rm -f "$OUT/rows.txt"
688 src=0
689 "$BIN_DIR/scorer" < "$OUT/attempts.txt" > "$OUT/summary.txt" || src=$?
690 [ "$src" -le 1 ] || die "scorer rejected $OUT/attempts.txt (rc $src)"
691 say "models_reported $(awk 'NR>1{print $6}' "$OUT/calls.txt" | sort -u | tr '\n' ' ')" >> "$OUT/run.txt"
692 say "finished $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$OUT/run.txt"
693 say "run $OUT"
694 grep '^models_reported' "$OUT/run.txt"
695 say "memory_ceiling_kills $(awk 'NR>1 && $7!="none"' "$OUT/memory.txt" | wc -l) (memory.txt)"
696 report "$OUT/summary.txt"
697}
698
699report() { # summary.txt -> one line per (lang, arm)
700 awk '/^group /{g=$2 " " $3} /^tasks_total /{t=$2} /^attempts_total /{a=$2}
701 /^verified_count /{v=$2} /^first_attempt_verified /{f=$2} /^total_tokens /{tt=$2}
702 /^tokens_per_verified /{tpv=$2} /^verified_per_1k_tokens /{k=$2} /^verified_per_minute /{m=$2}
703 /^end$/{printf "%-11s verified %s/%s attempts %s first_attempt_verified %s total_tokens %s tokens_per_verified %s verified_per_1k_tokens %s verified_per_minute %s\n", g, v, t, a, f, tt, tpv, k, m}' "$1"
704}
705
706# ---- --self-test
707
708ST_FAIL=0
709st_ok() { say "ok $*"; }
710st_bad() { say "FAIL $*"; ST_FAIL=1; }
711st_expect() { # label want got
712 if [ "$2" = "$3" ]; then st_ok "$1 = $3"; else st_bad "$1: want $2, got $3"; fi
713}
714
715group_field() { # summary lang arm field
716 awk -v g="group $2 $3" -v f="$4" '$0==g{on=1; next} on&&$1==f{print $2; exit} /^end$/{on=0}' "$1"
717}
718
719FAKE_PID=""
720start_fake() { # mode tasks_dir -> sets FAKE_PORT
721 "$BIN_DIR/fake_model" "$1" "$2" 1000 > "$BUILD_DIR/selftest/fake.out" 2>&1 &
722 FAKE_PID=$!
723 i=0
724 while [ $i -lt 100 ] && ! grep -q '^PORT ' "$BUILD_DIR/selftest/fake.out"; do
725 sleep 0.05
726 i=$((i + 1))
727 done
728 FAKE_PORT=$(sed -n 's/^PORT //p' "$BUILD_DIR/selftest/fake.out")
729 [ -n "$FAKE_PORT" ] || die "fake_model did not start"
730}
731
732stop_fake() {
733 if [ -n "$FAKE_PID" ]; then
734 kill "$FAKE_PID" 2>/dev/null || true
735 wait "$FAKE_PID" 2>/dev/null || true
736 FAKE_PID=""
737 fi
738}
739
740fake_run() { # name mode arms attempts -> sets FR_RC, SUMMARY
741 start_fake "$2" "$TASKS_DIR"
742 FR_RC=0
743 fr_out=$(sh "$SCRIPT_DIR/driver.sh" --run-model --endpoint "http://127.0.0.1:$FAKE_PORT" \
744 --model fake --langs om,c,py,rs --arms "$3" --attempts "$4" --out "$BUILD_DIR/selftest/$1" 2>&1) || FR_RC=$?
745 stop_fake
746 SUMMARY="$BUILD_DIR/selftest/$1/summary.txt"
747 say "--- run $1 (fake mode $2, arms $3, attempts $4): rc $FR_RC"
748 say "$fr_out"
749}
750
751self_test() {
752 . "$SCRIPT_DIR/audit.sh"
753 need_lang_tools "$ALL_LANGS"
754 check_sandbox
755 need_tool curl
756 rm -rf "$BUILD_DIR/selftest"
757 mkdir -p "$BUILD_DIR/selftest"
758 trap stop_fake EXIT
759 ntask=$(task_ids | wc -l)
760 say "== scorer"
761 rc=0
762 printf 'version 1\nattempts 2\ntask01 1 1 0 1 10 111 37 148\ntask02 1 1 0 1 10 111 37 148\n' |
763 "$BIN_DIR/scorer" > /dev/null || rc=$?
764 st_expect "scorer v1 all verified rc" 0 "$rc"
765 rc=0
766 printf 'version 9\nattempts 0\n' | "$BIN_DIR/scorer" > /dev/null 2>&1 || rc=$?
767 st_expect "scorer unknown version rc" 3 "$rc"
768 rc=0
769 printf 'version 1\nattempts 2\ntask01 1 1 0 1 10 111 37 148\n' | "$BIN_DIR/scorer" > /dev/null 2>&1 || rc=$?
770 st_expect "scorer truncated v1 rc" 2 "$rc"
771 rc=0
772 printf 'version 2\nattempts 1\ntask01 java plain 1 1 0 1 10 111 37 148\n' | "$BIN_DIR/scorer" > /dev/null 2>&1 || rc=$?
773 st_expect "scorer v2 unknown language rc" 2 "$rc"
774 rc=0
775 printf 'version 2\nattempts 1\ntask01 om plain 1 1 1 0 10 111 37 148\n' | "$BIN_DIR/scorer" > /dev/null || rc=$?
776 st_expect "scorer v2 refused compile rc (FAIL)" 1 "$rc"
777 audit_checks
778 memory_checks
779
780 say "== JSON edge (chat.om)"
781 rc=0
782 printf '{"error":{"message":"overloaded"}}' | "$BIN_DIR/chat" resp > /dev/null 3> /dev/null || rc=$?
783 st_expect "error object rc" 4 "$rc"
784 rc=0
785 printf '{"model":"m","choices":[{"message":{"content":"x"}}]}' | "$BIN_DIR/chat" resp > /dev/null 3> /dev/null || rc=$?
786 st_expect "response without usage rc" 4 "$rc"
787 rc=0
788 printf 'not json' | "$BIN_DIR/chat" resp > /dev/null 3> /dev/null || rc=$?
789 st_expect "non-JSON body rc" 4 "$rc"
790
791 say "== tasks"
792 if check_tasks; then st_ok "check-tasks"; else st_bad "check-tasks"; fi
793
794 fake_run good good plain 1
795 st_expect "good rc" 0 "$FR_RC"
796 st_expect "good global verdict" PASS "$(summary_status "$SUMMARY")"
797 for l in $ALL_LANGS; do
798 st_expect "good $l plain verdict" PASS "$(group_field "$SUMMARY" "$l" plain status)"
799 st_expect "good $l plain verified" "$ntask" "$(group_field "$SUMMARY" "$l" plain verified_count)"
800 st_expect "good $l plain first_attempt_verified" "$ntask" "$(group_field "$SUMMARY" "$l" plain first_attempt_verified)"
801 st_expect "good $l plain prompt_tokens" "$((ntask * 111))" "$(group_field "$SUMMARY" "$l" plain total_prompt_tokens)"
802 st_expect "good $l plain completion_tokens" "$((ntask * 37))" "$(group_field "$SUMMARY" "$l" plain total_completion_tokens)"
803 st_expect "good $l plain total_tokens" "$((ntask * 148))" "$(group_field "$SUMMARY" "$l" plain total_tokens)"
804 done
805 st_expect "good model reported" "fake-omega-bench" "$(awk 'NR==2{print $6}' "$BUILD_DIR/selftest/good/calls.txt")"
806 st_expect "good run saw no 503" "$((4 * ntask))" "$(awk 'NR>1 && $5==0' "$BUILD_DIR/selftest/good/busy.txt" | wc -l)"
807 st_expect "good run names its memory ceiling" "$MEM_MAX" "$(awk '$1=="memory_max_bytes"{print $2}' "$BUILD_DIR/selftest/good/run.txt")"
808 st_expect "good run: every attempt has compile and run peaks below the ceiling, no kill" "$((4 * ntask))" \
809 "$(awk -v m="$MEM_MAX" 'NR>1 && $5 ~ /^[0-9]+$/ && $6 ~ /^[0-9]+$/ && $5 < m && $6 < m && $7=="none"' "$BUILD_DIR/selftest/good/memory.txt" | wc -l)"
810 st_expect "good run names its task set" "$(task_set_sha256 "$SCRIPT_DIR")" \
811 "$(awk '$1=="task_set_sha256"{print $2}' "$BUILD_DIR/selftest/good/run.txt")"
812 for part in tasks/task01/expected.txt prompts/system-om.txt; do
813 tsd="$BUILD_DIR/selftest/taskset-$(printf '%s' "$part" | tr '/.' '--')"
814 mkdir -p "$tsd"
815 cp -R "$SCRIPT_DIR/tasks" "$SCRIPT_DIR/prompts" "$tsd/"
816 st_expect "task set copy digest ($part unchanged)" "$(task_set_sha256 "$SCRIPT_DIR")" "$(task_set_sha256 "$tsd")"
817 printf ' ' >> "$tsd/$part"
818 if [ "$(task_set_sha256 "$tsd")" = "$(task_set_sha256 "$SCRIPT_DIR")" ]; then
819 st_bad "task set digest ignored one added byte in $part"
820 else
821 st_ok "task set digest changes with one added byte in $part"
822 fi
823 done
824
825 BENCH_BUSY_SLEEP_S=0
826 export BENCH_BUSY_SLEEP_S
827 fake_run busy busy plain 1
828 st_expect "busy rc" 0 "$FR_RC"
829 st_expect "busy global verdict" PASS "$(summary_status "$SUMMARY")"
830 for l in $ALL_LANGS; do
831 st_expect "busy $l plain verified" "$ntask" "$(group_field "$SUMMARY" "$l" plain verified_count)"
832 st_expect "busy $l plain first_attempt_verified" "$ntask" "$(group_field "$SUMMARY" "$l" plain first_attempt_verified)"
833 st_expect "busy $l plain total_tokens (a 503 adds none)" "$((ntask * 148))" "$(group_field "$SUMMARY" "$l" plain total_tokens)"
834 done
835 st_expect "busy every request refused once, then answered" "$((4 * ntask))" \
836 "$(awk 'NR>1 && $5==1' "$BUILD_DIR/selftest/busy/busy.txt" | wc -l)"
837 st_expect "busy calls all 200" "$((4 * ntask))" "$(awk 'NR>1 && $5==200' "$BUILD_DIR/selftest/busy/calls.txt" | wc -l)"
838 unset BENCH_BUSY_SLEEP_S
839
840 fake_run bad bad plain 1
841 st_expect "bad rc" 0 "$FR_RC"
842 st_expect "bad global verdict" FAIL "$(summary_status "$SUMMARY")"
843 for l in $ALL_LANGS; do
844 st_expect "bad $l plain verdict" FAIL "$(group_field "$SUMMARY" "$l" plain status)"
845 st_expect "bad $l plain compiled" "$ntask" "$(group_field "$SUMMARY" "$l" plain compiled_count)"
846 st_expect "bad $l plain verified" 0 "$(group_field "$SUMMARY" "$l" plain verified_count)"
847 done
848
849 fake_run bad-then-good bad-then-good plain,feedback 2
850 st_expect "bad-then-good rc" 0 "$FR_RC"
851 st_expect "bad-then-good global verdict" FAIL "$(summary_status "$SUMMARY")"
852 for l in $ALL_LANGS; do
853 st_expect "bad-then-good $l plain verdict" FAIL "$(group_field "$SUMMARY" "$l" plain status)"
854 st_expect "bad-then-good $l feedback verdict" PASS "$(group_field "$SUMMARY" "$l" feedback status)"
855 st_expect "bad-then-good $l plain verified" 0 "$(group_field "$SUMMARY" "$l" plain verified_count)"
856 st_expect "bad-then-good $l plain attempts" "$((ntask * 2))" "$(group_field "$SUMMARY" "$l" plain attempts_total)"
857 st_expect "bad-then-good $l feedback verified" "$ntask" "$(group_field "$SUMMARY" "$l" feedback verified_count)"
858 st_expect "bad-then-good $l feedback first_attempt_verified" 0 "$(group_field "$SUMMARY" "$l" feedback first_attempt_verified)"
859 st_expect "bad-then-good $l feedback attempts" "$((ntask * 2))" "$(group_field "$SUMMARY" "$l" feedback attempts_total)"
860 st_expect "bad-then-good $l feedback total_tokens" "$((ntask * 2 * 148))" "$(group_field "$SUMMARY" "$l" feedback total_tokens)"
861 st_expect "bad-then-good $l feedback tokens_per_verified" "296.000" "$(group_field "$SUMMARY" "$l" feedback tokens_per_verified)"
862 done
863 st_expect "bad-then-good verified attempts are all attempt 2" "$((4 * ntask))" \
864 "$(awk '$3=="feedback" && $7==1 && $4==2' "$BUILD_DIR/selftest/bad-then-good/attempts.txt" | wc -l)"
865
866 fake_run refuse refuse plain 1
867 st_expect "refuse rc" 0 "$FR_RC"
868 st_expect "refuse global verdict" FAIL "$(summary_status "$SUMMARY")"
869 for l in $ALL_LANGS; do
870 st_expect "refuse $l plain verdict" FAIL "$(group_field "$SUMMARY" "$l" plain status)"
871 st_expect "refuse $l plain compiled" 0 "$(group_field "$SUMMARY" "$l" plain compiled_count)"
872 st_expect "refuse $l plain verified" 0 "$(group_field "$SUMMARY" "$l" plain verified_count)"
873 done
874 st_expect "refuse never ran a binary" 0 "$(find "$BUILD_DIR/selftest/refuse" -name out.txt | wc -l)"
875 st_expect "refuse memory.txt: compile peak, no run (-), no kill" "$((4 * ntask))" \
876 "$(awk 'NR>1 && NF==7 && $5 ~ /^[0-9]+$/ && $6=="-" && $7=="none"' "$BUILD_DIR/selftest/refuse/memory.txt" | wc -l)"
877 audit_reuse_check
878
879 say "== NOT_RUN paths"
880 start_fake good "$TASKS_DIR"
881 port=$FAKE_PORT
882 stop_fake
883 rc=0
884 out=$(sh "$SCRIPT_DIR/driver.sh" --run-model --endpoint "http://127.0.0.1:$port" --model fake \
885 --langs om --arms plain --attempts 1 --out "$BUILD_DIR/selftest/unreachable" 2>&1) || rc=$?
886 say "$out"
887 st_expect "unreachable endpoint rc" 3 "$rc"
888 case $out in *NOT_RUN*) st_ok "unreachable endpoint prints NOT_RUN" ;; *) st_bad "unreachable endpoint did not print NOT_RUN" ;; esac
889 start_fake good "$BUILD_DIR/selftest/no-such-tasks"
890 rc=0
891 out=$(sh "$SCRIPT_DIR/driver.sh" --run-model --endpoint "http://127.0.0.1:$FAKE_PORT" --model fake \
892 --langs om --arms plain --attempts 1 --out "$BUILD_DIR/selftest/http404" 2>&1) || rc=$?
893 stop_fake
894 say "$out"
895 st_expect "HTTP 404 rc" 3 "$rc"
896 rc=0
897 out=$(sh "$SCRIPT_DIR/driver.sh" --run-model --model fake 2>&1) || rc=$?
898 say "$out"
899 st_expect "missing --endpoint rc" 3 "$rc"
900 BENCH_BUSY_WAIT_S=0
901 export BENCH_BUSY_WAIT_S
902 fake_run busy-noretry busy plain 1
903 st_expect "busy with retries off rc" 3 "$FR_RC"
904 case $fr_out in
905 *"NOT_RUN: HTTP 503 (endpoint busy)"*) st_ok "busy with retries off prints NOT_RUN for the 503" ;;
906 *) st_bad "busy with retries off did not print NOT_RUN for the 503" ;;
907 esac
908 BENCH_BUSY_WAIT_S=1
909 BENCH_BUSY_SLEEP_S=1
910 export BENCH_BUSY_SLEEP_S
911 fake_run down down plain 1
912 st_expect "endpoint always busy (503 past BENCH_BUSY_WAIT_S=1) rc" 3 "$FR_RC"
913 case $fr_out in
914 *"NOT_RUN: HTTP 503 (endpoint busy)"*) st_ok "endpoint always busy prints NOT_RUN for the 503" ;;
915 *) st_bad "endpoint always busy did not print NOT_RUN for the 503" ;;
916 esac
917 BENCH_BUSY_WAIT_S=x
918 rc=0
919 out=$(sh "$SCRIPT_DIR/driver.sh" --run-model --endpoint http://127.0.0.1:9 --model fake 2>&1) || rc=$?
920 st_expect "nonnumeric BENCH_BUSY_WAIT_S rc" 2 "$rc"
921 unset BENCH_BUSY_WAIT_S BENCH_BUSY_SLEEP_S
922
923 if [ "$ST_FAIL" -eq 0 ]; then
924 say "SELF-TEST PASS"
925 return 0
926 fi
927 say "SELF-TEST FAIL"
928 return 1
929}
930
931# Reusable referee interface: no other mode changes its contract.
932verify_candidate() {
933 [ "$#" -eq 4 ] || die "--verify-candidate LANG TASK_ID CANDIDATE ABS_WORK"
934 vc_lang=$1 vc_task=$2 vc_candidate=$3 vc_work=$4
935 case $vc_lang in om|c|py|rs) ;; *) die "unknown referee language" ;; esac
936 case $vc_task in task[0-9][0-9]) ;; *) die "invalid task identity" ;; esac
937 [ -d "$TASKS_DIR/$vc_task" ] && [ ! -L "$TASKS_DIR/$vc_task" ] || die "unknown task identity"
938 for vc_path in "$vc_candidate" "$vc_work"; do
939 case $vc_path in /*) ;; *) die "referee paths must be absolute" ;; esac
940 case "$vc_path/" in */../*|*/./*|*'//'*) die "noncanonical referee path" ;; esac
941 vc_walk=$vc_path
942 while [ "$vc_walk" != / ]; do
943 [ ! -L "$vc_walk" ] || die "symbolic-link referee path"
944 vc_walk=$(dirname "$vc_walk")
945 done
946 done
947 [ -f "$vc_candidate" ] && [ ! -L "$vc_candidate" ] || die "candidate is not a regular file"
948 check_pin
949 check_sandbox
950 need_lang_tools "$vc_lang"
951 claim_output "$vc_work"
952 evaluate "$vc_lang" "$TASKS_DIR/$vc_task" "$vc_candidate" "$vc_work/eval"
953 say "COMP_RC=$COMP_RC RUN_RC=$RUN_RC VERIFIED=$VERIFIED"
954 [ "$VERIFIED" -eq 1 ]
955}
956
957# ---- main
958
959[ $# -ge 1 ] || usage
960mode=$1
961shift
962case $mode in
963 --verify-candidate) verify_candidate "$@" ;;
964 --task-set-sha256) [ "$#" -eq 0 ] || die "--task-set-sha256 takes no arguments"; task_set_sha256 "$SCRIPT_DIR" ;;
965 --sandbox) sandbox "$@" ;;
966 --output-probe) claim_output "$1" ;;
967 --evaluate-probe)
968 evaluate "$1" "$TASKS_DIR/task01" "$2" "$3"
969 say "COMP_RC=$COMP_RC RUN_RC=$RUN_RC VERIFIED=$VERIFIED MEM_KILL=$MEM_KILL" ;;
970 --deadline-probe)
971 evaluate py "$TASKS_DIR/task01" "$1" "$2"
972 [ "$COMP_RC" -eq 0 ] && [ "$VERIFIED" -eq 0 ] &&
973 { [ "$RUN_RC" -eq 124 ] || [ "$RUN_RC" -eq 137 ]; } ;;
974 --check-tasks) build_tools; check_tasks ;;
975 --self-test) build_tools; self_test ;;
976 --run-model)
977 case " $* " in *" --endpoint "*) build_tools ;; esac
978 run_model "$@" ;;
979 -h|--help) usage ;;
980 *) usage ;;
981esac