diff --git a/PROTOCOL.md b/PROTOCOL.md index 37c90d2..8ab4b84 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -291,3 +291,79 @@ on this one Spark, on the stated date and load. numbers is mixed into it. No `HeadToHead: ... FINAL IDLE` line (A5(h)) is on the BOARD as of 2026-10-29 22:15Z; the study takes `/tmp/aien-gb10.lock` only inside its own spark-window, under Drake's GPU authorization for this lane given on 2026-10-29. + + +### A8 (2026-10-29, before resumed 35B timing): external measurement integrity + +Numbered A8 and A9 because A6 is the llama.cpp methodology amendment on branch +`results/2026-10-27-a6` and A7 is the cold-start study above. + +Drake clarified that Aien architecture and structural implementation stay Python-free, while +external testing equipment, independent references and calculations may use Python, with Wolfram +preferred for calculations. These host measurement tools are external equipment; this amendment +introduces no Python production dependency. + +The legacy 35B runner could return success after a failed client, a missing foreign-process +monitor summary, an exhausted disturbed-cell retry, or a session timeout. Its Python client also +returned zero after failed HTTP requests and accepted truncated streams. Synthetic regressions +reproduced these paths before the fixes. New resumed runs use the following controls: + +- The client retains failed raw rows, requires content, a finish reason and the SSE DONE marker, + and returns nonzero if any request fails. Missing usage remains eligible for the original + separately labeled retokenization path; it is not invented by the client. +- No quiet gate means NOT_RUN. A monitor must exit 0 or 1 and provide exactly one summary with a + positive elapsed-tick count; missing or invalid kthread samples also mean NOT_RUN. Named + interference keeps the existing VOID rule and three-attempt limit. +- Every attempted cell records PASS, FAIL, NOT_RUN or VOID in `results/cell-status.jsonl`. + When that ledger exists, `bench/extract.py` admits only cell ids with exactly one PASS record. + Missing, duplicate or conflicting records exclude a cell. Historical runs without this ledger + retain the legacy extraction behavior and are not retrospectively qualified by this fix. +- DONE requires all fourteen declared cells accepted and no TIMEOUT. An incomplete session returns + nonzero and retains its rows and logs. Existing session files are refused rather than overwritten. + `H2H_RESULTS` selects a fresh results directory while leaving the frozen instruments and prompts + at `H2H_REPO`; for extraction, supply a parent directory containing that `results/` directory. + +CPU-only controls: `python3 bench/test-run-arm.py`, `python3 bench/test-bench-python.py`, and +`python3 bench/test-extract-admission.py`; shell syntax: `bash -n bench/run_arm.sh`. +This fixes acceptance/reporting defects only. The runner's shared-model coordination, lifecycle, +current source/weight verification and resumed 35B execution still require qualification before +use. The active 9B campaign uses frozen instruments recorded in its own manifest and is unchanged. + + +### A9 (2026-10-29, before resumed 35B timing): owned-process lifecycle + +The external runner now sources `bench/session-lifecycle.sh`. It tracks child process identities +using Linux `/proc//stat` starttime, rechecks identity before signaling, snapshots descendants, +waits for children, and refuses untracked or stale live process identities. A pid whose `/proc` +entry is already gone was reaped by the shell and is not waited for again: Bash 5.2 `wait` on it +from the EXIT trap that interrupted the client wait (the watchdog's TERM) blocked forever. It no +longer searches process command lines to decide which server to stop or count for memory. Native +server identity is published to the sampler because a sampler started before launch cannot see +later shell-variable updates; container memory sampling includes the owned container root and +descendants. + +Each container has a unique session name and `aien.stack-comparison.run` ownership label. Creation +completes before `docker start --attach`; missing images are refused with `--pull never`. Shutdown +checks the label before stopping a container. The historical shared container names are unused. + +EXIT, INT and TERM enter one cleanup path for the client, monitor, server, watchdog and samplers. +The client runs as a tracked child so the parent can interrupt its wait. The watchdog warns at +55 minutes from GPU-lock acquisition and ends request execution at 59 minutes, reserving the last +minute of the original 60-minute limit for cleanup. Cleanup gives process waits a shared 30-second +budget, bounds container stop and GPU inventory commands, and removes DONE on failure. These are +host-exercised controls; an actual model/session and unload-baseline qualification remain required. + +Before model launch, the GPU inventory must be empty. The runner itself never stops the shared +18091 model; the authorized exclusive-window controller must check activity, stop it only when +idle, and restore its exact configuration afterward. `H2H_GPU_LOCK_FD=9` permits that controller +to lend the already-open GPU-lock descriptor. The runner checks its path and acquires it +nonblockingly; cleanup preserves a borrowed lock so the controller can retain exclusivity through +restoration. A standalone runner releases only its own lock. + +CPU-only controls: `python3 bench/test-run-arm-lifecycle.py`, plus the A8 controls. Tests cover +foreign container refusal, labeled owned launch, create failure, normal/failing/interrupted exits, +watchdog interruption, stale/untracked process refusal, descendant shutdown, termination-resistant +children, sampler identity and parent-versus-child lock ownership. No GPU, real model or real +container is used by these controls. The active frozen 9B campaign is unchanged. Source and runtime +pins, the shared-service controller, unload/memory evidence and full 35B execution remain separate +requirements before this runner is used for the larger-model comparison. diff --git a/README.md b/README.md index 0167176..6af1142 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,63 @@ the CUDApp cutover; the CUDApp pin records the GPU-stack state at the time of th Omega replacement: none yet; an Omega HTTP/SSE client is the replacement path once the Omega standard library has sockets and threads. +## Measurement controls + +Before a resumed 35B run, check the external instruments with: + +```sh +python3 bench/test-run-arm.py +python3 bench/test-run-arm-lifecycle.py +python3 bench/test-unload-gates.py +python3 bench/test-shared-model-guard.py +python3 bench/test-shared-window.py +python3 bench/test-bench-python.py +python3 bench/test-extract-admission.py +bash -n bench/run_arm.sh +``` + +Protocol amendments A8 and A9 describe owned-process cleanup, per-cell admission records, failed-stream detection and refusal to +overwrite previous evidence. Passing these CPU-only controls does not qualify a model or complete +the GPU benchmark. Historical rows without an admission ledger retain their original limitations. + +The separate `shared-model-guard.py` checks the saved executable, arguments, working directory, +required environment, idle health, connections, GPU inventory and the coordinator-reviewed BOARD +checksum. Its stop mode signals a bound Linux process handle and refuses an exited handle. The +controller must record intent and undo before stopping, hold the GPU lock and restore the same +shared setup afterward. +Guard controls use fixtures and harmless child processes; they never access the shared model, +its port or GPU inventory. + +Session cleanup now enforces the protocol's unload gate: no GPU compute processes remain and +available memory is no more than 2 GiB below its pre-launch baseline. Missing or malformed +memory readings and failed GPU queries also fail the session and remove its DONE marker. +`unload-status.txt` records both checks; more available memory is acceptable. The check observes +memory after process cleanup without flushing caches or killing unrelated processes. A failure +requires investigation before another arm starts. Fixture tests exercise the actual cleanup +function; real-model unload and shared-service restoration still require hardware evidence. + +`bench/shared-window.py` integrates the guard, one arm session and same-configuration restoration. +It requires a fresh output directory, the saved process snapshot, exact file hashes in a JSON +mapping of absolute paths to SHA-256, and the checksum of BOARD after the coordinator has reviewed +live test activity. It appends intent and undo, then refuses if the board changes before stopping. +Required pins cover the controller, guard, launcher, snapshot, shared executable, runner and its +helpers and prompts, plus `arms.conf` if present. Prepare frozen copies and their pins before use. +The launcher contract is the existing 35B batch model with eight slots and context 49152; a different +snapshot is refused before stop. The controller does not authorize a model swap. + +The controller holds the global lock through restoration, passes descriptor 9 to the runner, and +closes it for the restored service. Failed or interrupted tests still attempt restoration only +after the original and runner have exited, GPU inventory is empty and memory has recovered. +It refuses overlapping launches and never kills a foreign process. A runner that cannot finish +cleanup retains its inherited lock; a failed recovery gate leaves the model unrestored and records +the reason in `window-result.json`. Such a failure requires investigation, not another launch. +Events, runner output and restoration output remain in the fresh attempt directory. + +Use `python3 bench/shared-window.py --help` for required arguments. Host-only controls exercise +sequencing and refusal paths, real fixture-child lock inheritance, and a fixture restoration +launcher. They do not establish real GPU unloading, actual shared-model recovery, or completion of +the larger-model comparison. Those hardware checks remain pending. + ## License Apache-2.0 WITH LLVM-exception, see [LICENSE](LICENSE). diff --git a/bench/bench.py b/bench/bench.py index b4c535a..478b9f7 100755 --- a/bench/bench.py +++ b/bench/bench.py @@ -38,6 +38,7 @@ def one_request(host, port, model, prompt, max_tokens, timeout=1800): "usage": None, "finish_reason": None, "error": None, "http_status": None, "busy_retries": 0} conn = None + done = False try: row["t_send"] = time.monotonic() while True: @@ -67,12 +68,16 @@ def one_request(host, port, model, prompt, max_tokens, timeout=1800): continue payload = line[5:].strip() if payload == b"[DONE]": + done = True break try: ev = json.loads(payload) except json.JSONDecodeError: row["error"] = "bad json chunk: " + payload[:200].decode(errors="replace") continue + if ev.get("error"): + row["error"] = "server error event: " + str(ev["error"])[:1000] + continue now = time.monotonic() if ev.get("usage"): row["usage"] = ev["usage"] @@ -92,6 +97,13 @@ def one_request(host, port, model, prompt, max_tokens, timeout=1800): finally: if conn is not None: conn.close() + if row["error"] is None: + if not done: + row["error"] = "stream ended without DONE" + elif not row["text"] or row["t_first"] is None or row["t_last"] is None: + row["error"] = "no content received" + elif not row["finish_reason"]: + row["error"] = "missing finish reason" return row @@ -144,12 +156,17 @@ def main(): ap.add_argument("--out", required=True) ap.add_argument("--cell-run", default="", help="id of this cell invocation (voiding unit, A2)") args = ap.parse_args() + if args.concurrency < 1 or args.reps < 1 or args.warmup < 0 or args.max_tokens < 1: + ap.error("concurrency, reps and max-tokens must be positive; warmup must be nonnegative") allp = [json.loads(l) for l in open(args.prompts) if l.strip()] if args.select: want = args.select.split(",") byid = {p["id"]: p for p in allp} allp = [byid[w] for w in want] + if not allp: + ap.error("prompt selection is empty") + failed = False with open(args.out, "a") as f: total = args.warmup + args.reps for k in range(total): @@ -168,12 +185,14 @@ def main(): f.write(json.dumps(r) + "\n") f.flush() err = r["error"] + failed = failed or bool(err) u = r["usage"] or {} print("%s %s %s rep=%d warm=%s c=%d i=%d pt=%s ct=%s err=%s" % ( args.arm, args.round, args.metric, rep, warm, r["concurrency"], r["stream_index"], u.get("prompt_tokens"), u.get("completion_tokens"), (err or "")[:120]), file=sys.stderr) + return 1 if failed else 0 if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/bench/extract.py b/bench/extract.py index 55d1ca4..aca5347 100755 --- a/bench/extract.py +++ b/bench/extract.py @@ -26,17 +26,28 @@ void = set() if os.path.exists(REPO + "/results/voids.jsonl"): void = {v["cell_run"] for v in map(json.loads, filter(str.strip, open(REPO + "/results/voids.jsonl"))) if honoured(v)} +# New runs are admitted per cell. A missing, duplicate or non-PASS record excludes the cell; +# untouched historical runs without a ledger retain their original extraction semantics. +admission = None +admission_path = REPO + "/results/cell-status.jsonl" +if os.path.exists(admission_path): + admission = {} + for line in open(admission_path): + entry = json.loads(line) + cr = entry["cell_run"] + admission[cr] = entry["status"] if cr not in admission else "DUPLICATE" + raw = [json.loads(line) for path in sorted(glob.glob(REPO + "/results/raw/*.jsonl")) for line in open(path)] first = {} # cell without its try suffix -> lowest non-void try number for r in raw: cr = r.get("cell_run") - if cr and cr not in void: + if cr and cr not in void and (admission is None or admission.get(cr) == "PASS"): cell, _, n = cr.rpartition("-t") first[cell] = min(first.get(cell, int(n)), int(n)) rows = [] for r in raw: cr = r.get("cell_run") - if r["warmup"] or r["arm"] == "STUB" or cr in void: + if r["warmup"] or r["arm"] == "STUB" or cr in void or (admission is not None and admission.get(cr) != "PASS"): continue if cr: cell, _, n = cr.rpartition("-t") diff --git a/bench/run_arm.sh b/bench/run_arm.sh index d0343b0..891112f 100755 --- a/bench/run_arm.sh +++ b/bench/run_arm.sh @@ -7,6 +7,8 @@ set -u ARM=$1; ROUND=$2 REPO=${H2H_REPO:-$(cd "$(dirname "$0")/.." && pwd)} +source "$REPO/bench/session-lifecycle.sh" || exit 2 +RUN_ID="${ARM,,}-${ROUND,,}-$(date +%s)-$$" H2H=${H2H:-/home/drakestapleton/h2h} MODEL=/home/drakestapleton/models/qwen3.6-35b-a3b-fp8-95a723d0 VLLM_IMG=nvcr.io/nvidia/vllm@sha256:557747337846eecf34486866f3d992383c6f8af869fdb0e365b5093fcaee02c2 @@ -21,9 +23,15 @@ SGLANG_IMG=; MODEL4=; GGUF4= BOARD=/home/drakestapleton/handoffs/BOARD.md VLLM_UTIL=${VLLM_UTIL:-0.50} SGLANG_MEM=${SGLANG_MEM:-0.50} -OUT=$REPO/results/raw/$ARM-$ROUND.jsonl -LOGD=$REPO/results/logs/$ARM-$ROUND +RESULTS=${H2H_RESULTS:-$REPO/results} +OUT=$RESULTS/raw/$ARM-$ROUND.jsonl +LOGD=$RESULTS/logs/$ARM-$ROUND +if [ -e "$OUT" ] || [ -e "$LOGD" ]; then + echo "refusing to overwrite an existing session: $LOGD or $OUT" >&2 + exit 2 +fi mkdir -p "$LOGD" "$(dirname "$OUT")" +touch "$RESULTS/cell-status.jsonl" || exit 2 ts() { date -u +%Y-%m-%dT%H:%M:%SZ; } board() { echo "$(ts) HeadToHead: $*" >> "$BOARD"; echo "$(ts) $*" >> "$LOGD/session.log"; } notrun() { board "$ARM $ROUND NOT_RUN: $*"; echo "$*" > "$LOGD/NOT_RUN"; exit 4; } @@ -31,10 +39,10 @@ memavail() { awk '/MemAvailable/{print $2}' /proc/meminfo; } CTR= case $ARM in OURS) PORT=18190; PAT='aien-serve-http.*--port 18190'; MID=qwen3.6-35b-a3b-fp8 ;; - VLLM) PORT=18191; PAT='vllm serve|VLLM::|EngineCore'; MID=q36; CTR=h2h-vllm; MDIR=$MODEL ;; - VLLM4) PORT=18191; PAT='vllm serve|VLLM::|EngineCore'; MID=q36; CTR=h2h-vllm; MDIR=$MODEL4 ;; - SGLANG) PORT=18194; PAT='sglang'; MID=q36; CTR=h2h-sglang; MDIR=$MODEL ;; - SGLANG4) PORT=18194; PAT='sglang'; MID=q36; CTR=h2h-sglang; MDIR=$MODEL4 ;; + VLLM) PORT=18191; PAT='vllm serve|VLLM::|EngineCore'; MID=q36; CTR=stack-h2h-$RUN_ID; MDIR=$MODEL ;; + VLLM4) PORT=18191; PAT='vllm serve|VLLM::|EngineCore'; MID=q36; CTR=stack-h2h-$RUN_ID; MDIR=$MODEL4 ;; + SGLANG) PORT=18194; PAT='sglang'; MID=q36; CTR=stack-h2h-$RUN_ID; MDIR=$MODEL ;; + SGLANG4) PORT=18194; PAT='sglang'; MID=q36; CTR=stack-h2h-$RUN_ID; MDIR=$MODEL4 ;; LLAMA) PORT=18192; PAT='llama-server.*--port 18192'; MID=q36; G=$GGUF; MMAP= ;; LLAMA16) PORT=18193; PAT='llama-server.*--port 18193'; MID=q36; G=$GGUF16; MMAP=--no-mmap ;; LLAMA4) PORT=18192; PAT='llama-server.*--port 18192'; MID=q36; G=$GGUF4; MMAP= ;; @@ -77,12 +85,28 @@ wait_quiet() { # PROTOCOL A2: before each cell, no foreign process >20% CPU ove sampler() { # 1 Hz: epoch MemAvailable_kB summed_RSS_kB load1 kthread_psr while :; do - rss=$(for p in $(pgrep -f "$PAT"); do awk '/VmRSS/{print $2}' /proc/$p/status 2>/dev/null; done | awk '{s+=$1}END{print s+0}') + rss=$(for p in $(server_pids); do awk '/VmRSS/{print $2}' /proc/$p/status 2>/dev/null; done | awk '{s+=$1}END{print s+0}') echo "$(date +%s) $(memavail) $rss $(cut -d' ' -f1 /proc/loadavg) $(ktpsr)" sleep 1 done } +server_pids() { + if [ -n "$CTR" ]; then + [ "$(docker inspect -f '{{index .Config.Labels "aien.stack-comparison.run"}}' "$CTR" 2>/dev/null)" = "$RUN_ID" ] || return 1 + local root + root=$(docker inspect -f '{{.State.Pid}}' "$CTR" 2>/dev/null) || return 1 + h2h_descendant_pids "$root" + elif [ -s "$LOGD/server-identity.txt" ]; then + local root expected identity state birth parent + read -r root expected < "$LOGD/server-identity.txt" || return 1 + identity=$(h2h_identity "$root") || return 1 + read -r state birth parent <<< "$identity" + [ "$birth" = "$expected" ] || return 1 + h2h_descendant_pids "$root" + fi +} + start_server() { case $ARM in OURS) @@ -93,34 +117,43 @@ start_server() { --max-tokens-cap 16384 --thinking off --batch-slots 8 ) < /dev/null > "$LOGD/server.log" 2>&1 & SPID=$! ;; VLLM|VLLM4) - docker run --rm --name h2h-vllm --runtime nvidia --gpus all --ipc host --network host \ + timeout 30 docker create --pull never --rm --name "$CTR" --label "aien.stack-comparison.run=$RUN_ID" --runtime nvidia --gpus all --ipc host --network host \ --cpuset-cpus $SRV_CPUS -v "$MDIR":/model:ro "$VLLM_IMG" vllm serve /model --served-model-name q36 \ --host 127.0.0.1 --port 18191 \ --max-model-len 49152 --max-num-seqs 32 --gpu-memory-utilization "$VLLM_UTIL" \ - --language-model-only < /dev/null > "$LOGD/server.log" 2>&1 & + --language-model-only < /dev/null > "$LOGD/container-id.txt" 2> "$LOGD/server.log" || return 1 + docker start --attach "$CTR" < /dev/null >> "$LOGD/server.log" 2>&1 & SPID=$! ;; SGLANG|SGLANG4) - docker run --rm --name h2h-sglang --runtime nvidia --gpus all --ipc host --network host \ + timeout 30 docker create --pull never --rm --name "$CTR" --label "aien.stack-comparison.run=$RUN_ID" --runtime nvidia --gpus all --ipc host --network host \ --cpuset-cpus $SRV_CPUS -v "$MDIR":/model:ro "$SGLANG_IMG" python3 -m sglang.launch_server \ --model-path /model --served-model-name q36 --host 127.0.0.1 --port 18194 \ --context-length 49152 --max-running-requests 32 --mem-fraction-static "$SGLANG_MEM" \ - < /dev/null > "$LOGD/server.log" 2>&1 & + < /dev/null > "$LOGD/container-id.txt" 2> "$LOGD/server.log" || return 1 + docker start --attach "$CTR" < /dev/null >> "$LOGD/server.log" 2>&1 & SPID=$! ;; LLAMA*) LD_LIBRARY_PATH=$CUDART_DIR:$LLAMA_DIR taskset -c $SRV_CPUS "$LLAMA_DIR/llama-server" -m "$G" --host 127.0.0.1 \ --port $PORT -ngl 999 -fa on -c 393216 -np 32 --jinja $MMAP < /dev/null > "$LOGD/server.log" 2>&1 & SPID=$! ;; esac + h2h_track "$SPID" || return 1 + printf '%s %s\n' "$SPID" "${H2H_PID_START[$SPID]}" > "$LOGD/server-identity.txt" } stop_server() { - case $ARM in - VLLM*|SGLANG*) docker stop -t 60 $CTR >/dev/null 2>&1 ;; - *) kill -TERM $SPID 2>/dev/null ;; - esac - for i in $(seq 1 120); do kill -0 $SPID 2>/dev/null || break; sleep 1; done - kill -KILL $SPID 2>/dev/null - for i in $(seq 1 60); do pgrep -f "$PAT" >/dev/null || break; sleep 1; done + if [ -n "$CTR" ] && docker inspect "$CTR" >/dev/null 2>&1; then + local owner + owner=$(docker inspect -f '{{index .Config.Labels "aien.stack-comparison.run"}}' "$CTR" 2>/dev/null) + if [ "$owner" != "$RUN_ID" ]; then + echo "refusing to stop container owned by another session: $CTR" >&2 + return 1 + fi + timeout 15 docker stop -t 10 "$CTR" >/dev/null 2>&1 || { + docker inspect "$CTR" >/dev/null 2>&1 && return 1 + } + fi + if [ -n "$SPID" ]; then h2h_stop "$SPID" || return 1; SPID=; fi } ready() { @@ -137,47 +170,160 @@ loopback_only() { # A5(f): every listener on the test port must be 127.0.0.1, e [ -s "$LOGD/listen.txt" ] && ! awk '{print $4}' "$LOGD/listen.txt" | grep -qv '^127\.0\.0\.1:' } +cell_status() { + python3 -c 'import json,sys; print(json.dumps({"cell_run":sys.argv[1],"status":sys.argv[2]}))' \ + "$1" "$2" >> "$RESULTS/cell-status.jsonl" +} + cell() { # metric concurrency max_tokens promptfile [extra] # A2: a cell is VOID and re-run (<=3 tries) when the nvidia-modeset kthread was sampled on a server # core, or a process outside HeadToHead used >20% of one server core (bench/coremon.py) local metric=$1 c=$2 mt=$3 pf=$4; shift 4 - local try t0 t1 hit cm cmrc why off + local try t0 t1 hit cm cmrc why off clientrc mkdir -p "$LOGD/coremon" for try in 1 2 3; do - [ -e "$LOGD/TIMEOUT" ] && return - wait_quiet || { echo "$(ts) cell $metric ran without a quiet window (LOADED)" >> "$LOGD/session.log"; } local id="$ARM-$ROUND-$metric-t$try" + [ -e "$LOGD/TIMEOUT" ] && { cell_status "$id" NOT_RUN; return 1; } + wait_quiet || { echo "$(ts) cell $metric NOT_RUN: no quiet window" >> "$LOGD/session.log"; cell_status "$id" NOT_RUN; return 1; } taskset -c $MON_CPU python3 "$REPO/bench/coremon.py" --cpus $SRV_CPUS --exclude-tree $(mytree) \ --out "$LOGD/coremon/$id.jsonl" & cm=$! + CMON_PID=$cm + h2h_track "$cm" || return 1 t0=$(date +%s) taskset -c $CLI_CPUS python3 "$REPO/bench/bench.py" --port $PORT --model $MID --arm $ARM --round $ROUND --metric "$metric" \ - --prompts "$REPO/prompts/$pf" --concurrency $c --max-tokens $mt --out "$OUT" --cell-run "$id" "$@" 2>> "$LOGD/client.log" - kill -TERM $cm; wait $cm; cmrc=$? + --prompts "$REPO/prompts/$pf" --concurrency $c --max-tokens $mt --out "$OUT" --cell-run "$id" "$@" 2>> "$LOGD/client.log" & CPID=$! + h2h_track "$CPID" || return 1 + wait "$CPID"; clientrc=$? + unset 'H2H_PID_START[$CPID]'; CPID= + h2h_matches "$cm" && kill -TERM "$cm" 2>/dev/null || true + wait "$cm"; cmrc=$? + unset 'H2H_PID_START[$cm]'; CMON_PID= + if [ "$clientrc" -ne 0 ]; then + echo "$(ts) $id FAIL: client exit $clientrc; raw rows retained" >> "$LOGD/session.log" + cell_status "$id" FAIL + return 1 + fi + if [ "$cmrc" -ne 0 ] && [ "$cmrc" -ne 1 ]; then + echo "$(ts) $id foreign-process check NOT_RUN: monitor exit $cmrc" >> "$LOGD/session.log" + cell_status "$id" NOT_RUN + return 1 + fi sleep 2; t1=$(date +%s) + if ! awk -v a=$t0 -v b=$t1 '$1>=a && $1<=b {n++; if ($5 !~ /^[0-9]+$/) bad=1} END{exit (!n || bad)}' "$LOGD/mem.tsv"; then + echo "$(ts) $id kthread check NOT_RUN: missing or invalid samples" >> "$LOGD/session.log" + cell_status "$id" NOT_RUN + return 1 + fi hit=$(awk -v a=$t0 -v b=$t1 -v s="$SRV_LIST" '$1>=a && $1<=b && index(s, " "$5" ") {print $5; exit}' "$LOGD/mem.tsv") why= [ -n "$hit" ] && why="nvidia-modeset kthread on server core $hit" # A4: only a coremon summary that names offenders voids the cell; a monitor that wrote no # summary is recorded as "foreign check NOT_RUN" for that cell, never as a void off=$(python3 -c 'import json,sys -s=[json.loads(l) for l in open(sys.argv[1]) if "\"summary\"" in l] -print(json.dumps(s[-1]["offenders"]) if s else "NOSUMMARY")' "$LOGD/coremon/$id.jsonl" 2>/dev/null || echo NOSUMMARY) +rows=[json.loads(l) for l in open(sys.argv[1])] +s=[r for r in rows if r.get("summary") is True] +if len(s)!=1 or not isinstance(s[0].get("elapsed_ticks"),int) or s[0]["elapsed_ticks"]<=0 or not isinstance(s[0].get("offenders"),list): + print("NOSUMMARY") +else: + print(json.dumps(s[0]["offenders"]))' "$LOGD/coremon/$id.jsonl" 2>/dev/null || echo NOSUMMARY) case $off in - NOSUMMARY) echo "$(ts) $id foreign-process check NOT_RUN: coremon exit $cmrc, no summary" >> "$LOGD/session.log" ;; - '[]') ;; + NOSUMMARY) echo "$(ts) $id foreign-process check NOT_RUN: coremon exit $cmrc, no summary" >> "$LOGD/session.log"; cell_status "$id" NOT_RUN; return 1 ;; + '[]') [ "$cmrc" -eq 0 ] || { echo "$(ts) $id FAIL: monitor exit disagrees with clean summary" >> "$LOGD/session.log"; cell_status "$id" FAIL; return 1; } ;; *) why="${why:+$why; }foreign process >20% of a server core: $(echo "$off" | cut -c1-300)" ;; esac - if [ -z "$why" ]; then return; fi + if [ -z "$why" ]; then + cell_status "$id" PASS || return 1 + CELLS_COMPLETED=$((CELLS_COMPLETED + 1)) + return 0 + fi python3 -c 'import json,sys; print(json.dumps({"cell_run": sys.argv[1], "reason": sys.argv[2], "t0": int(sys.argv[3]), "t1": int(sys.argv[4])}))' \ - "$id" "$why" $t0 $t1 >> "$REPO/results/voids.jsonl" + "$id" "$why" $t0 $t1 >> "$RESULTS/voids.jsonl" + cell_status "$id" VOID || return 1 echo "$(ts) VOID $id: $why" >> "$LOGD/session.log" done + echo "$(ts) $metric NOT_RUN: all three attempts disturbed" >> "$LOGD/session.log" + return 1 +} + +mark_complete() { + if [ "$CELLS_COMPLETED" -ne 14 ] || [ -e "$LOGD/TIMEOUT" ]; then + echo "incomplete: $CELLS_COMPLETED/14 accepted cells; see session.log" > "$LOGD/INCOMPLETE" + return 1 + fi + touch "$LOGD/DONE" +} + +start_watchdog() { + ( + if [ "$#" -ge 1 ]; then sleep "$1"; + else delay=$((3300 - SECONDS)); [ "$delay" -le 0 ] || sleep "$delay"; fi + board "T-5 $ARM $ROUND: cleanup reserved within 60-minute limit" + if [ "$#" -ge 2 ]; then sleep "$2"; + else delay=$((3540 - SECONDS)); [ "$delay" -le 0 ] || sleep "$delay"; fi + touch "$LOGD/TIMEOUT" + board "$ARM $ROUND reached 59 min; stopping own session with cleanup time reserved" + kill -TERM $$ + ) & WD=$! + h2h_track "$WD" +} + +cleanup_session() { + local rc=$? pid + trap - EXIT + trap '' INT TERM + H2H_STOP_DEADLINE=$((SECONDS + 30)) + for pid in "$WD" "$CPID" "$CMON_PID"; do + [ -z "$pid" ] || h2h_stop "$pid" || rc=1 + done + stop_server || rc=1 + for pid in "$SAMP" "$VMS"; do + [ -z "$pid" ] || h2h_stop "$pid" || rc=1 + done + if [ "$GPU_LOCK_HELD" = 1 ]; then + timeout 5 nvidia-smi --query-compute-apps=pid,name,used_memory --format=csv > "$LOGD/gpu-after.csv" 2>&1 || rc=1 + AFTER=$(memavail) + echo "after_memavail_kB $AFTER" >> "$LOGD/mem-baseline.txt" + # Recording the inventory alone does not prove that the model unloaded. + local remaining_gpu + if ! remaining_gpu=$(timeout 5 nvidia-smi --query-compute-apps=pid --format=csv,noheader,nounits); then + echo "FAIL GPU inventory unavailable after unload" >> "$LOGD/unload-status.txt" + rc=1 + elif [ -n "$remaining_gpu" ]; then + echo "FAIL GPU processes remain after unload" >> "$LOGD/unload-status.txt" + rc=1 + else + echo "PASS no GPU compute processes remain" >> "$LOGD/unload-status.txt" + fi + # /proc/meminfo reports KiB. Refuse missing/malformed/overflow-sized samples. + if [[ ! "$BASE" =~ ^[0-9]{1,12}$ || ! "$AFTER" =~ ^[0-9]{1,12}$ ]]; then + echo "FAIL unavailable or invalid memory baseline/sample" >> "$LOGD/unload-status.txt" + rc=1 + elif (( 10#$BASE == 0 || 10#$AFTER == 0 || 10#$BASE - 10#$AFTER > 2 * 1024 * 1024 )); then + echo "FAIL memory did not recover within 2 GiB of baseline" >> "$LOGD/unload-status.txt" + rc=1 + else + echo "PASS memory recovered within 2 GiB of baseline" >> "$LOGD/unload-status.txt" + fi + echo "kthread_psr_end $(ktpsr)" >> "$LOGD/session.log" + board "END $ARM $ROUND own session stopped at $SECONDS s; memavail base=${BASE}kB after=${AFTER}kB; exit=$rc" + if [ "$GPU_LOCK_RELEASE" = 1 ]; then flock -u 9 || rc=1; fi + fi + if [ "$rc" -ne 0 ]; then + rm -f "$LOGD/DONE" + echo "session exit $rc; see session.log" >> "$LOGD/INCOMPLETE" + fi + exit "$rc" } # ---- session ---- # PROTOCOL A2 (Main's gate): start only when no foreign process used >20% CPU for 60 s and load1 < 6, # before taking the lock, so the 60-min hold is not spent waiting -SPID= +SPID= CPID= CMON_PID= WD= SAMP= VMS= BASE= GPU_LOCK_HELD=0 GPU_LOCK_RELEASE=1 +trap cleanup_session EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +CELLS_COMPLETED=0 +SESSION_RC=1 case $ARM in SGLANG*) [ -n "$SGLANG_IMG" ] || notrun "no SGLang image verified for aarch64/sm_121 (bench/arms.conf)" ;; esac @@ -194,56 +340,62 @@ for pair in LLAMA:convert.log LLAMA16:convert-bf16.log; do # the GGUF must be f sleep 30 done done -exec 9>/tmp/aien-gb10.lock -echo "$(ts) quiet: $(tail -1 "$LOGD/quiet.jsonl"); waiting for /tmp/aien-gb10.lock" >> "$LOGD/session.log" -flock -w 900 9 || { board "$ARM $ROUND NOT STARTED: /tmp/aien-gb10.lock busy 900 s"; exit 3; } +if [ "${H2H_GPU_LOCK_FD:-}" = 9 ]; then + GPU_LOCK_RELEASE=0 + [ "$(readlink /proc/$$/fd/9)" = /tmp/aien-gb10.lock ] || notrun "inherited GPU-lock descriptor names another file" + flock -n 9 || notrun "inherited GPU-lock descriptor cannot acquire the lock" +else + exec 9>/tmp/aien-gb10.lock + echo "$(ts) quiet: $(tail -1 "$LOGD/quiet.jsonl"); waiting for /tmp/aien-gb10.lock" >> "$LOGD/session.log" + flock -w 900 9 || { board "$ARM $ROUND NOT STARTED: /tmp/aien-gb10.lock busy 900 s"; exit 3; } +fi +GPU_LOCK_HELD=1 SECONDS=0 board "START $ARM $ROUND gpu lock held (<=60 min; test port $PORT; live 18091 untouched)" echo "kthread_psr_start $(ktpsr)" >> "$LOGD/session.log" pick_srv echo "server_cpus $SRV_CPUS client_cpus $CLI_CPUS monitor_cpu $MON_CPU" >> "$LOGD/session.log" -nvidia-smi --query-compute-apps=pid,name,used_memory --format=csv > "$LOGD/gpu-before.csv" 2>&1 +timeout 5 nvidia-smi --query-compute-apps=pid,name,used_memory --format=csv > "$LOGD/gpu-before.csv" 2>&1 || notrun "GPU process inventory failed" +GPU_ROWS=$(timeout 5 nvidia-smi --query-compute-apps=pid --format=csv,noheader,nounits) || notrun "GPU process inventory failed" +[ -z "$GPU_ROWS" ] || notrun "another model/process is resident; shared-service window must be coordinated before launch" BASE=$(memavail); echo "baseline_memavail_kB $BASE" > "$LOGD/mem-baseline.txt" sampler > "$LOGD/mem.tsv" & SAMP=$! +h2h_track "$SAMP" || exit 1 vmstat -t 1 > "$LOGD/vmstat.txt" & VMS=$! +h2h_track "$VMS" || exit 1 +start_watchdog || exit 1 T0=$(date +%s.%N) -start_server -( sleep 3300; board "T-5 $ARM $ROUND: gpu lock released by 60 min" ; sleep 300; \ - touch "$LOGD/TIMEOUT"; board "$ARM $ROUND hit 60 min; harness stops its server"; stop_server ) & WD=$! +start_server || { board "$ARM $ROUND NOT_RUN: launch failed"; exit 4; } if ready && loopback_only; then echo "load_seconds $(echo "$(date +%s.%N) - $T0" | bc)" >> "$LOGD/session.log" case $ARM in LLAMA*) LD_LIBRARY_PATH=$CUDART_DIR:$LLAMA_DIR "$LLAMA_DIR/llama-server" --version > "$LOGD/version.txt" 2>&1 ;; esac [ -n "$CTR" ] && docker exec $CTR pip list 2>/dev/null | grep -i -E '^(vllm|sglang|torch|transformers|flashinfer)' > "$LOGD/version.txt" for c in 1 4 8 16; do [ -e "$LOGD/TIMEOUT" ] && break - cell decode-c$c $c 256 decode.jsonl --warmup 2 --reps 3 + cell decode-c$c $c 256 decode.jsonl --warmup 2 --reps 3 || break done for p in p256 p2k p8k; do + [ "$CELLS_COMPLETED" -ge 4 ] || break [ -e "$LOGD/TIMEOUT" ] && break - cell prefill-$p 1 1 prefill.jsonl --select $p --warmup 2 --reps 3 --nonce + cell prefill-$p 1 1 prefill.jsonl --select $p --warmup 2 --reps 3 --nonce || break done - [ -e "$LOGD/TIMEOUT" ] || cell agree 1 128 decode.jsonl --warmup 0 --reps 16 + if [ "$CELLS_COMPLETED" -eq 7 ] && [ ! -e "$LOGD/TIMEOUT" ]; then + cell agree 1 128 decode.jsonl --warmup 0 --reps 16 || true + fi # A3 grid: N = 1, 8, 32 streams x prompt 512 / 8k tokens, 256 new tokens, 1 warmup + 3 runs for p in p512 p8k; do + [ "$CELLS_COMPLETED" -ge 8 ] || break for n in 1 8 32; do [ -e "$LOGD/TIMEOUT" ] && break - cell grid-$p-n$n $n 256 prefill.jsonl --select $p --warmup 1 --reps 3 --nonce + cell grid-$p-n$n $n 256 prefill.jsonl --select $p --warmup 1 --reps 3 --nonce || break 2 done done board "$ARM $ROUND cells done at $SECONDS s" - touch "$LOGD/DONE" + if mark_complete; then SESSION_RC=0; fi else if [ -s "$LOGD/listen.txt" ]; then why="FAIL: listener on port $PORT is not loopback-only (listen.txt); server stopped" else why="server did not become ready (see results/logs/$ARM-$ROUND/server.log)"; fi echo "$why" > "$LOGD/NOT_RUN" board "$ARM $ROUND NOT_RUN: $why" fi -stop_server -kill $WD 2>/dev/null; pkill -P $WD 2>/dev/null -sleep 5 -kill $SAMP $VMS 2>/dev/null -nvidia-smi --query-compute-apps=pid,name,used_memory --format=csv > "$LOGD/gpu-after.csv" 2>&1 -AFTER=$(memavail); echo "after_memavail_kB $AFTER" >> "$LOGD/mem-baseline.txt" -echo "kthread_psr_end $(ktpsr)" >> "$LOGD/session.log" -board "END $ARM $ROUND gpu lock released after $SECONDS s; memavail base=${BASE}kB after=${AFTER}kB" -flock -u 9 +exit "$SESSION_RC" diff --git a/bench/session-lifecycle.sh b/bench/session-lifecycle.sh new file mode 100644 index 0000000..238aa08 --- /dev/null +++ b/bench/session-lifecycle.sh @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +# External benchmark process ownership. Source from a Bash runner; no model/GPU access here. +# Linux proc_pid_stat(5): after comm, state is index0, ppid index1 and starttime index19. +declare -A H2H_PID_START=() + +h2h_identity() { + local pid=$1 line rest + local -a fields + [[ "$pid" =~ ^[1-9][0-9]*$ ]] || return 1 + { IFS= read -r line < "/proc/$pid/stat"; } 2>/dev/null || return 1 + rest=${line##*) } + read -r -a fields <<< "$rest" + [ "${#fields[@]}" -ge 20 ] || return 1 + printf '%s %s %s\n' "${fields[0]}" "${fields[19]}" "${fields[1]}" +} + +h2h_track() { + local pid=$1 owner=$BASHPID identity state birth parent + identity=$(h2h_identity "$pid") || { H2H_PID_START[$pid]=gone; wait "$pid" 2>/dev/null || true; return 0; } + read -r state birth parent <<< "$identity" + [ "$parent" = "$owner" ] || { echo "refusing to track non-child process $pid" >&2; return 1; } + H2H_PID_START[$pid]=$birth +} + +h2h_matches() { + local pid=$1 identity state birth parent + [ -n "${H2H_PID_START[$pid]:-}" ] || return 1 + identity=$(h2h_identity "$pid") || return 1 + read -r state birth parent <<< "$identity" + [ "$birth" = "${H2H_PID_START[$pid]}" ] && [ "$state" != Z ] && [ "$state" != X ] +} + +h2h_tree_snapshot() { + local root=$1 pid identity state birth parent changed=1 + local -A parents=() births=() keep=() + keep[$root]=1 + while read -r pid parent; do parents[$pid]=$parent; done < <(ps -e -o pid=,ppid=) + while [ "$changed" = 1 ]; do + changed=0 + for pid in "${!parents[@]}"; do + if [ -n "${keep[${parents[$pid]}]:-}" ] && [ -z "${keep[$pid]:-}" ]; then + keep[$pid]=1; changed=1 + fi + done + done + h2h_matches "$root" || return 0 + for pid in "${!keep[@]}"; do + identity=$(h2h_identity "$pid") || continue + read -r state birth parent <<< "$identity" + if [ "$pid" = "$root" ]; then + [ "$birth" = "${H2H_PID_START[$root]}" ] || return 0 + else + [ "$parent" = "${parents[$pid]}" ] || continue + fi + births[$pid]=$birth + done + h2h_matches "$root" || return 0 + for pid in "${!births[@]}"; do printf '%s %s\n' "$pid" "${births[$pid]}"; done +} + +h2h_descendant_pids() { + local root=$1 + [[ "$root" =~ ^[1-9][0-9]*$ ]] || return 1 + ps -e -o pid=,ppid= | awk -v root="$root" ' + {parent[$1]=$2; present[$1]=1} + END { + if (!present[root]) exit + keep[root]=1; changed=1 + while (changed) {changed=0; for (p in parent) if (keep[parent[p]] && !keep[p]) {keep[p]=1;changed=1}} + for (p in keep) if (keep[p]) print p + }' +} + +# Reap an exited child of this shell without blocking on a pid that is already gone. +# A pid with no /proc entry was reaped by this shell already; Bash 5.2 `wait` on it +# from an EXIT trap that interrupted another `wait` (the watchdog's TERM) can block +# forever. A pid that is not this shell's child cannot be waited for either. +h2h_reap() { + local identity state birth parent + identity=$(h2h_identity "$1") || return 0 + read -r state birth parent <<< "$identity" + [ "$parent" = "$BASHPID" ] || return 0 + wait "$1" 2>/dev/null || true +} + +h2h_stop() { + local pid=$1 attempts=${2:-600} child birth attempt alive + local -a tree=() + [ -n "${H2H_PID_START[$pid]:-}" ] || { echo "refusing to stop untracked process $pid" >&2; return 1; } + if ! h2h_matches "$pid"; then + local identity state current parent + if identity=$(h2h_identity "$pid"); then + read -r state current parent <<< "$identity" + if [ "$state" != Z ] && [ "$state" != X ]; then + echo "refusing stale process identity $pid" >&2 + return 1 + fi + fi + h2h_reap "$pid" + unset 'H2H_PID_START[$pid]' + return 0 + fi + if h2h_matches "$pid"; then + while read -r child birth; do + H2H_PID_START[$child]=$birth + tree+=("$child") + done < <(h2h_tree_snapshot "$pid") + for child in "${tree[@]}"; do + h2h_matches "$child" && kill -TERM "$child" 2>/dev/null || true + done + for ((attempt=0; attempt/dev/null || true + done + fi + h2h_reap "$pid" + for ((attempt=0; attempt<20; attempt++)); do + if [ -n "${H2H_STOP_DEADLINE:-}" ] && [ "$SECONDS" -ge "$H2H_STOP_DEADLINE" ]; then break; fi + alive=0 + for child in "${tree[@]}"; do h2h_matches "$child" && alive=1; done + [ "$alive" = 0 ] && break + sleep 0.1 + done + for child in "${tree[@]}"; do + if h2h_matches "$child"; then echo "owned process $child still live after shutdown" >&2; return 1; fi + unset 'H2H_PID_START[$child]' + done + unset 'H2H_PID_START[$pid]' +} diff --git a/bench/shared-model-guard.py b/bench/shared-model-guard.py new file mode 100644 index 0000000..7622a49 --- /dev/null +++ b/bench/shared-model-guard.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""External benchmark guard. Default checks only; --stop requires all idle/identity gates. + +This is test equipment, not part of Aien architecture or model-serving dependencies. +Never invoke against the shared service during an active test. The enclosing controller must +record its intent/undo on BOARD before calling, retain the GPU lock, and restore the same setup. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import select +import signal +import subprocess +import time +import urllib.request + + +class Refused(RuntimeError): + pass + + +def digest(path): + with open(path,'rb') as source: + return hashlib.file_digest(source,'sha256').hexdigest() + + +def process_identity(pid, snapshot, expected_sha256, proc_root=Path('/proc')): + root=proc_root/str(pid) + actual={'exe':os.readlink(root/'exe'),'cwd':os.readlink(root/'cwd'), + 'argv':(root/'cmdline').read_bytes().decode().rstrip('\0').split('\0')} + for key in ['exe','cwd','argv']: + if actual[key]!=snapshot[key]: + raise Refused('shared model '+key+' changed') + if digest(root/'exe')!=expected_sha256 or digest(snapshot['exe'])!=expected_sha256: + raise Refused('shared model executable digest changed') + env={} + for entry in (root/'environ').read_bytes().split(b'\0'): + if b'=' in entry: + key,value=entry.split(b'=',1) + env[key.decode(errors='replace')]=value.decode(errors='replace') + for key,value in snapshot.get('env',{}).items(): + if env.get(key)!=value: + raise Refused('shared model required environment changed: '+key) + fields=(root/'stat').read_text().rsplit(') ',1)[1].split() + if fields[0] in ['Z','X']: + raise Refused('shared model already exited') + return {'pid':pid,'starttime_ticks':fields[19],'exe_sha256':expected_sha256, + 'configuration':'matches saved executable/cwd/argv/required environment'} + + +def check_observation(pid, health, connections, gpu_pids, board_sha256, reviewed_board_sha256): + if board_sha256!=reviewed_board_sha256: + raise Refused('shared board changed; review current activity before retrying') + expected={'status':'ok','model':'qwen3.6-35b-a3b-fp8','engine':'omega-qwen36-batch', + 'concurrency':8,'busy':False,'in_flight':0} + for key,value in expected.items(): + if type(health.get(key)) is not type(value) or health.get(key)!=value: + raise Refused('shared model is not the expected healthy idle configuration: '+key) + if connections.strip(): + raise Refused('shared model has established connections') + if type(gpu_pids) is not list or any(type(p) is not int or p<1 for p in gpu_pids) or gpu_pids!=[pid]: + raise Refused('GPU inventory is not solely the expected shared model') + + +def observe(pid, board, reviewed_sha256): + request=urllib.request.Request('http://127.0.0.1:18091/health',headers={'Connection':'close'}) + with urllib.request.urlopen(request,timeout=3) as response: + health=json.load(response) + connections=subprocess.check_output(['ss','-tnH','state','established', + '( sport = :18091 or dport = :18091 )'],text=True,timeout=5) + raw=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid', + '--format=csv,noheader,nounits'],text=True,timeout=5) + gpu_pids=[int(line.strip()) for line in raw.splitlines() if line.strip()] + check_observation(pid,health,connections,gpu_pids,digest(board),reviewed_sha256) + return health + + +def send_term(pidfd): + if select.select([pidfd],[],[],0)[0]: + raise Refused('bound process exited before stop; no signal sent') + signal.pidfd_send_signal(pidfd,signal.SIGTERM) + + +def guard(pid, snapshot, expected_sha256, board, reviewed_sha256, stop=False): + # Open first, then inspect. A numeric PID reused after this point cannot redirect this signal. + fd=os.pidfd_open(pid) + try: + identity=process_identity(pid,snapshot,expected_sha256) + samples=[] + for _ in range(3): + samples.append(observe(pid,board,reviewed_sha256)) + time.sleep(1) + if process_identity(pid,snapshot,expected_sha256)!=identity: + raise Refused('process identity changed during idle checks') + samples.append(observe(pid,board,reviewed_sha256)) + if select.select([fd],[],[],0)[0]: + raise Refused('bound process exited during checks') + result={'identity':identity,'idle_samples':len(samples),'stop_sent':False, + 'reviewed_board_sha256':reviewed_sha256,'scope':'shared-model preflight only'} + if stop: + send_term(fd) + result['stop_sent']=True + return result + finally: + os.close(fd) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--pid',required=True,type=int) + parser.add_argument('--snapshot',required=True,type=Path) + parser.add_argument('--binary-sha256',required=True) + parser.add_argument('--board',type=Path,default=Path('/home/drakestapleton/handoffs/BOARD.md')) + parser.add_argument('--reviewed-board-sha256',required=True) + parser.add_argument('--stop',action='store_true') + parser.add_argument('--out',required=True,type=Path) + args=parser.parse_args() + # Refuse a reused receipt before touching a process. + with args.out.open('x') as output: + try: + result=guard(args.pid,json.loads(args.snapshot.read_text()),args.binary_sha256, + args.board,args.reviewed_board_sha256,args.stop) + status=0 + except (Refused,OSError,ValueError,TypeError,KeyError,IndexError,AttributeError,subprocess.SubprocessError) as error: + result={'status':'REFUSED','reason':str(error),'stop_sent':False} + status=75 + json.dump(result,output,indent=2) + output.write('\n') + return status + + +if __name__=='__main__': + raise SystemExit(main()) diff --git a/bench/shared-window.py b/bench/shared-window.py new file mode 100644 index 0000000..bfe530a --- /dev/null +++ b/bench/shared-window.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""External test controller. Requires reviewed BOARD and pinned inputs; never swaps models.""" +import argparse +import contextlib +import datetime +import fcntl +import importlib.util +import json +import os +from pathlib import Path +import select +import signal +import subprocess +import time +import urllib.request + +HERE=Path(__file__).resolve().parent +spec=importlib.util.spec_from_file_location('shared_guard',HERE/'shared-model-guard.py') +guard=importlib.util.module_from_spec(spec); spec.loader.exec_module(guard) + + +def execute(ops): + """Keep the lock through all recovery. Refusal before stop never launches restoration.""" + result={'test_exit':None,'restored':False,'status':'INCOMPLETE'} + with ops.lock(): + ops.preflight() + stop_attempted=False + try: + stop_attempted=True + ops.stop() + ops.wait_original_exit() + ops.before_test() + result['test_exit']=ops.run() + except Exception as error: + result['error']=str(error) + finally: + if stop_attempted: + try: + ops.recovery_gate() + ops.restore() + ops.verify_restored() + result['restored']=True + except Exception as error: + result['recovery_error']=str(error) + if result['test_exit']==0 and result['restored'] and 'error' not in result: + result['status']='PASS' + return result + + +class Live: + def __init__(self,args): + self.a=args; self.original_fd=None; self.child=None; self.interrupted=False + self.baseline=None; self.snapshot=json.loads(args.snapshot.read_text()) + self.pins=json.loads(args.pins.read_text()); self.original=None + def event(self,kind,**fields): + with (self.a.out/'events.jsonl').open('a') as out: + out.write(json.dumps({'at':datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'event':kind,**fields})+'\n') + @contextlib.contextmanager + def lock(self): + fd=os.open('/tmp/aien-gb10.lock',os.O_WRONLY|os.O_CREAT,0o600) + try: + fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) + # Runner contract requires descriptor 9. Never overwrite an unknown descriptor. + if fd!=9: + try: os.fstat(9) + except OSError: pass + else: raise guard.Refused('descriptor 9 already in use') + os.dup2(fd,9); os.close(fd); fd=9 + self.event('lock_acquired') + yield + finally: + if self.original_fd is not None: os.close(self.original_fd) + os.close(fd) + def validate_pins(self,restoration=False): + required=[self.a.snapshot,self.a.launcher,Path(self.snapshot['exe']), + HERE/'shared-model-guard.py',Path(__file__).resolve()] + if not restoration: + required += [self.a.repo/p for p in ['bench/run_arm.sh','bench/session-lifecycle.sh', + 'bench/bench.py','bench/quiet.py','bench/coremon.py','prompts/decode.jsonl','prompts/prefill.jsonl']] + conf=self.a.repo/'bench/arms.conf' + if not restoration and conf.exists(): required.append(conf) + for path in required: + if str(path.resolve()) not in self.pins: raise guard.Refused('missing pin: '+str(path)) + checks={str(p.resolve()):self.pins[str(p.resolve())] for p in required} if restoration else self.pins + for name,expected in checks.items(): + if guard.digest(name)!=expected: raise guard.Refused('pinned file changed: '+name) + def validate_restore_contract(self): + expected=['./aien-serve-http','--engine','omega','--model-dir', + str(Path.home()/'models/qwen3.6-35b-a3b-fp8-95a723d0'),'--port','18091', + '--max-context','49152','--max-tokens-cap','16384','--thinking','off','--batch-slots','8'] + if self.snapshot['argv']!=expected: + raise guard.Refused('snapshot differs from supported same-model restoration contract') + cwd=Path(self.snapshot['cwd']) + if cwd.parent!=self.a.launcher.parent or str(cwd/'aien-serve-http')!=self.snapshot['exe']: + raise guard.Refused('snapshot executable/working directory does not match launcher layout') + expected_env={'AIEN_Q36_STROKE':'1','AIEN_SERVE_GPU_LOCK':'/tmp/aien-serve-18091.lock'} + if self.snapshot['env']!=expected_env: + raise guard.Refused('snapshot environment differs from supported restoration contract') + def gpu_empty(self): + rows=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid', + '--format=csv,noheader,nounits'],text=True,timeout=5) + if rows.strip(): raise guard.Refused('GPU processes remain; refusing overlapping model launch') + def memory(self): + for line in Path('/proc/meminfo').read_text().splitlines(): + if line.startswith('MemAvailable:'): + parts=line.split() + if len(parts)==3 and parts[2]=='kB' and parts[1].isdigit() and int(parts[1])>0: + return int(parts[1]) + raise guard.Refused('valid MemAvailable unavailable') + def preflight(self): + self.validate_pins() + self.validate_restore_contract() + self.sha=self.pins[str(Path(self.snapshot['exe']).resolve())] + self.original=int(self.a.pidfile.read_text().strip()) + self.original_fd=os.pidfd_open(self.original) + self.identity=guard.process_identity(self.original,self.snapshot,self.sha) + # Review is a coordinator action, not something inferred from file age or locks. + old=self.a.board.read_bytes() + import hashlib + if hashlib.sha256(old).hexdigest()!=self.a.reviewed_board_sha256: + raise guard.Refused('BOARD changed since coordinator review') + entry=('\n'+datetime.datetime.now(datetime.timezone.utc).isoformat()+ + ' CodexStackCompare EXCLUSIVE35B '+self.a.arm+' '+self.a.round+ + ': Drake said "you may stop the model" and "Only you can\'t stop it if it\'s doing a test." '+ + 'Coordinator reviewed BOARD; idle/identity checks required before stop. '+ + 'One session capped at60min plus restoration. UNDO: same saved executable/model/flags via '+ + str(self.a.launcher)+' with explicit saved batch settings. Evidence '+str(self.a.out)+'\n').encode() + with self.a.board.open('ab') as out: out.write(entry) + reviewed=hashlib.sha256(old+entry).hexdigest() + observation=guard.guard(self.original,self.snapshot,self.sha,self.a.board,reviewed,False) + if observation['identity']!=self.identity: raise guard.Refused('original process identity changed') + self.reviewed=reviewed + self.event('preflight',observation=observation) + def stop(self): + if self.interrupted: raise guard.Refused('interrupted before stopping shared model') + guard.observe(self.original,self.a.board,self.reviewed) + guard.send_term(self.original_fd) + self.event('shared_stop_sent') + def wait_original_exit(self): + if not select.select([self.original_fd],[],[],60)[0]: + raise guard.Refused('original model did not exit; no force kill') + self.event('shared_exited') + def before_test(self): + self.gpu_empty(); self.baseline=self.memory(); self.validate_pins() + self.event('baseline',memavailable_kib=self.baseline) + def run(self): + if self.interrupted: raise guard.Refused('interrupted before test launch') + env=os.environ.copy() + env.update(H2H_GPU_LOCK_FD='9',H2H_REPO=str(self.a.repo),H2H_RESULTS=str(self.a.out/'results')) + with (self.a.out/'runner.log').open('xb') as log: + self.child=subprocess.Popen(['bash',str(self.a.repo/'bench/run_arm.sh'),self.a.arm,self.a.round], + env=env,stdout=log,stderr=subprocess.STDOUT,pass_fds=(9,)) + # The inner runner owns descendants, containers and its 60-minute watchdog. + # Its pre-lock quiet wait can be longer; bound the complete invocation as well. + deadline=time.monotonic()+4500 + while self.child.poll() is None: + if self.interrupted or time.monotonic()>deadline: + self.child.terminate() + try: self.child.wait(timeout=60) + except subprocess.TimeoutExpired: + raise guard.Refused('runner did not finish cleanup; retain its inherited lock, no restore') + raise guard.Refused('test interrupted or outer deadline reached') + time.sleep(0.25) + self.event('test_exit',code=self.child.returncode) + done=self.a.out/'results/logs'/('%s-%s' % (self.a.arm,self.a.round))/'DONE' + if self.child.returncode==0 and not done.is_file(): + raise guard.Refused('runner returned success without a completed-session marker') + return self.child.returncode + def recovery_gate(self): + if self.child is not None and self.child.poll() is None: + raise guard.Refused('runner still active; restoration refused') + if not select.select([self.original_fd],[],[],0)[0]: + raise guard.Refused('original still present; duplicate restoration refused') + self.gpu_empty() + after=self.memory() + self.event('unloaded',memavailable_kib=after,baseline_kib=self.baseline) + if self.baseline is not None and self.baseline-after>2*1024*1024: + raise guard.Refused('memory has not recovered within 2 GiB; restoration refused') + def restore(self): + # An unrelated benchmark-input change must not prevent restoring the saved service. + self.validate_pins(restoration=True) + env=os.environ.copy() + env.update(self.snapshot['env']) + env.update(Q36_BATCH_BIN=Path(self.snapshot['cwd']).name,Q36_BATCH_SLOTS='8',Q36_MAX_CONTEXT='49152') + with (self.a.out/'restore.log').open('xb') as log: + # close_fds prevents the restored service from retaining the global GPU lock. + subprocess.run([str(self.a.launcher)],env=env,stdout=log,stderr=subprocess.STDOUT, + close_fds=True,timeout=30,check=True) + self.event('restore_launched') + def verify_restored(self): + deadline=time.monotonic()+180 + last='no health response' + while time.monotonic() "$LOGD/foreign-stopped" ;; esac; } +kill() { return 1; } +sleep() { :; } +pgrep() { return 1; } +''' % shlex.quote(tmp) + result=subprocess.run(['bash','-c',script+function+'\nstop_server\n'],capture_output=True,text=True,timeout=5) + self.assertFalse((Path(tmp)/'foreign-stopped').exists(),result.stderr) + self.assertNotEqual(result.returncode,0) + + def test_owned_container_launch_records_label_and_shutdown(self): + source=(HERE/'run_arm.sh').read_text() + functions=source[source.index('start_server() {'):source.index('ready() {')] + with tempfile.TemporaryDirectory() as tmp: + script="""set -u +source %s +LOGD=%s ARM=VLLM CTR=stack-fixture RUN_ID=fixture SPID= +MDIR=/fixture VLLM_IMG=fixture-image SRV_CPUS=0-1 VLLM_UTIL=0.50 +trap 'for p in $(jobs -pr); do kill -TERM "$p" 2>/dev/null || true; done; wait 2>/dev/null || true' EXIT +timeout() { shift; "$@"; } +docker() { + case "$1" in + create) printf '%%s\n' "$@" > "$LOGD/create-args"; echo fixture-id ;; + start) echo started > "$LOGD/start-called"; exec sleep 60 ;; + inspect) echo fixture ;; + stop) echo stopped > "$LOGD/stop-called" ;; + esac +} +""" % (shlex.quote(str(HERE/'session-lifecycle.sh')),shlex.quote(tmp)) + result=subprocess.run(['bash','-c',script+functions+'\nstart_server && stop_server\n'], + capture_output=True,text=True,timeout=5) + self.assertEqual(result.returncode,0,result.stderr) + args=(Path(tmp)/'create-args').read_text().splitlines() + self.assertIn('aien.stack-comparison.run=fixture',args) + self.assertIn('never',args) + self.assertTrue((Path(tmp)/'server-identity.txt').exists()) + self.assertTrue((Path(tmp)/'stop-called').exists()) + + def test_failed_container_creation_never_starts_server(self): + source=(HERE/'run_arm.sh').read_text() + function=source[source.index('start_server() {'):source.index('stop_server() {')] + with tempfile.TemporaryDirectory() as tmp: + script="""set -u +source %s +LOGD=%s ARM=VLLM CTR=stack-fixture RUN_ID=fixture SPID= +MDIR=/fixture VLLM_IMG=fixture-image SRV_CPUS=0-1 VLLM_UTIL=0.50 +timeout() { shift; "$@"; } +docker() { if [ "$1" = create ]; then return 7; fi; echo wrongly-started > "$LOGD/start-called"; } +""" % (shlex.quote(str(HERE/'session-lifecycle.sh')),shlex.quote(tmp)) + result=subprocess.run(['bash','-c',script+function+'\nstart_server\n'],capture_output=True,text=True,timeout=5) + self.assertNotEqual(result.returncode,0) + self.assertFalse((Path(tmp)/'start-called').exists()) + +class ProcessLifecycleTests(unittest.TestCase): + def shell(self, body): + prefix="""set -u +trap 'for p in $(jobs -pr); do kill -TERM "$p" 2>/dev/null || true; done; wait 2>/dev/null || true' EXIT +source %s +""" % shlex.quote(str(HERE/'session-lifecycle.sh')) + result=subprocess.run(['bash','-c',prefix+body],capture_output=True,text=True,timeout=15) + self.assertEqual(result.returncode,0,result.stderr) + return result.stdout + + def test_tracked_child_stops_and_untracked_decoy_survives(self): + self.shell("""sleep 60 & own=$!; h2h_track "$own" +sleep 60 & decoy=$! +h2h_stop "$own" 10 || exit 1 +kill -0 "$decoy" || exit 2 +kill -TERM "$decoy"; wait "$decoy" 2>/dev/null || true +[ -z "${H2H_PID_START[$own]:-}" ] +""") + + def test_stale_birth_does_not_signal_process(self): + self.shell("""sleep 60 & own=$!; h2h_track "$own" +H2H_PID_START[$own]=stale +if h2h_stop "$own" 1; then exit 1; fi +kill -0 "$own" || exit 2 +kill -TERM "$own"; wait "$own" 2>/dev/null || true +""") + + def test_cleanup_deadline_forces_own_term_ignoring_child(self): + with tempfile.TemporaryDirectory() as tmp: + ready=Path(tmp)/'ready' + body="""bash -c 'trap "" TERM; echo ready > "$1"; exec sleep 60' fixture %s & own=$! +h2h_track "$own" +for attempt in {1..100}; do [ -e %s ] && break; sleep 0.01; done +H2H_STOP_DEADLINE=$SECONDS +h2h_stop "$own" || exit 1 +if kill -0 "$own" 2>/dev/null; then exit 2; fi +""" % (shlex.quote(str(ready)),shlex.quote(str(ready))) + self.shell(body) + + def test_non_child_and_untracked_process_refused(self): + self.shell("""if h2h_track $$; then exit 1; fi +sleep 60 & other=$! +if h2h_stop "$other" 1; then kill "$other"; exit 2; fi +kill -0 "$other" || exit 3 +kill -TERM "$other"; wait "$other" 2>/dev/null || true +""") + + def test_already_exited_child_can_be_reaped(self): + self.shell("""true & own=$!; wait "$own" +h2h_track "$own" || exit 1 +h2h_stop "$own" 1 +""") + + def test_term_ignoring_child_is_killed_after_grace(self): + with tempfile.TemporaryDirectory() as tmp: + ready=Path(tmp)/'ready' + body="""bash -c 'trap "" TERM; echo ready > "$1"; exec sleep 60' fixture %s & own=$! +h2h_track "$own" +for attempt in {1..100}; do [ -e %s ] && break; sleep 0.01; done +h2h_stop "$own" 2 || exit 1 +if kill -0 "$own" 2>/dev/null; then exit 2; fi +""" % (shlex.quote(str(ready)),shlex.quote(str(ready))) + self.shell(body) + + def test_descendant_is_stopped_with_root(self): + with tempfile.TemporaryDirectory() as tmp: + ready=Path(tmp)/'child' + body="""( sleep 60 & child=$! +trap 'kill -TERM "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 0' TERM +printf '%%s' "$child" > %s +wait "$child" +) & own=$! +h2h_track "$own" +for attempt in {1..100}; do [ -s %s ] && break; sleep 0.01; done +child=$(cat %s) +h2h_stop "$own" 10 || exit 1 +identity=$(h2h_identity "$child") || exit 0 +read -r state birth parent <<< "$identity" +[ "$state" = Z ] || [ "$state" = X ] +""" % tuple(shlex.quote(str(ready)) for _ in range(3)) + self.shell(body) + + def test_memory_sampler_resolves_published_server_identity(self): + source=(HERE/'run_arm.sh').read_text() + function=source[source.index('server_pids() {'):source.index('start_server() {')] + with tempfile.TemporaryDirectory() as tmp: + script='LOGD=%s\nCTR= SPID= RUN_ID=fixture\n' % shlex.quote(tmp) + script+=function+""" +sleep 60 & actual=$!; h2h_track "$actual" +sleep 60 & decoy=$! +printf '%s %s\n' "$actual" "${H2H_PID_START[$actual]}" > "$LOGD/server-identity.txt" +observed=$(server_pids) +[ "$observed" = "$actual" ] || exit 1 +h2h_stop "$actual" 10 || exit 2 +kill -TERM "$decoy"; wait "$decoy" 2>/dev/null || true +""" + self.shell(script) + + def test_cleanup_preserves_parent_lock_and_releases_own_lock(self): + source=(HERE/'run_arm.sh').read_text() + cleanup=source[source.index('cleanup_session() {'):source.index('# ---- session ----')] + for release in [0,1]: + with self.subTest(release=release),tempfile.TemporaryDirectory() as tmp: + prefix="""set -u +LOGD=%s +SPID= CPID= CMON_PID= WD= SAMP= VMS= BASE=100 GPU_LOCK_HELD=1 GPU_LOCK_RELEASE=%d +ARM=CONTROL ROUND=R0 +timeout() { shift; "$@"; } +nvidia-smi() { case "$*" in *noheader*) : ;; *) echo fixture-empty-inventory-header ;; esac; } +memavail() { echo 100; } +ktpsr() { echo 99; } +board() { :; } +stop_server() { :; } +""" % (shlex.quote(tmp),release) + script=prefix+cleanup+""" +export LOGD SPID CPID CMON_PID WD SAMP VMS BASE GPU_LOCK_HELD GPU_LOCK_RELEASE ARM ROUND +export -f cleanup_session timeout nvidia-smi memavail ktpsr board stop_server +exec 9> "$LOGD/lock" +flock -n 9 || exit 1 +bash -c 'trap cleanup_session EXIT; exit 0' || exit 2 +if flock -n "$LOGD/lock" true; then acquired=1; else acquired=0; fi +[ "$acquired" = "$GPU_LOCK_RELEASE" ] || exit 3 +flock -u 9 +flock -n "$LOGD/lock" true +""" + result=subprocess.run(['bash','-c',script],capture_output=True,text=True,timeout=5) + self.assertEqual(result.returncode,0,result.stderr) + + def lifecycle_fixture(self, mode): + source=(HERE/'run_arm.sh').read_text() + stop=source[source.index('stop_server() {'):source.index('ready() {')] + cleanup=source[source.index('start_watchdog() {'):source.index('# ---- session ----')] + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp) + prefix='''set -u +source %s +LOGD=%s +SPID= CPID= CMON_PID= WD= SAMP= VMS= BASE= GPU_LOCK_HELD=0 CTR= +ARM=OURS ROUND=R0 RUN_ID=fixture +board() { :; } +''' % (shlex.quote(str(HERE/'session-lifecycle.sh')),shlex.quote(tmp)) + body=""" +trap cleanup_session EXIT +trap 'exit 143' TERM +trap 'exit 130' INT +sleep 60 & SPID=$!; h2h_track "$SPID" +sleep 60 & CPID=$!; h2h_track "$CPID" +sleep 60 & CMON_PID=$!; h2h_track "$CMON_PID" +sleep 60 & WD=$!; h2h_track "$WD" +sleep 60 & SAMP=$!; h2h_track "$SAMP" +sleep 60 & VMS=$!; h2h_track "$VMS" +touch "$LOGD/DONE" +printf '%s\n' "$SPID" "$CPID" "$CMON_PID" "$WD" "$SAMP" "$VMS" > "$LOGD/children" +""" + if mode=='timeout': + body += 'h2h_stop "$WD" 10; WD=; start_watchdog 0.02 0.02; wait "$CPID"\n' + else: + body += 'wait "$CPID"\n' if mode=='term' else ('exit 7\n' if mode=='fail' else 'exit 0\n') + process=subprocess.Popen(['bash','-c',prefix+stop+cleanup+body],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + try: + if mode=='term': + deadline=time.monotonic()+5 + while not (root/'children').exists() and time.monotonic() "$LOGD/coremon/CONTROL-R0-decode-c1-t${try}.jsonl"; return %d ;; + *) echo client >> "$ROOT/client-calls"; return %d ;; + esac +} +''' % (shlex.quote(tmp), quiet, shlex.quote(monitor_text), monitor, client) + result = subprocess.run(['bash', '-c', prefix + function + '\ncell decode-c1 1 2 decode.jsonl\n'], + capture_output=True, text=True, timeout=5) + calls = (root / 'client-calls').read_text().splitlines() if (root / 'client-calls').exists() else [] + return result.returncode, calls, result.stderr + + def test_clean_cell_passes(self): + rc, calls, err = self.run_cell() + self.assertEqual(rc, 0, err) + self.assertEqual(len(calls), 1) + + def test_quiet_failure_never_runs_client(self): + rc, calls, err = self.run_cell(quiet=1) + self.assertNotEqual(rc, 0, err) + self.assertEqual(calls, []) + + def test_client_failure_is_not_accepted(self): + self.assertNotEqual(self.run_cell(client=7)[0], 0) + + def test_missing_monitor_summary_is_not_accepted(self): + self.assertNotEqual(self.run_cell(summary=False)[0], 0) + + def test_monitor_crash_is_not_accepted(self): + self.assertNotEqual(self.run_cell(monitor=2)[0], 0) + + def test_exhausted_foreign_process_retries_fail(self): + rc, calls, _ = self.run_cell(monitor=1, offenders=True) + self.assertNotEqual(rc, 0) + self.assertEqual(len(calls), 3) + + def test_exhausted_kthread_retries_fail(self): + rc, calls, _ = self.run_cell(contaminated=True) + self.assertNotEqual(rc, 0) + self.assertEqual(len(calls), 3) + + def test_missing_kthread_samples_fail(self): + self.assertNotEqual(self.run_cell(missing_samples=True)[0], 0) + + def test_invalid_kthread_samples_fail(self): + self.assertNotEqual(self.run_cell(invalid_samples=True)[0], 0) + + def test_zero_monitor_duration_fails(self): + self.assertNotEqual(self.run_cell(elapsed=0)[0], 0) + + def test_completion_requires_all_cells_and_no_timeout(self): + source = (HERE / 'run_arm.sh').read_text() + function = source[source.index('mark_complete() {'):source.index('# ---- session ----')] + for count, timed_out, expected in [(0, False, False), (13, False, False), + (14, True, False), (14, False, True)]: + with self.subTest(count=count, timed_out=timed_out), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + if timed_out: + (root / 'TIMEOUT').touch() + script = 'LOGD=%s\nCELLS_COMPLETED=%d\n' % (shlex.quote(tmp), count) + result = subprocess.run(['bash', '-c', script + function + '\nmark_complete'], + capture_output=True, timeout=5) + self.assertEqual(result.returncode == 0, expected) + self.assertEqual((root / 'DONE').exists(), expected) + + def test_existing_session_is_not_overwritten(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + log = root / 'logs/OURS-R1' + log.mkdir(parents=True) + sentinel = log / 'DONE' + sentinel.write_text('historical') + env = dict(os.environ, H2H_RESULTS=tmp) + result = subprocess.run(['bash', str(HERE / 'run_arm.sh'), 'OURS', 'R1'], + env=env, capture_output=True, text=True, timeout=5) + self.assertEqual(result.returncode, 2) + self.assertEqual(sentinel.read_text(), 'historical') + + def test_timeout_never_runs_client(self): + rc, calls, _ = self.run_cell(timeout=True) + self.assertNotEqual(rc, 0) + self.assertEqual(calls, []) + +if __name__ == '__main__': + unittest.main() diff --git a/bench/test-shared-model-guard.py b/bench/test-shared-model-guard.py new file mode 100644 index 0000000..b3bb26f --- /dev/null +++ b/bench/test-shared-model-guard.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""External guard controls. No shared port, GPU query or shared model is touched.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch +sys.dont_write_bytecode=True +HERE=Path(__file__).resolve().parent +spec=importlib.util.spec_from_file_location('shared_guard',HERE/'shared-model-guard.py') +guard=importlib.util.module_from_spec(spec);spec.loader.exec_module(guard) +HEALTH=dict(status='ok',model='qwen3.6-35b-a3b-fp8',engine='omega-qwen36-batch', + concurrency=8,busy=False,in_flight=0) + +class ObservationTests(unittest.TestCase): + def test_expected_idle_observation_passes(self): + guard.check_observation(42,HEALTH,'',[42],'reviewed','reviewed') + def test_active_or_changed_health_refused(self): + for key,value in [('busy',True),('in_flight',1),('in_flight',False),('concurrency',1), + ('model','other'),('engine','other'),('status','loading')]: + health=dict(HEALTH);health[key]=value + with self.subTest(key=key,value=value),self.assertRaises(guard.Refused): + guard.check_observation(42,health,'',[42],'reviewed','reviewed') + def test_established_client_refused(self): + with self.assertRaises(guard.Refused):guard.check_observation(42,HEALTH,'fixture client',[42],'reviewed','reviewed') + def test_foreign_missing_or_duplicate_gpu_pid_refused(self): + for pids in [[],[41],[42,43],[42,42],['42'],[True]]: + with self.subTest(pids=pids),self.assertRaises(guard.Refused): + guard.check_observation(42,HEALTH,'',pids,'reviewed','reviewed') + def test_board_change_refused(self): + with self.assertRaises(guard.Refused):guard.check_observation(42,HEALTH,'',[42],'new','reviewed') + +class IdentityTests(unittest.TestCase): + def fixture(self,root): + binary=root/'fixture-executable';binary.write_bytes(b'harmless identity fixture') + proc=root/'proc/42';proc.mkdir(parents=True) + (proc/'exe').symlink_to(binary);(proc/'cwd').symlink_to(root) + argv=['./fixture','--engine','omega'];(proc/'cmdline').write_bytes(b'\0'.join(x.encode() for x in argv)+b'\0') + (proc/'environ').write_bytes(b'AIEN_Q36_STROKE=1\0UNRELATED=not-recorded\0') + fields=['S','1']+['0']*17+['12345']+['0']*5 + (proc/'stat').write_text('42 (fixture name) '+ ' '.join(fields)) + snapshot=dict(exe=str(binary),cwd=str(root),argv=argv,env={'AIEN_Q36_STROKE':'1'}) + return snapshot,hashlib.sha256(binary.read_bytes()).hexdigest(),proc + def test_saved_identity_matches_without_recording_unrelated_environment(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);snapshot,digest,proc=self.fixture(root) + actual=guard.process_identity(42,snapshot,digest,root/'proc') + self.assertEqual(actual['starttime_ticks'],'12345') + self.assertNotIn('not-recorded',json.dumps(actual)) + def test_configuration_drift_refused(self): + for key,value in [('argv',['changed']),('cwd','/different'),('exe','/different')]: + with self.subTest(key=key),tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);snapshot,digest,proc=self.fixture(root);snapshot[key]=value + with self.assertRaises(guard.Refused):guard.process_identity(42,snapshot,digest,root/'proc') + def test_binary_and_required_environment_changes_refused(self): + for kind in ['binary','environment']: + with self.subTest(kind=kind),tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);snapshot,digest,proc=self.fixture(root) + if kind=='binary':Path(snapshot['exe']).write_bytes(b'changed') + else:(proc/'environ').write_bytes(b'AIEN_Q36_STROKE=0\0') + with self.assertRaises(guard.Refused):guard.process_identity(42,snapshot,digest,root/'proc') + +class SequencingTests(unittest.TestCase): + def run_fake(self,stop=False,busy=False,changed=False,exited=False): + identity=dict(pid=42,starttime_ticks='1',exe_sha256='fixture') + observations=[dict(HEALTH)]*4 + with patch.object(guard.os,'pidfd_open',return_value=999),patch.object(guard.os,'close') as close,\ + patch.object(guard,'process_identity',side_effect=[identity,dict(identity,starttime_ticks='2') if changed else identity]),\ + patch.object(guard,'observe',side_effect=guard.Refused('busy') if busy else observations) as observe,\ + patch.object(guard.time,'sleep'),patch.object(guard.select,'select',return_value=([999] if exited else [],[],[])),\ + patch.object(guard,'send_term') as send: + try: + result=guard.guard(42,{},'fixture',Path('/unused'),'reviewed',stop) + return result,send.call_count,observe.call_count + finally: + self.assertEqual(close.call_args_list,[( (999,), {} )]) + if busy or changed or exited:self.assertEqual(send.call_count,0) + def test_check_only_never_signals(self): + result,sent,observed=self.run_fake() + self.assertFalse(result['stop_sent']);self.assertEqual(sent,0);self.assertEqual(observed,4) + def test_stop_requires_all_samples_and_final_identity_check(self): + result,sent,observed=self.run_fake(stop=True) + self.assertTrue(result['stop_sent']);self.assertEqual(sent,1);self.assertEqual(observed,4) + def test_busy_identity_drift_or_exited_handle_never_signals(self): + for options in [dict(busy=True),dict(changed=True),dict(exited=True)]: + with self.subTest(options=options),self.assertRaises(guard.Refused):self.run_fake(stop=True,**options) + +class ReceiptTests(unittest.TestCase): + def test_cli_refuses_existing_receipt_before_any_process_access(self): + with tempfile.TemporaryDirectory() as tmp: + output=Path(tmp)/'existing.json';output.write_text('preserve evidence') + result=subprocess.run([sys.executable,str(HERE/'shared-model-guard.py'), + '--pid','0','--snapshot',str(Path(tmp)/'absent.json'), + '--binary-sha256','invalid','--reviewed-board-sha256','invalid', + '--stop','--out',str(output)],capture_output=True,text=True,timeout=5) + self.assertNotEqual(result.returncode,0) + self.assertEqual(output.read_text(),'preserve evidence') + self.assertIn('FileExistsError',result.stderr) + +class PidfdTests(unittest.TestCase): + def test_bound_signal_stops_only_fixture_child(self): + child=subprocess.Popen(['sleep','60']);decoy=subprocess.Popen(['sleep','60']) + fd=os.pidfd_open(child.pid) + try: + guard.send_term(fd);self.assertEqual(child.wait(timeout=2),-signal.SIGTERM) + self.assertIsNone(decoy.poll()) + finally: + os.close(fd) + for process in [child,decoy]: + if process.poll() is None:process.terminate() + process.wait(timeout=2) + def test_exited_bound_handle_refused(self): + child=subprocess.Popen(['sleep','60']);fd=os.pidfd_open(child.pid) + try: + child.terminate();child.wait(timeout=2) + with self.assertRaises(guard.Refused):guard.send_term(fd) + finally: + os.close(fd) + if child.poll() is None:child.terminate();child.wait(timeout=2) + +if __name__=='__main__':unittest.main() diff --git a/bench/test-shared-window.py b/bench/test-shared-window.py new file mode 100644 index 0000000..94e23e9 --- /dev/null +++ b/bench/test-shared-window.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Host-only sequencing, recovery and real-child controls; no live shared service access.""" +import contextlib,importlib.util,pathlib,tempfile,unittest,types,os,fcntl,subprocess,threading +from unittest.mock import patch +HERE=pathlib.Path(__file__).resolve().parent +spec=importlib.util.spec_from_file_location('window',HERE/'shared-window.py') +window=importlib.util.module_from_spec(spec);spec.loader.exec_module(window) +class Fake: + def __init__(self,fail=None,code=0): self.fail=fail;self.code=code;self.events=[];self.held=False + def step(self,name): + if not self.held: raise AssertionError('operation without lock') + self.events.append(name) + if self.fail==name: raise RuntimeError('fixture '+name) + @contextlib.contextmanager + def lock(self): + self.held=True;self.events.append('lock') + try: yield + finally:self.held=False;self.events.append('unlock') + def preflight(self):self.step('preflight') + def stop(self):self.step('stop') + def wait_original_exit(self):self.step('wait') + def before_test(self):self.step('before') + def run(self):self.step('run');return self.code + def recovery_gate(self):self.step('recovery') + def restore(self):self.step('restore') + def verify_restored(self):self.step('verify') +class Sequencing(unittest.TestCase): + def test_success_holds_lock_through_verified_restore(self): + f=Fake();r=window.execute(f) + self.assertEqual(r['status'],'PASS') + self.assertEqual(f.events,['lock','preflight','stop','wait','before','run','recovery','restore','verify','unlock']) + def test_busy_preflight_never_stops_or_restores(self): + f=Fake('preflight') + with self.assertRaises(RuntimeError):window.execute(f) + self.assertEqual(f.events,['lock','preflight','unlock']) + def test_failed_test_still_restores_and_fails(self): + f=Fake(code=7);r=window.execute(f) + self.assertEqual(r['test_exit'],7);self.assertTrue(r['restored']);self.assertEqual(r['status'],'INCOMPLETE') + def test_exception_after_stop_always_attempts_gated_recovery(self): + for step in ['stop','wait','before','run']: + with self.subTest(step=step): + f=Fake(step);r=window.execute(f) + self.assertIn('recovery',f.events);self.assertTrue(r['restored']);self.assertEqual(r['status'],'INCOMPLETE') + def test_failed_recovery_gate_never_launches_original(self): + f=Fake('recovery');r=window.execute(f) + self.assertNotIn('restore',f.events);self.assertFalse(r['restored']) + def test_failed_launcher_never_claims_restored(self): + f=Fake('restore');r=window.execute(f) + self.assertNotIn('verify',f.events);self.assertFalse(r['restored']) + def test_failed_identity_never_claims_restored(self): + f=Fake('verify');r=window.execute(f) + self.assertFalse(r['restored']);self.assertIn('recovery_error',r) +class LiveAdapter(unittest.TestCase): + def bare(self,root): + obj=object.__new__(window.Live) + obj.a=types.SimpleNamespace(out=root,repo=root,arm='OURS',round='R1') + obj.child=None;obj.interrupted=False;obj.baseline=5000000 + return obj + def test_real_child_borrows_lock_and_failed_exit_is_preserved(self): + with tempfile.TemporaryDirectory() as temp: + root=pathlib.Path(temp);(root/'bench').mkdir() + (root/'bench/run_arm.sh').write_text('test -e /proc/$$/fd/9 || exit 22\nflock -n 9 || exit 23\necho "$H2H_GPU_LOCK_FD"\nexit 7\n') + obj=self.bare(root) + fd=os.open(root/'lock',os.O_CREAT|os.O_RDWR,0o600) + saved=None + try: + try:saved=os.dup(9) + except OSError:pass + os.dup2(fd,9);fcntl.flock(9,fcntl.LOCK_EX|fcntl.LOCK_NB) + self.assertEqual(obj.run(),7) + probe=subprocess.run(['flock','-n',str(root/'lock'),'true']) + self.assertNotEqual(probe.returncode,0,'child released parent lock') + self.assertEqual((root/'runner.log').read_text().strip(),'9') + finally: + os.close(9) + if saved is not None:os.dup2(saved,9);os.close(saved) + if fd!=9:os.close(fd) + def test_interruption_before_launch_is_refused(self): + with tempfile.TemporaryDirectory() as tmp: + obj=self.bare(pathlib.Path(tmp));obj.interrupted=True + with self.assertRaises(window.guard.Refused):obj.run() + self.assertIsNone(obj.child) + def test_success_without_done_is_refused(self): + with tempfile.TemporaryDirectory() as tmp: + obj=self.bare(pathlib.Path(tmp)) + child=types.SimpleNamespace(poll=lambda:0,returncode=0) + with patch.object(window.subprocess,'Popen',return_value=child): + with self.assertRaisesRegex(window.guard.Refused,'completed-session marker'):obj.run() + def test_interruption_stops_and_reaps_real_fixture_child(self): + with tempfile.TemporaryDirectory() as tmp: + root=pathlib.Path(tmp);(root/'bench').mkdir() + (root/'bench/run_arm.sh').write_text('exec sleep 30\n') + obj=self.bare(root);fd=os.open(root/'lock',os.O_CREAT|os.O_RDWR,0o600);saved=None + timer=threading.Timer(0.1,lambda:setattr(obj,'interrupted',True)) + try: + try:saved=os.dup(9) + except OSError:pass + os.dup2(fd,9);timer.start() + with self.assertRaisesRegex(window.guard.Refused,'interrupted'):obj.run() + self.assertIsNotNone(obj.child.returncode) + with self.assertRaises(ChildProcessError):os.waitpid(obj.child.pid,os.WNOHANG) + finally: + timer.cancel();timer.join() + if obj.child is not None and obj.child.poll() is None:obj.child.kill();obj.child.wait() + os.close(9) + if saved is not None:os.dup2(saved,9);os.close(saved) + if fd!=9:os.close(fd) + def test_active_runner_refuses_restoration_without_gpu_query(self): + obj=self.bare(pathlib.Path('/unused'));obj.child=types.SimpleNamespace(poll=lambda:None) + with patch.object(obj,'gpu_empty') as gpu: + with self.assertRaises(window.guard.Refused):obj.recovery_gate() + gpu.assert_not_called() + def test_original_still_alive_refuses_duplicate(self): + obj=self.bare(pathlib.Path('/unused'));obj.original_fd=42 + with patch.object(window.select,'select',return_value=([],[],[])),patch.object(obj,'gpu_empty') as gpu: + with self.assertRaises(window.guard.Refused):obj.recovery_gate() + gpu.assert_not_called() + def test_memory_deficit_refuses_restore(self): + with tempfile.TemporaryDirectory() as tmp: + obj=self.bare(pathlib.Path(tmp));obj.original_fd=42 + with patch.object(window.select,'select',return_value=([42],[],[])),patch.object(obj,'gpu_empty'),patch.object(obj,'memory',return_value=1): + with self.assertRaises(window.guard.Refused):obj.recovery_gate() + def test_residual_gpu_refuses_restore(self): + obj=self.bare(pathlib.Path('/unused'));obj.original_fd=42 + with patch.object(window.select,'select',return_value=([42],[],[])),patch.object(obj,'gpu_empty',side_effect=window.guard.Refused('foreign GPU')),patch.object(obj,'memory') as memory: + with self.assertRaises(window.guard.Refused):obj.recovery_gate() + memory.assert_not_called() + def test_restore_launcher_does_not_inherit_gpu_lock(self): + with tempfile.TemporaryDirectory() as tmp: + root=pathlib.Path(tmp);obj=self.bare(root) + obj.a.launcher=root/'restore.sh' + obj.a.launcher.write_text('#!/bin/bash\n[ ! -e /proc/$$/fd/9 ] || exit 21\n[ "$Q36_BATCH_BIN" = bin-fixture ] || exit 22\n[ "$Q36_BATCH_SLOTS" = 8 ] || exit 23\n[ "$Q36_MAX_CONTEXT" = 49152 ] || exit 24\necho RESTORED_FIXTURE\n') + obj.a.launcher.chmod(0o700) + obj.snapshot={'cwd':str(root/'bin-fixture'),'env':{'AIEN_Q36_STROKE':'1'}} + fd=os.open(root/'lock',os.O_CREAT|os.O_RDWR,0o600);saved=None + try: + try:saved=os.dup(9) + except OSError:pass + os.dup2(fd,9);fcntl.flock(9,fcntl.LOCK_EX|fcntl.LOCK_NB) + with patch.object(obj,'validate_pins') as pins: + obj.restore();pins.assert_called_once_with(restoration=True) + self.assertEqual((root/'restore.log').read_text().strip(),'RESTORED_FIXTURE') + self.assertNotEqual(subprocess.run(['flock','-n',str(root/'lock'),'true']).returncode,0) + finally: + os.close(9) + if saved is not None:os.dup2(saved,9);os.close(saved) + if fd!=9:os.close(fd) + def test_changed_snapshot_contract_refused_before_stop(self): + obj=self.bare(pathlib.Path('/unused'));obj.snapshot={'argv':['different-model']} + with self.assertRaises(window.guard.Refused):obj.validate_restore_contract() + def test_gpu_query_error_is_not_empty_inventory(self): + obj=self.bare(pathlib.Path('/unused')) + with patch.object(window.subprocess,'check_output',side_effect=subprocess.CalledProcessError(1,'fixture')): + with self.assertRaises(subprocess.CalledProcessError):obj.gpu_empty() +if __name__=='__main__':unittest.main() diff --git a/bench/test-unload-gates.py b/bench/test-unload-gates.py new file mode 100644 index 0000000..71b5e55 --- /dev/null +++ b/bench/test-unload-gates.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Host-only regression tests of the runner's actual EXIT cleanup acceptance.""" +import pathlib, subprocess, tempfile, unittest, shlex +HERE=pathlib.Path(__file__).resolve().parent +class UnloadTests(unittest.TestCase): + def run_cleanup(self, baseline='5000000', after='5000000', gpu='', query_exit=0): + source=(HERE/'run_arm.sh').read_text() + cleanup=source[source.index('cleanup_session() {'):source.index('# ---- session ----')] + with tempfile.TemporaryDirectory() as tmp: + root=pathlib.Path(tmp); (root/'DONE').touch() + script='''set -u +LOGD=%s +BASE=%s AFTER_FIXTURE=%s GPU_FIXTURE=%s QUERY_EXIT=%s +WD= CPID= CMON_PID= SAMP= VMS= GPU_LOCK_HELD=1 GPU_LOCK_RELEASE=0 ARM=fixture ROUND=R1 +stop_server() { return 0; } +timeout() { shift; "$@"; } +nvidia-smi() { printf '%%s' "$GPU_FIXTURE"; return "$QUERY_EXIT"; } +memavail() { printf '%%s' "$AFTER_FIXTURE"; } +ktpsr() { echo 0; } +board() { :; } +''' % tuple(map(shlex.quote,[tmp,baseline,after,gpu,str(query_exit)])) + proc=subprocess.run(['bash','-c',script+cleanup+'\ntrap cleanup_session EXIT\nexit 0\n'],capture_output=True,text=True,timeout=3) + return proc.returncode,(root/'DONE').exists(),(root/'INCOMPLETE').exists(),proc.stderr + def assert_rejected(self, **kwargs): + rc,done,incomplete,err=self.run_cleanup(**kwargs) + self.assertNotEqual(rc,0,err); self.assertFalse(done); self.assertTrue(incomplete) + def test_recovered_memory_and_empty_gpu_pass(self): + self.assertEqual(self.run_cleanup()[:3],(0,True,False)) + def test_boundary_two_gib_deficit_passes(self): + self.assertEqual(self.run_cleanup(after=str(5000000-2*1024*1024))[:3],(0,True,False)) + def test_one_kib_beyond_boundary_fails(self): + self.assert_rejected(after=str(5000000-2*1024*1024-1)) + def test_more_available_memory_passes(self): + self.assertEqual(self.run_cleanup(after='6000000')[:3],(0,True,False)) + def test_missing_memory_fails(self): + self.assert_rejected(after='') + def test_invalid_memory_fails(self): + for value in ['unknown','-1','0','999999999999999999999999','1\n2']: + with self.subTest(value=value): self.assert_rejected(after=value) + def test_missing_baseline_fails(self): + self.assert_rejected(baseline='') + def test_remaining_gpu_process_fails(self): + self.assert_rejected(gpu='12345\n') + def test_inventory_failure_fails(self): + self.assert_rejected(query_exit=1) +if __name__=='__main__': unittest.main() diff --git a/results/receipts/cpu-tests-pr4-535e8d3.txt b/results/receipts/cpu-tests-pr4-535e8d3.txt new file mode 100644 index 0000000..263bf33 --- /dev/null +++ b/results/receipts/cpu-tests-pr4-535e8d3.txt @@ -0,0 +1,11 @@ +gpu-head-to-head PR #4 CPU-only test receipt +head 535e8d37855d99f8f2f53a522c1eda74cc8813e6 (bench/ tree e977a0209a0c6dd376497cb922b53f7a3a3ded19) +host: DGX Spark CPU, Python 3.12.3, 2026-10-31T02:12:34Z, no GPU, no model loaded +python3 bench/test-bench-python.py -> exit 0, Ran 9 tests, last line: OK +python3 bench/test-extract-admission.py -> exit 0, Ran 4 tests, last line: OK +python3 bench/test-run-arm-lifecycle.py -> exit 0, Ran 16 tests, last line: OK +python3 bench/test-run-arm.py -> exit 0, Ran 13 tests, last line: OK +python3 bench/test-shared-model-guard.py -> exit 0, Ran 14 tests, last line: OK +python3 bench/test-shared-window.py -> exit 0, Ran 18 tests, last line: OK +python3 bench/test-unload-gates.py -> exit 0, Ran 9 tests, last line: OK +NOT_RUN: shared-model restoration on a live server; hardware comparisons