Measurement windows: run order, build cache, receipts and the 27B baseline scripts (tools/ops)
mergedf434b9a877fb895d #291 · opened 2026-10-20 14:59 UTC · closed 2026-10-30 11:13 UTC · merged 2026-10-30 11:13 UTC
Imported from GitHub aien-dev/aien-architecture-mv#291, by drakestapleton
Base 3439f00ce54547273188e0db1124fc9ed08f832a · Head 20da6284b590387aa230f23a9994e9642d03be5b
Merged on GitHub as 3d1682bb2ee57197909758f61b61a2bc962c392d; reachable from main bccab5ea7a17be6c9ab30b1bd05db4898a4601be (observed 2026-11-18T16:37:28Z)
drakestapleton wrote on 2026-10-20 14:59 UTC
What this does
Adds docs/ops/MEASUREMENT_WINDOWS.md and the tools/ops scripts: spark-window (open/close, --gb10, first-come-first-served wait), spark-build-once (tree-hash build cache), spark-receipt, spark-calibrate, spark-baseline (streamed decode timing, waits on the server's health), plus the first complete window evidence. Installed copies are not changed by this PR.
Tests
Worker report: two-worktree build-cache evidence and a passing 27B baseline in docs/ops/evidence. Judge verdict on the exact head is the merge gate. A follow-up branch (fix/spark-window-close, bare close only closes your own window) is stacked on this one and waits for it.
tools/ops/spark-window, quiet-build, quiet-measure are now the installed ~/.local/bin copies (sha256 05723bbd..., b8b40d2c..., c838569e...), so this PR documents what runs (L189, L322, L405). docs/ops/MEASUREMENT_WINDOWS.md updated (20 min exclusive lease max, NO VERDICT on overrun, quiet-machine wait, gate, 25 min build cap).
Merged fix/spark-window-starve (d612f4ea; installed copy already has L189, kept) and fix/spark-window-close (fdabc61c, L162 owner check, auto-merged onto the installed copy).
Tests (temp locks; now also temp gate/want/board and host load ignored): test-spark-window-starve.sh 4/4 PASS under taskset; test_spark_window_close.sh 23/0 PASS (nice only: under taskset -c 10-14 the open took >20 s and hit the test timeout); negative control against the installed copy: 9 pass / 14 fail.
The installed ~/.local/bin/spark-window still lacks the L162 owner check. Installing this version is a separate operator step, not done here.
drakestapleton reviewed (COMMENTED) on 2026-10-30 11:15 UTC
ArchReview triage: blocked (pending the judge verdict on head 20da628, the merge gate this PR sets).
It's no longer stacked, since the close and starve fixes are merged in. The tools/ops scripts are said to match the installed ~/.local/bin copies by sha256, which can't be verified from the repo, so the judge should confirm those hashes.
Checks are green; mergeable.
Fetch it
A git bundle of the pull request's head, 75910 bytes.
diff --git a/README.md b/README.md
index abcdbd1..fd90d94 100644
--- a/README.md
+++ b/README.md
@@ -51,6 +51,7 @@ Superseded plans are kept only under [docs/archive/plans](docs/archive/plans/REA
| `qualification/` | Release candidates (`candidates/CAND-*.toml` and their gate results) and recorded exceptions |
| `formal/invariants/` | Invariants written down for formal checking ([ADR 0027](docs/adr/0027-formal-oracle-lean-bootstrap.md)) |
| `tools/crumb/` | The crumb tool (C11), which compiles and checks the `.crumb` files |
+| `tools/ops/` | The Spark's shared measurement base: build once, one measurement window at a time, per-window calibration and 27B baseline ([how to use it](docs/ops/MEASUREMENT_WINDOWS.md)) |
| `scripts/` | Small shell tools (doctrine check, candidate and pin checks, R16 status wording, the pull request gate, crumb rebase helper) and their `test_*.sh` tests |
| `tests/gates/` | The gate manifests the Spark runs on every pull request |
diff --git a/docs/ops/MEASUREMENT_WINDOWS.md b/docs/ops/MEASUREMENT_WINDOWS.md
new file mode 100644
index 0000000..3b1a8ca
--- /dev/null
+++ b/docs/ops/MEASUREMENT_WINDOWS.md
@@ -0,0 +1,171 @@
+# Measurement windows and the shared base
+
+Several agents measure on the one Spark at the same time. When three of them timed things in parallel
+on 2026-10-19, two of the three verdicts came back INCONCLUSIVE only because the box was loaded by the
+others. Drake's rule: build once, measure the shared parts once per window, and then each agent measures
+only its own difference, one after another.
+
+The shared base is four small shell tools in `~/.local/bin` (copies in [`tools/ops/`](../../tools/ops/README.md)):
+
+| Tool | What it does |
+|---|---|
+| `spark-build-once` | Builds a source tree once. A second caller with the same source gets the stored result in seconds. |
+| `spark-window` | Opens one measurement window at a time, keeps the box quiet while it is open, records the box state at open and close. |
+| `spark-calibrate` | The one calibration of a window: CPU memory bandwidth and idle power at the wall. |
+| `spark-baseline 27b` | The one 27B baseline of a window: a fixed 64-token reply, tokens per second and joules per token. |
+
+`spark-receipt` (the energy receipt every measurement already uses) now stamps the window id and the
+window's calibration file into each receipt. It is shell and awk now; the keys, file name and output
+are the same as before, plus the two new keys.
+
+## The run order
+
+1. One window at a time. `spark-window open` refuses when a window is already open or waiting, and
+ shows whose it is.
+2. To wait your turn, add `--wait`: you get a place in line and your window opens when everyone
+ ahead of you is done, first come, first served. While anyone is in line, an `open` without
+ `--wait` is refused, so nobody jumps ahead. Say so on the ledger:
+ `ledger note <your id> "measure: in line for a window"`. `spark-window status` shows the line.
+ (Retrying a refused `open` every 15 s lost the turn for four hours on 2026-10-20; that is why the
+ line exists.)
+3. Inside your window: calibrate once, take the 27B baseline once (if your work involves the 27B),
+ then run only your own measurements. Every receipt carries the window id, so a reader can match it
+ to the calibration and the baseline taken under the same conditions.
+4. Close the window as soon as your timings are done. A window that holds anything exclusive (the
+ default) lasts at most 20 minutes and `open` refuses a longer `--lease`; other windows default to
+ 90 minutes. A window that runs past its lease lets its locks go, writes NO VERDICT in its folder
+ and posts on the board: its timings are not valid (L405, Drake 2026-10-22). Split long measurements.
+5. A timing window opens only when the machine is quiet anyway: at most 3 jobs on the quiet lock and
+ a 1-minute load of at most 10. It waits for that holding nothing (L405).
+
+Builds are not measurements: do them before you open the window, through `spark-build-once` or
+`quiet-build`. While a window is open, builds wait, but at most 25 minutes; then they run anyway and
+the window is marked "shared machine" (L405).
+
+## Exact commands
+
+Open a window (waits its turn; prints the window id when it holds the box):
+
+```sh
+id=$(spark-window open my-measurement --ledger L109 --lease 20 --wait)
+```
+
+By default the window also holds the GPU lock (`--gb10 exclusive`, added by L154), so GPU-only jobs
+cannot run inside it. The 27B server takes that lock itself for every reply, so a window that measures
+the 27B server, including `spark-baseline`, must be opened with `--gb10 none`; `spark-baseline` refuses
+otherwise. `spark-calibrate` works in both: it uses the window's GPU lock when the window holds it and
+takes the lock itself when it does not.
+
+Calibrate and take the baseline inside it:
+
+```sh
+spark-window run spark-calibrate
+spark-window run spark-baseline 27b
+```
+
+Run your own measurement inside it (any command; `spark-receipt` inside picks up the window id):
+
+```sh
+spark-window run spark-receipt my-run --idle 30 -- ./my-benchmark args
+```
+
+Close it:
+
+```sh
+spark-window close "$id"
+```
+
+A bare `spark-window close` closes the open window only if you own it: the shell that ran `open` is
+in your process tree, or `$SPARK_WINDOW` (set by `run`) is its id. Otherwise it refuses with exit 3
+and names the holder (L162, 2026-10-20: one lane's finishing script closed another lane's window).
+`spark-window close <ID>` closes exactly that window.
+
+See what is open and who holds or waits on the locks:
+
+```sh
+spark-window status
+spark-window locks
+```
+
+Build once (from inside a git worktree; name every result you need with `--out`):
+
+```sh
+spark-build-once --out build/dagsim -- make build/dagsim
+```
+
+## What lands on disk
+
+Everything for one window sits in `~/yardsticks/windows/<window id>/`:
+
+| File | Contents |
+|---|---|
+| `open.json`, `close.json` | Box state at open and close: load, free memory, GPU use and power, who holds the GPU and quiet locks, who waits, the latest sensor row |
+| `calibration.json` | Memory bandwidth (median, lowest and highest of 10 copies, with 1 and 8 threads) and idle power at the wall over 30 s |
+| `calibration/` | The raw probe output and the idle receipt |
+| `baseline-27b.json` | Decode tokens per second, joules per token over the decode at the wall and above idle, the reply's fingerprint, the server build |
+| `baseline-27b/` | The exact request, the reply, the arrival time of every streamed piece, the receipt, the GPU lock samples |
+
+Receipts still go to `~/yardsticks/receipts/<date>-<name>.json` and now carry `window_id` and
+`calibration` (both `null` outside a window). The build cache lives in `~/.cache/spark-build-once/`
+and its log in `~/yardsticks/build-once.log`.
+
+## How it works, in plain words
+
+- **The quiet lock.** The hive already had one rule for keeping the box quiet: builds share
+ `/tmp/aien-quiet.lock` through `quiet-build`, a measurement takes it alone through `quiet-measure`.
+ A window is a long-running `quiet-measure`: a small holder process takes the lock alone and keeps it
+ until you close the window or the lease runs out. Inside the window `quiet-measure` sees its own
+ window and runs your command straight away instead of waiting on its own lock.
+- **Getting both locks without starving (L154, L189, L322).** The window waits for the GPU lock
+ holding nothing, so it never blocks CPU timings while it queues. Once it has the GPU lock it keeps it
+ and raises a gate (`/tmp/aien-quiet.gate`): new `quiet-build` and `quiet-measure` callers wait outside
+ while the ones already holding the quiet lock finish (L322: without the gate, shared takers kept
+ arriving and the window waited 40+ minutes). It drains the quiet lock for at most 5 minutes, then
+ lets everything go and waits for a quiet machine again (L405). If a process waiting for the GPU lock
+ holds the quiet lock, the window lets the GPU lock go (gate stays up), waits for the quiet lock, then
+ tries the GPU lock without blocking while keeping the quiet lock it won (L189: letting a won quiet
+ lock go starved the window for hours). `--quiet none` takes the GPU lock only, for checks that
+ compare values, never speeds.
+- **The GPU lock.** `/tmp/aien-gb10.lock` is separate. The calibration holds it for its minute of
+ probing and idling so the GPU stays idle. The baseline does not hold it, because the 27B server takes
+ that lock itself for every reply; holding it would make the server wait on us forever. Programs that
+ use only the GPU lock keep it busy almost all the time (the first window ran out its hour waiting for
+ it to go quiet), so the baseline asks for the reply word by word and stamps each word as it arrives.
+ From the first word to the last the server is holding the GPU lock for our reply, so the decode rate
+ and its energy are clean however long the reply waited in the GPU queue. The baseline samples the
+ lock table throughout and is marked not ok if anyone else held the GPU lock during the decode, or if
+ the whole reply arrived in one burst (then nothing was timed).
+- **The build cache key** is the source tree as it is on disk (the committed tree, plus uncommitted
+ changes, plus new files that git does not ignore), the folder you run from, the exact command, the
+ `--out` list and the `PHYSICS_DIR` / `AIENOS_LOCK_REPO` settings. Any change gives a new key, so a
+ stored build is only reused for identical sources. Two callers with the same key at the same moment:
+ one builds, the other waits on a per-key lock and then takes the stored result. Results are stored
+ by an atomic rename, so a half-written entry is never visible.
+
+## Limits, said plainly
+
+- Wall power is the whole UPS output in 10 W steps about every 2 s, not the Spark alone. A 64-token
+ reply lasts a few seconds, so its joules per token rest on a few samples: read it as coarse.
+- The headline speed is the decode rate: words after the first, divided by the time from the first word
+ to the last. The whole-request rate is recorded too, but it includes the wait in the GPU queue and the
+ short prompt's prefill.
+- Programs that take only the GPU lock and not the quiet lock can still run during a window. The
+ window records them (lock holders at open and close; the baseline samples the lock during its
+ decode), it does not stop them.
+- The memory probe is the one research/583 used (omega `research/cost-sim-583@3bd56731`,
+ `tools/dagsim/memcpy_probe.c`), built with `cc -O2 -pthread`; 583 did not record its compiler
+ flags, so its numbers and ours are comparable in method, not guaranteed bit for bit.
+
+## Receipt format: what changed
+
+Same keys, same order, same file name, same output as before; two keys added at the end. Run side by
+side on the same 8-second command, the old and new receipts differed only in timing jitter
+(`start`, `seconds`, `wall_J` within 0.02 %) and these lines:
+
+```diff
+ "note": "wall W = UPS ups.load x 10 (CP1500PFCLCD, 1 percent steps, ~2 s); whole UPS output, not the Spark alone",
++ "window_id": "20261019T232138Z-103d00",
++ "calibration": "/home/drakestapleton/yardsticks/windows/20261019T232138Z-103d00/calibration.json"
+```
+
+Outside a window both are `null`. Numbers still print with a decimal point (`180.0`), as before.
diff --git a/docs/ops/evidence/L113-build-once-two-worktrees.md b/docs/ops/evidence/L113-build-once-two-worktrees.md
new file mode 100644
index 0000000..570dc6e
--- /dev/null
+++ b/docs/ops/evidence/L113-build-once-two-worktrees.md
@@ -0,0 +1,22 @@
+# L113 spark-build-once: two worktrees, same omega commit, built at the same moment (2026-10-19/20)
+
+Worktrees ~/workspace/l113-buildonce-a and -b at omega a8ffd2b9, PHYSICS_DIR=~/workspace/physics-pf-6d7cf0d4,
+command `spark-build-once --out build/omegatool -- make -j8 all`; a started, b 2 s later, then b again.
+The 4 h are the wait in the quiet-build queue (quiet lock held exclusive by measurement runs most of the night).
+
+```
+start 2026-10-19T23:24:04Z
+a rc=0 seconds=14444.147746585 end=2026-10-20T03:24:48Z
+b rc=0 seconds=14442.346979828 end=2026-10-20T03:24:48Z
+b-again rc=0 seconds=4.153938887 end=2026-10-20T03:24:52Z
+0255c599602b06385284d02a35428032bbe23950309550abd8c694dda4cff154 /home/drakestapleton/workspace/l113-buildonce-a/build/omegatool
+0255c599602b06385284d02a35428032bbe23950309550abd8c694dda4cff154 /home/drakestapleton/workspace/l113-buildonce-b/build/omegatool
+spark-build-once: key 76b5b2b20976fd84328b6da7 (source e5cdaa81721c, cmd: make -j8 all)
+spark-build-once: MISS 76b5b2b20976fd84328b6da7, building through quiet-build
+spark-build-once: stored 76b5b2b20976fd84328b6da7 (1.1M)
+spark-build-once: key 76b5b2b20976fd84328b6da7 (source e5cdaa81721c, cmd: make -j8 all)
+spark-build-once: HIT 76b5b2b20976fd84328b6da7 (built 2026-10-20T03:24:48Z in /home/drakestapleton/workspace/l113-buildonce-a; 0 s)
+spark-build-once: key 76b5b2b20976fd84328b6da7 (source e5cdaa81721c, cmd: make -j8 all)
+spark-build-once: HIT 76b5b2b20976fd84328b6da7 (built 2026-10-20T03:24:48Z in /home/drakestapleton/workspace/l113-buildonce-a; 14442 s)
+(b printed 240 'waiting' lines in between, one a minute; the last: spark-build-once: waiting 14403 s for key 76b5b2b20976fd84328b6da7, held by: pid ...)
+```
diff --git a/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/README.md b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/README.md
new file mode 100644
index 0000000..503aa41
--- /dev/null
+++ b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/README.md
@@ -0,0 +1,19 @@
+# L113 first complete measurement window (2026-10-20)
+
+Window `20261020T095626Z-bd2f56`, opened with `spark-window open l113-window-8 --ledger L113 --lease 90 --gb10 none --wait`,
+held 09:56:27Z, closed 09:59:31Z. Copies of the four JSON files are here. The full set, including the stream
+with a time stamp per piece, the request, the GPU-lock samples and the receipts, is in `~/yardsticks/windows/20261020T095626Z-bd2f56/` on the Spark.
+
+| What | Value |
+|---|---|
+| Memory copy, 1 thread (median of 10) | 45.65 GB/s |
+| Memory copy, 8 threads (median of 10) | 86.15 GB/s |
+| Wall power with the GPU held idle, 30 s | 245.3 W (box load 28.7: other agents' CPU work kept running) |
+| 27B decode, client clock (63 tokens, first to last) | 8.358 s, 7.538 tok/s |
+| 27B decode, server's own log for the same reply | 8360 ms for 64 tokens, 7.66 tok/s |
+| Wall J/token over the decode (5 sensor samples, coarse) | 40.3 J; 7.8 J above the window's idle |
+| Reply fingerprint (fixed prompt, seed 1, greedy) | sha256 9132f20e... |
+| Checks | ok: 64 tokens, HTTP 200 on the first send, no other GPU-lock holder during the decode, window held throughout, reply streamed (not one burst) |
+
+The client and server decode times agree to 2 ms. The 27B server was busy with other clients for at least 96 s
+before our send (480 polls of /health at 0.2 s); the decode itself is unaffected by that wait.
diff --git a/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/baseline-27b.json b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/baseline-27b.json
new file mode 100644
index 0000000..40ccb85
--- /dev/null
+++ b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/baseline-27b.json
@@ -0,0 +1,31 @@
+{
+ "window_id": "20261020T095626Z-bd2f56",
+ "model": "qwen3.8-27b-fp8",
+ "ok": true,
+ "request": {"url": "http://127.0.0.1:18091/v1/chat/completions", "max_tokens": 64, "temperature": 0, "seed": 1, "stream": true, "file": "/home/drakestapleton/yardsticks/windows/20261020T095626Z-bd2f56/baseline-27b/request.json"},
+ "completion_tokens": 64,
+ "content_chunks": 64,
+ "decode_tokens_counted": 63,
+ "stream_arrived_in_one_burst": false,
+ "finish_reason": "length",
+ "http_code": 200,
+ "tries": 1,
+ "server_log_line": "aien-serve-http: chatcmpl-18e0347bbb09ec8e016b: prompt 35 tok, reply 64 tok, finish length, prefill 495 ms, decode 8360 ms (7.66 tok/s), sampling mode=greedy seed=1 temp=0 top_p=0.95 top_k=20 greedy=64 sampled=0 kept(min/med/mean/max)=0/0/0.00/0 kept1=0/0 top_prob(min/mean)=1.0000/1.0000 p_repeat=1.000e0",
+ "request_seconds": 8.866,
+ "first_token_seconds": 0.508,
+ "tok_per_s_request": 7.219,
+ "decode_seconds": 8.358,
+ "decode_tok_per_s": 7.538,
+ "decode_wall_W_mean": 304,
+ "decode_sensor_samples": 5,
+ "decode_wall_J_per_token": 40.33,
+ "idle_W_calibration": 245.333,
+ "decode_J_per_token_above_idle": 7.783,
+ "reply_sha256": "9132f20ee435bf0dc6da7145efbf26d5e204b6184bd3929a367855a47d2a067b",
+ "window_held_throughout": true,
+ "gb10_other_holders_during_decode": "",
+ "server": {"pid": 1527223, "exe": "/home/drakestapleton/.local/state/aien-q38/bin-fast-46134247/aien-serve-http", "exe_sha256": "df9360112fdc815539f3e289fccfd8070845129ef4ccb466bb90c729ec71d0e5", "args": "./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091 --max-context 131072 --max-tokens-cap 16384 --thinking off "},
+ "receipt": "/home/drakestapleton/yardsticks/receipts/2026-10-20-baseline-27b-20261020T095626Z-bd2f56.json",
+ "calibration": "/home/drakestapleton/yardsticks/windows/20261020T095626Z-bd2f56/calibration.json",
+ "note": "one streamed request; first_token_seconds includes the wait in the server's GPU-lock queue and the prefill; decode = first to last token, while the server holds the GPU lock; wall W is the whole UPS output in 10 W steps every ~2 s, so a few-second decode rests on a few samples: read J/token as coarse"
+}
diff --git a/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/calibration.json b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/calibration.json
new file mode 100644
index 0000000..8214dae
--- /dev/null
+++ b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/calibration.json
@@ -0,0 +1,14 @@
+{
+ "window_id": "20261020T095626Z-bd2f56",
+ "start": "2026-10-20T09:56:59Z",
+ "gb10_lock_waited_s": 32,
+ "gb10_lock_held_by": "calibrate",
+ "window_held_throughout": true,
+ "memcpy_probe": {"source": "omega research/cost-sim-583@3bd56731c5517e2a9c8f195955c71e73dc6f9269 tools/dagsim/memcpy_probe.c", "blob": "3c1ec3b9b68f933236beb266f11a45a4cfb2978b", "cflags": "-O2 -pthread",
+ "binary_sha256": "a9ef1c14caba26ab55edc1c93cfbbae2c65f467b6d744c429e06f500714cb28c", "cmd": "nice -n 10 memcpy_probe 1 K 10",
+ "unit": "GB/s, read+write counted twice, as in M1 block4", "k1": {"reps": 10, "GBps_median": 45.65, "GBps_min": 41.0, "GBps_max": 50.0}, "k8": {"reps": 10, "GBps_median": 86.15, "GBps_min": 66.5, "GBps_max": 120.5}},
+ "idle": {"seconds": 30, "wall_W_mean": 245.3333333, "gpu_W_mean": 7.316666667, "gpu_util_mean": 0.0,
+ "samples": 15, "load1_start": "28.67", "receipt": "/home/drakestapleton/yardsticks/receipts/2026-10-20-calib-idle-20261020T095626Z-bd2f56.json"},
+ "files": "calibration/memcpy_k1.csv calibration/memcpy_k8.csv calibration/idle-receipt.json",
+ "note": "wall W is the whole UPS output (UPS ups.load x 10, 10 W steps, ~2 s), not the Spark alone; the GPU is held idle by the GB10 lock during the 30 s but servers stay resident"
+}
diff --git a/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/close.json b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/close.json
new file mode 100644
index 0000000..cb0e30a
--- /dev/null
+++ b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/close.json
@@ -0,0 +1,7 @@
+{"window_id": "20261020T095626Z-bd2f56", "closed_by": "spark-window close", "reason": "closed", "held_s": 185, "state": {"utc": "2026-10-20T09:59:31Z", "loadavg": "38.67 34.30 34.55 44/2640 2430768", "mem_avail_kB": 51213368, "gpu_util_pct": "0", "gpu_W": "7.42",
+ "gb10_lock_holders": "holds exclusive pid 988592 (39350s) /home/drakestapleton/workspace/pipeline/target-sc/release/aien-test worker --poll 60 --github --repos omega,ai; queued exclusive pid 1527223 (47054s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; ",
+ "quiet_lock_holders": "",
+ "quiet_waiters": "",
+ "gpu_apps": "1527223, 34716 MiB, ./aien-serve-http;",
+ "sensors_row": "1792490369,2026-10-20T04:59:29-05:00,310,7.49,0,38.67,51494132,2,511", "sensors_row_age_s": 2}
+}
diff --git a/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/open.json b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/open.json
new file mode 100644
index 0000000..8999693
--- /dev/null
+++ b/docs/ops/evidence/L113-window-20261020T095626Z-bd2f56/open.json
@@ -0,0 +1,7 @@
+{"window_id": "20261020T095626Z-bd2f56", "name": "l113-window-8", "owner": "L113", "lease_min": 90, "gb10": "none", "waited_s": 1, "state": {"utc": "2026-10-20T09:56:27Z", "loadavg": "30.91 33.85 34.66 24/2633 2271089", "mem_avail_kB": 63943696, "gpu_util_pct": "0", "gpu_W": "7.52",
+ "gb10_lock_holders": "holds exclusive pid 988592 (39167s) /home/drakestapleton/workspace/pipeline/target-sc/release/aien-test worker --poll 60 --github --repos omega,ai; queued exclusive pid 1527223 (46870s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; queued exclusive pid 988592 (39167s) /home/drakestapleton/workspace/pipeline/target-sc/release/aien-test worker --poll 60 --github --repos omega,ai; queued exclusive pid 1527223 (46870s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; queued exclusive pid 1527223 (46870s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; queued exclusive pid 1527223 (46870s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; queued exclusive pid 1527223 (46870s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; queued exclusive pid 1527223 (46870s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; queued exclusive pid 1527223 (46870s) ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.8-27b-fp8-017b9c7a --port 18091; ",
+ "quiet_lock_holders": "holds exclusive pid 2269818 (s) (set by a finished flock; the open window 20261020T095626Z-bd2f56 holder 2269788 keeps it); ",
+ "quiet_waiters": "",
+ "gpu_apps": "1527223, 34716 MiB, ./aien-serve-http;",
+ "sensors_row": "1792490186,2026-10-20T04:56:26-05:00,310,7.64,0,31.51,64155016,2,503", "sensors_row_age_s": 1}
+}
diff --git a/tools/ops/README.md b/tools/ops/README.md
new file mode 100644
index 0000000..71bb46a
--- /dev/null
+++ b/tools/ops/README.md
@@ -0,0 +1,23 @@
+# tools/ops: the Spark's shared measurement base
+
+Shell tools installed in `~/.local/bin` on the Spark. These are the committed copies; install by copying
+each file over the old one (copy to a temporary name, then rename, so running jobs keep the old file).
+How and when to use them: [docs/ops/MEASUREMENT_WINDOWS.md](../../docs/ops/MEASUREMENT_WINDOWS.md).
+
+| File | Purpose |
+|---|---|
+| `spark-build-once` | Build cache keyed by the source tree, command and env knobs; concurrent callers build once |
+| `spark-window` | One measurement window at a time; holds the quiet lock exclusive; box state at open and close. A bare `close` only closes a window you opened (same shell tree, or `SPARK_WINDOW` set); otherwise refused with exit 3, use `close <ID>` |
+| `test_spark_window_close.sh` | Offline test for the close rule above (scratch locks and folder, never the live windows) |
+| `spark-calibrate` | Per-window calibration: memcpy bandwidth (omega#583 probe) and 30 s idle power at the wall |
+| `spark-baseline` | Per-window 27B baseline: fixed 64-token streamed reply on 127.0.0.1:18091, decode tok/s and J/token |
+| `spark-receipt` | Energy receipt for any command; now stamps `window_id` and `calibration` |
+| `quiet-measure` | Exclusive quiet lock for a measurement; runs directly inside its own open window |
+| `quiet-build` | Builds: since 2026-10-20 (Drake, L118) they never wait; they run on the efficient cores at low priority and are logged for overlap checks. Copy of the installed version |
+
+Shown on the Spark (2026-10-19/20): two callers on one source built once in a scratch repo (the second
+reused the stored result), two windows opened at the same moment (one refused), lease expiry, the
+`--wait` line in a sandbox (turns in arrival order, a late open refused, a waiter that gave up dropped).
+Real runs: two omega worktrees at one commit built once, identical output, a repeat in 4 s
+(docs/ops/evidence/L113-build-once-two-worktrees.md); window 20261020T095626Z-bd2f56 with a calibration
+and a passing 27B baseline (~/yardsticks/windows/20261020T095626Z-bd2f56/).
diff --git a/tools/ops/quiet-build b/tools/ops/quiet-build
new file mode 100755
index 0000000..b16739c
--- /dev/null
+++ b/tools/ops/quiet-build
@@ -0,0 +1,58 @@
+#!/bin/sh
+# quiet-build CMD... Run a build or CPU-heavy job politely.
+# Waits while a measurement is pending (flag files in /tmp/aien-quiet.want.d whose
+# owner process is alive; at most 1 min, L405), then passes the gate /tmp/aien-quiet.gate (a measurement window
+# at the front of the line holds it while the quiet lock drains; L322, 2026-10-21), then holds
+# /tmp/aien-quiet.lock shared. Locks already held are never affected by the gate.
+# L405 (2026-10-22, Drake: "stop chip locking"): correctness work never waits behind a timing
+# lock for long. ALL waiting together (flags + gate + lock) is capped at SPARK_BUILD_MAX_WAIT
+# seconds (default 1500 = 25 min: a timing window holds at most 20 min after at most 5 min of
+# draining). Past the cap the job runs anyway at nice 19, without the lock, and the overrun is
+# written to the open window (its numbers become "shared machine") and to
+# ~/.local/state/quiet/intrusions.log. Every wait is logged in ~/.local/state/quiet/waits.log.
+# SPARK_QUIET_LOCK / SPARK_QUIET_GATE / SPARK_QUIET_WANT / SPARK_WINDOWS_ROOT / SPARK_BUILD_MAX_WAIT override (tests only).
+case "${1-}" in
+ ""|-h|--help|help)
+ sed -n '2,/^[^#]/{/^#/s/^# \{0,1\}//p}' "$0"
+ exit 0 ;;
+esac
+Q=${SPARK_QUIET_LOCK:-/tmp/aien-quiet.lock}; GATE=${SPARK_QUIET_GATE:-/tmp/aien-quiet.gate}
+W=${SPARK_QUIET_WANT:-/tmp/aien-quiet.want.d}; WR=${SPARK_WINDOWS_ROOT:-$HOME/yardsticks/windows}
+MAXW=${SPARK_BUILD_MAX_WAIT:-1500}
+L=$HOME/.local/state/quiet; mkdir -p "$L" 2>/dev/null
+t0=$(date +%s); left() { r=$(( MAXW - ($(date +%s) - t0) )); [ "$r" -gt 0 ] && echo "$r" || echo 0; }
+# 1. pending measurements (flags), at most SPARK_FLAG_WAIT s (default 60; was 600 until L405: on 2026-10-22
+# one measurement queued 80 min held 14 new builds here 10 min each) and never past the cap
+while [ $(( $(date +%s) - t0 )) -lt "${SPARK_FLAG_WAIT:-60}" ] && [ "$(left)" -gt 0 ]; do
+ live=0
+ for f in "$W"/*; do
+ [ -e "$f" ] || continue
+ p=$(basename "$f" | sed 's/^legacy-//')
+ if ! kill -0 "$p" 2>/dev/null; then rm -f "$f"
+ # a measurement that has waited over SPARK_FLAG_MAX_AGE s (default 600) has had its chance; it should take a
+ # spark-window, which waits for a quiet machine (L405: one flag 80 min old paused every new build 60 s)
+ elif [ $(( $(date +%s) - $(stat -c %Y "$f" 2>/dev/null || date +%s) )) -lt "${SPARK_FLAG_MAX_AGE:-600}" ]; then live=1; fi
+ done
+ [ "$live" -eq 0 ] && break
+ sleep 5
+done
+# 2. the gate (fail open: a stuck gate never blocks a build past the cap)
+[ -e "$GATE" ] || { : > "$GATE"; chmod 666 "$GATE"; } 2>/dev/null
+[ "$(left)" -gt 0 ] && flock -s -w "$(left)" "$GATE" true 2>/dev/null
+# 3. the quiet lock, shared, on fd 9 (inherited by CMD, so it is held for CMD's life)
+[ -e "$Q" ] || { : > "$Q"; chmod 666 "$Q"; } 2>/dev/null
+exec 9<"$Q"
+if flock -s -n 9 || { [ "$(left)" -gt 0 ] && flock -s -w "$(left)" 9; }; then
+ w=$(( $(date +%s) - t0 ))
+ printf '%s waited_s=%s how=lock %s\n' "$(date -u +%FT%TZ)" "$w" "$*" | cut -c1-300 >> "$L/waits.log" 2>/dev/null
+ exec "$@"
+fi
+exec 9<&-
+w=$(( $(date +%s) - t0 ))
+id=$(cat "$WR/OPEN" 2>/dev/null)
+line="$(date -u +%FT%TZ) waited_s=$w cap_s=$MAXW window=${id:-none} pid=$$ running without the quiet lock at nice 19: $*"
+printf '%s\n' "$line" | cut -c1-300 >> "$L/intrusions.log" 2>/dev/null
+[ -n "$id" ] && [ -d "$WR/$id" ] && printf '%s\n' "$line" | cut -c1-300 >> "$WR/$id/intrusions" 2>/dev/null
+printf '%s waited_s=%s how=bypass %s\n' "$(date -u +%FT%TZ)" "$w" "$*" | cut -c1-300 >> "$L/waits.log" 2>/dev/null
+echo "quiet-build: waited ${w}s (cap ${MAXW}s) behind a timing lock; running anyway at nice 19 (L405)" >&2
+exec nice -n 19 "$@"
diff --git a/tools/ops/quiet-measure b/tools/ops/quiet-measure
new file mode 100755
index 0000000..e6b226e
--- /dev/null
+++ b/tools/ops/quiet-measure
@@ -0,0 +1,44 @@
+#!/bin/sh
+# 2026-10-20: commands are pinned to the X925 cores; old copy quiet-measure.bak-20261020.
+# quiet-measure CMD... Run a timing measurement with the box as quiet as possible.
+# Raises a "wanted" flag so quiet-build stops starting new builds, then takes
+# /tmp/aien-quiet.lock exclusive (waits for running builds to drain), after passing the gate
+# /tmp/aien-quiet.gate (held by a window waiting at the front of the line; fail open after 25 min; L322).
+# Plain flock alone starves measurements: new shared holders keep arriving.
+# Inside a measurement window (SPARK_WINDOW set by spark-window run, and that
+# window is the open one with a live holder) the lock is already held
+# exclusive for us, so CMD runs directly instead of waiting on our own lock.
+# L405: a measurement holding the lock past 25 min no longer stops builds; they run beside it and it warns.
+# Fast cores for timing (Cortex-X925: 5-9,15-19); builds live on the A725 cores. Builds running at start are logged.
+case "${1-}" in
+ ""|-h|--help|help)
+ sed -n '2,/^[^#]/{/^#/s/^# \{0,1\}//p}' "$0"
+ exit 0 ;;
+ -*)
+ echo "$(basename "$0"): unknown option '$1' (the first argument must be the command to run; try --help)" >&2
+ exit 2 ;;
+esac
+L=$HOME/.local/state/quiet; mkdir -p "$L"
+printf '%s builds_running=%s %s\n' "$(date -u +%FT%TZ)" "$(ls /tmp/aien-build.active.d 2>/dev/null | wc -l)" "$*" >> "$L/measure-overlap.log"
+PIN="taskset -c 5-9,15-19"
+if [ -n "${SPARK_WINDOW:-}" ]; then
+ WR=${SPARK_WINDOWS_ROOT:-$HOME/yardsticks/windows}
+ if [ "$(cat "$WR/OPEN" 2>/dev/null)" = "$SPARK_WINDOW" ] && [ -f "$WR/$SPARK_WINDOW/held" ] &&
+ kill -0 "$(cat "$WR/$SPARK_WINDOW/holder.pid" 2>/dev/null)" 2>/dev/null; then
+ exec $PIN "$@"
+ fi
+ echo "quiet-measure: window $SPARK_WINDOW is not open and held; taking the quiet lock the normal way" >&2
+fi
+W=${SPARK_QUIET_WANT:-/tmp/aien-quiet.want.d}; Q=${SPARK_QUIET_LOCK:-/tmp/aien-quiet.lock}; GATE=${SPARK_QUIET_GATE:-/tmp/aien-quiet.gate}
+mkdir -p "$W" 2>/dev/null; chmod 1777 "$W" 2>/dev/null
+f="$W/$$"; echo "$(date -u +%FT%TZ) $*" > "$f"
+trap 'rm -f "$f"' EXIT INT TERM
+[ -e "$GATE" ] || { : > "$GATE"; chmod 666 "$GATE"; } 2>/dev/null
+flock -s -w "${SPARK_GATE_WAIT:-1500}" "$GATE" true 2>/dev/null # fail open
+# L405: correctness jobs stop waiting after their cap (25 min) and run beside us; say so, so the numbers are labelled.
+tsf="$W/.$$.held"
+flock -x "$Q" sh -c 'date -u +%FT%TZ > "$0"; exec "$@"' "$tsf" $PIN "$@"; rc=$?
+ts=$(cat "$tsf" 2>/dev/null); rm -f "$tsf"
+n=$( [ -n "$ts" ] && awk -v t="$ts" '$1 >= t' "$L/intrusions.log" 2>/dev/null | wc -l || echo 0)
+[ "${n:-0}" -gt 0 ] && echo "quiet-measure: $n correctness job(s) ran beside this measurement after waiting their cap; label its numbers 'shared machine' (L405)" >&2
+exit $rc
diff --git a/tools/ops/spark-baseline b/tools/ops/spark-baseline
new file mode 100755
index 0000000..36d9c20
--- /dev/null
+++ b/tools/ops/spark-baseline
@@ -0,0 +1,149 @@
+#!/bin/sh
+# spark-baseline MODEL: the one baseline receipt per model per measurement window.
+#
+# spark-baseline 27b one fixed request to the resident 27B server on
+# 127.0.0.1:18091: fixed prompt, temperature 0, seed 1,
+# 64 tokens, sent once the GPU lock is quiet, timed through
+# spark-receipt. Never starts, stops or restarts a server.
+# Run inside an open window (spark-window run spark-baseline 27b). Writes
+# ~/yardsticks/windows/<id>/baseline-27b.json with the decode rate (streamed reply,
+# first to last token) and request tok/s, wall J/token over the decode
+# (receipt wall_J / tokens) and J/token above idle (window calibration idle W),
+# the reply's sha256 (same server build + same request = same reply) and the
+# server process, so a different build is visible.
+set -u
+WR=${SPARK_WINDOWS_ROOT:-$HOME/yardsticks/windows}
+model=${1:?usage: spark-baseline 27b}
+case $model in
+ 27b) port=${SPARK_BASELINE_PORT:-18091}; mid=qwen3.8-27b-fp8 ;; # port override only for tests against a stand-in server
+ *) echo "spark-baseline: unknown model $model (known: 27b)" >&2; exit 2 ;;
+esac
+id=${SPARK_WINDOW:-$(spark-window id)} || { echo "spark-baseline: no open window; run spark-window open NAME first" >&2; exit 1; }
+[ "$(cat "$WR/OPEN" 2>/dev/null)" = "$id" ] && [ -f "$WR/$id/held" ] || { echo "spark-baseline: window $id is not the open, held window" >&2; exit 1; }
+held() { [ "$(cat "$WR/OPEN" 2>/dev/null)" = "$id" ] && [ -f "$WR/$id/held" ] && [ ! -f "$WR/$id/expired" ] && kill -0 "$(cat "$WR/$id/holder.pid" 2>/dev/null)" 2>/dev/null; }
+d=$WR/$id; b=$d/baseline-$model; mkdir -p "$b"
+export SPARK_WINDOW=$id SPARK_WINDOW_DIR=$d
+# The 27B server takes the GPU lock itself for each reply. A window that holds that lock (spark-window
+# open --gb10 exclusive|shared, L154) would make the server wait for the window to end: refuse up front.
+case $(cat "$d/gb10" 2>/dev/null) in exclusive|shared)
+ echo "spark-baseline: window $id holds the GPU lock (--gb10 $(cat "$d/gb10")), so the 27B server cannot answer inside it; open the window with --gb10 none" >&2; exit 1 ;; esac
+[ -f "$d/calibration.json" ] || echo "spark-baseline: warning: window $id has no calibration.json yet (run spark-calibrate first); J/token above idle will be null" >&2
+
+N=64; SEED=1
+PROMPT="Count upward from one in English words, separated by commas, and do not stop: one, two, three,"
+REQ=$(printf '{"model": "%s", "messages": [{"role": "user", "content": "%s"}], "temperature": 0, "seed": %s, "max_tokens": %s, "stream": true, "stream_options": {"include_usage": true}}' "$mid" "$PROMPT" "$SEED" "$N")
+echo "$REQ" > "$b/request.json"
+
+spid=$(ss -ltnpH "sport = :$port" 2>/dev/null | sed -n 's/.*pid=\([0-9]*\).*/\1/p' | head -n 1)
+[ -n "$spid" ] || { echo "spark-baseline: nothing listens on 127.0.0.1:$port; not starting one" >&2; exit 1; }
+sexe=$(readlink "/proc/$spid/exe" 2>/dev/null); sargs=$(tr '\0' ' ' < "/proc/$spid/cmdline" 2>/dev/null | cut -c1-300)
+models=$(curl -s --max-time 10 "http://127.0.0.1:$port/v1/models")
+case $models in *"\"$mid\""*) ;; *) echo "spark-baseline: server on :$port does not serve $mid: $models" >&2; exit 1 ;; esac
+
+# The server takes /tmp/aien-gb10.lock itself for each generation (holding it here would deadlock),
+# and GPU-only jobs keep that lock busy. So the reply is streamed and every chunk is timestamped:
+# from the first to the last token the server holds the GPU lock for us, which makes the decode
+# rate and its energy clean whatever the queue did before. The lock table is sampled throughout;
+# any other process seen holding the GPU lock during the decode marks the baseline not ok.
+G=/tmp/aien-gb10.lock; gino=$(stat -c %i "$G")
+held || { echo "spark-baseline: window $id is not held; nothing measured" >&2; exit 1; }
+( while :; do grep -E ":$gino " /proc/locks | sed "s/^/$(date +%s.%N) /"; sleep 0.5; done ) > "$b/gb10-during.txt" 2>/dev/null &
+smp=$!
+# bash for EPOCHREALTIME: a clock read without starting a process per line, so a burst stays a burst.
+# The server serves one reply at a time and turns a request away at once (503) while another runs
+# (other clients, e.g. aien-translate, use it around the clock; a window cannot stop them). So: watch
+# /health until busy is false, send at once, and on 503 go back to watching; give up after 20 min.
+# Every try is logged in attempts.txt. A reply line without a final newline (an error body) is kept.
+rm -f "$b/attempts.txt" "$b/headers.txt"
+spark-receipt "baseline-$model-$id" --idle 10 -- bash -c '
+ end=$(( ${EPOCHREALTIME%.*} + 1200 )); i=0; w=0
+ while [ ${EPOCHREALTIME%.*} -lt $end ]; do
+ case $(curl -s --max-time 2 "$6") in *"\"busy\":false"*) ;; *) w=$((w + 1)); sleep 0.2; continue ;; esac
+ i=$((i + 1)); echo "send $EPOCHREALTIME after $w busy polls" >> "$5"
+ curl -sN -D "$4" -H "Content-Type: application/json" --data-binary @"$1" "$2" |
+ while IFS= read -r l || [ -n "$l" ]; do printf "%s %s\n" "$EPOCHREALTIME" "$l"; done > "$3"
+ c=$(awk "NR == 1 { print \$2 }" "$4" 2>/dev/null)
+ echo "try $i http ${c:-none} $EPOCHREALTIME $(head -c 160 "$3" | tr "\n" " ")" >> "$5"
+ [ "$c" = 503 ] || break
+ done
+ exit 0' bash "$b/request.json" "http://127.0.0.1:$port/v1/chat/completions" "$b/stream.txt" "$b/headers.txt" "$b/attempts.txt" "http://127.0.0.1:$port/health" > "$b/receipt.out" 2>&1
+rc=$?
+tsend=$(awk '$1 == "send" { t = $2 } END { print t }' "$b/attempts.txt" 2>/dev/null)
+tries=$(grep -c '^try ' "$b/attempts.txt" 2>/dev/null); tries=${tries:-0}
+kill $smp 2>/dev/null; wait $smp 2>/dev/null
+held && wheld=true || wheld=false
+# chunks: "<epoch> data: {json}"; content chunks carry choices[0].delta.content
+grep -E '^[0-9.]+ data: \{' "$b/stream.txt" | while read -r t _ j; do
+ printf '%s\t%s\n' "$t" "$(printf '%s' "$j" | jq -c '[(.choices[0].delta.content // ""), (.usage.completion_tokens // null), (.choices[0].finish_reason // null)]')"
+done > "$b/chunks.tsv"
+cut -f2 "$b/chunks.tsv" | jq -rj '.[0]' > "$b/reply.txt"
+nchunk=$(cut -f2 "$b/chunks.tsv" | jq -r 'select(.[0] != "") | 1' | wc -l)
+t_first=$(awk -F'\t' '$2 !~ /^\[""/ {print $1; exit}' "$b/chunks.tsv")
+t_last=$(awk -F'\t' '$2 !~ /^\[""/ {t=$1} END {print t}' "$b/chunks.tsv")
+toks=$(cut -f2 "$b/chunks.tsv" | jq -r '.[1] // empty' | tail -n 1); toks=${toks:-$nchunk}
+fin=$(cut -f2 "$b/chunks.tsv" | jq -r '.[2] // empty' | tail -n 1); fin=${fin:-none}
+# the server logs its own prefill and decode timing per reply under the reply id: keep that line as a cross-check
+cid=$(grep -m 1 -E '^[0-9.]+ data: \{' "$b/stream.txt" | cut -d" " -f3- | jq -r '.id // empty' 2>/dev/null)
+slog=$(readlink "/proc/$spid/fd/2" 2>/dev/null)
+sline=""; [ -n "$cid" ] && [ -f "$slog" ] && sline=$(grep -F "$cid:" "$slog" | tail -n 1 | cut -c1-400)
+code=$(awk 'NR == 1 { print $2 }' "$b/headers.txt" 2>/dev/null); code=${code:-0}
+secs=$(awk -v a="$tsend" -v b="$t_last" 'BEGIN { if (b == "") print "null"; else printf "%.3f\n", b - a }')
+ttft=$(awk -v a="$tsend" -v b="$t_first" 'BEGIN { if (b == "") print "null"; else printf "%.3f\n", b - a }')
+dsecs=$(awk -v a="$t_first" -v b="$t_last" 'BEGIN { if (a == "" || b == "") print "null"; else printf "%.3f\n", b - a }')
+others=$(awk -v s="$spid" -v a="${t_first:-0}" -v e="${t_last:-0}" '$1 >= a && $1 <= e { if ($3 != "->" && $6 != s) print $6 }' "$b/gb10-during.txt" | sort -u | tr '\n' ' ')
+# wall power over the decode only, from the sensor rows (same CSV spark-receipt reads)
+dec=$(awk -F, -v a="${t_first:-0}" -v e="${t_last:-0}" '$1 ~ /^[0-9]+$/ && $1 >= int(a) && $1 <= int(e) + 1 && $3 ~ /^[0-9.]+$/ { w += $3; n++ } END { if (n) printf "%.6g %d\n", w / n, n; else print "null 0" }' "$HOME/yardsticks/sensors/$(date -d "@${t_first%.*}" +%F 2>/dev/null || date +%F).csv" 2>/dev/null)
+dW=${dec% *}; dn=${dec#* }
+r=$(sed -n 's/^receipt: //p' "$b/receipt.out"); cp "$r" "$b/receipt.json" 2>/dev/null
+rsha=$(sha256sum < "$b/reply.txt" | cut -c1-64)
+idleW=$(jq -r '.idle.wall_W_mean // "null"' "$d/calibration.json" 2>/dev/null); idleW=${idleW:-null}
+num() { awk -v x="$1" 'BEGIN { if (x == "" || x == "null") print "null"; else print x + 0 }'; }
+# values go in as awk variables, never pasted into the program: a pasted 0 divisor is a gawk error
+q() { awk -v s="$1" -v t="$2" -v w="$3" -v i="$4" -v op="$5" 'BEGIN {
+ if (s == "" || s == "null" || s + 0 <= 0 || t + 0 == 0 || (op != "rate" && (w == "" || w == "null")) || (op == "above" && (i == "" || i == "null"))) { print "null"; exit }
+ if (op == "rate") printf "%.4g\n", t / s; else if (op == "wall") printf "%.4g\n", w * s / t; else printf "%.4g\n", (w - i) * s / t }'; }
+# tokens that arrived after the first content chunk; when chunks carry more than one token, scale by tokens per chunk
+dtoks=$(awk -v t="$toks" -v c="$nchunk" 'BEGIN { if (c < 2) print 0; else if (t == c) print t - 1; else printf "%.6g\n", (c - 1) * t / c }')
+tps=$(q "$secs" "$toks" "" "" rate)
+dtps=$(q "$dsecs" "$dtoks" "" "" rate)
+djpt=$(q "$dsecs" "$dtoks" "$dW" "" wall)
+djpt_inc=$(q "$dsecs" "$dtoks" "$dW" "$idleW" above)
+# a decode of under 50 ms for many tokens means the server sent the reply in one burst, not as it decoded
+burst=$(awk -v s="$dsecs" -v t="$dtoks" 'BEGIN { print (t + 0 > 4 && (s == "null" || s + 0 < 0.05)) ? "true" : "false" }')
+ok=true; [ "$rc" = 0 ] && [ "$code" = 200 ] && [ "$toks" = "$N" ] && [ -z "$others" ] && [ "$wheld" = true ] && [ "$burst" = false ] || ok=false
+cat > "$b.json.tmp" <<EOJ
+{
+ "window_id": "$id",
+ "model": "$mid",
+ "ok": $ok,
+ "request": {"url": "http://127.0.0.1:$port/v1/chat/completions", "max_tokens": $N, "temperature": 0, "seed": $SEED, "stream": true, "file": "$b/request.json"},
+ "completion_tokens": $toks,
+ "content_chunks": $nchunk,
+ "decode_tokens_counted": $dtoks,
+ "stream_arrived_in_one_burst": $burst,
+ "finish_reason": "$fin",
+ "http_code": $code,
+ "tries": $tries,
+ "server_log_line": $(printf '%s' "$sline" | jq -Rs .),
+ "request_seconds": $(num "$secs"),
+ "first_token_seconds": $(num "$ttft"),
+ "tok_per_s_request": $tps,
+ "decode_seconds": $(num "$dsecs"),
+ "decode_tok_per_s": $dtps,
+ "decode_wall_W_mean": $(num "$dW"),
+ "decode_sensor_samples": $dn,
+ "decode_wall_J_per_token": $djpt,
+ "idle_W_calibration": $(num "$idleW"),
+ "decode_J_per_token_above_idle": $djpt_inc,
+ "reply_sha256": "$rsha",
+ "window_held_throughout": $wheld,
+ "gb10_other_holders_during_decode": "$others",
+ "server": {"pid": $spid, "exe": "$sexe", "exe_sha256": "$(sha256sum "$sexe" 2>/dev/null | cut -c1-64)", "args": "$(printf '%s' "$sargs" | sed 's/"/\\"/g')"},
+ "receipt": "$r",
+ "calibration": "$( [ -f "$d/calibration.json" ] && echo "$d/calibration.json")",
+ "note": "one streamed request; first_token_seconds includes the wait in the server's GPU-lock queue and the prefill; decode = first to last token, while the server holds the GPU lock; wall W is the whole UPS output in 10 W steps every ~2 s, so a few-second decode rests on a few samples: read J/token as coarse"
+}
+EOJ
+mv -f "$b.json.tmp" "$b.json"
+cat "$b.json"; echo "baseline: $b.json"
+[ "$ok" = true ]
diff --git a/tools/ops/spark-build-once b/tools/ops/spark-build-once
new file mode 100755
index 0000000..d0b81d2
--- /dev/null
+++ b/tools/ops/spark-build-once
@@ -0,0 +1,121 @@
+#!/bin/sh
+# spark-build-once [--out PATH]... [--link] [--] CMD...
+#
+# Build once, reuse everywhere. Run from inside a git worktree. The cache key is
+# the source tree as it is on disk (HEAD tree + uncommitted diff + untracked,
+# not-ignored files), the folder you run from, the exact command, the --out
+# list, the machine type, and the env knobs PHYSICS_DIR / AIENOS_LOCK_REPO (their
+# values, plus their own tree hash when they point into a git worktree).
+#
+# hit : copies the stored artifacts into your --out paths (or symlinks with
+# --link) and returns in seconds; the build does not run.
+# miss: runs CMD through quiet-build, then stores every --out path under
+# $SPARK_BUILD_CACHE/<key> by atomic rename. A failed build stores nothing.
+#
+# Concurrent callers with the same key: one builds, the others wait on the
+# per-key lock (they print who holds it and for how long) and then take the hit.
+# Every call appends one line to ~/yardsticks/build-once.log.
+# Exit code: the build's own on a miss, 0 on a hit, 2 on usage errors.
+set -u
+C=${SPARK_BUILD_CACHE:-$HOME/.cache/spark-build-once}
+LOG=$HOME/yardsticks/build-once.log
+outs=""; link=0
+while [ $# -gt 0 ]; do
+ case $1 in
+ --out) [ $# -ge 2 ] || { echo "spark-build-once: --out needs a path" >&2; exit 2; }
+ case $2 in /*|*..*) echo "spark-build-once: --out must be a relative path inside the worktree: $2" >&2; exit 2;; esac
+ outs="$outs
+$2"; shift 2 ;;
+ --link) link=1; shift ;;
+ --) shift; break ;;
+ -h|--help) sed -n '2,20p' "$0"; exit 0 ;;
+ *) break ;;
+ esac
+done
+[ $# -gt 0 ] || { echo "usage: spark-build-once [--out PATH]... [--link] [--] CMD..." >&2; exit 2; }
+outs=$(printf '%s\n' "$outs" | sed '/^$/d')
+[ -n "$outs" ] || { echo "spark-build-once: name at least one artifact with --out PATH" >&2; exit 2; }
+top=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "spark-build-once: not inside a git worktree" >&2; exit 2; }
+mkdir -p "$C" "$(dirname "$LOG")"
+
+# tree_hash DIR: HEAD tree + hash of uncommitted diff and untracked files (writes no git objects)
+tree_hash() {
+ ( cd "$1" || exit 1
+ t=$(git rev-parse -q --verify 'HEAD^{tree}' 2>/dev/null || echo none)
+ d=$( { git diff HEAD --binary 2>/dev/null; git ls-files -o --exclude-standard -z | xargs -0 -r sha256sum; } | sha256sum | cut -c1-64)
+ echo "$t $d" )
+}
+src=$(tree_hash "$top")
+knobs=""
+for v in PHYSICS_DIR AIENOS_LOCK_REPO; do
+ eval "val=\${$v:-}"
+ h=""
+ if [ -n "$val" ] && [ -d "$val" ] && kt=$(git -C "$val" rev-parse --show-toplevel 2>/dev/null); then h=$(tree_hash "$kt"); fi
+ knobs="$knobs $v=$val[$h]"
+done
+cmdh=$(printf '%s\0' "$@" | sha256sum | cut -c1-64)
+key=$(printf 'v1\n%s\n%s\n%s\n%s\n%s\n%s\n' "$src" "$(git rev-parse --show-prefix)" "$cmdh" "$outs" "$knobs" "$(uname -m)" | sha256sum | cut -c1-24)
+D=$C/$key
+t0=$(date +%s)
+log() { printf '%s\t%s\t%s\t%ss\t%s\t' "$(date -u +%FT%TZ)" "$key" "$1" "$(( $(date +%s) - t0 ))" "$PWD" >> "$LOG"; shift; printf '%s ' "$@" | tr '\t\n' ' ' >> "$LOG"; echo >> "$LOG"; }
+echo "spark-build-once: key $key (source $(echo "$src" | cut -c1-12), cmd: $*)" >&2
+
+restore() {
+ while IFS= read -r p; do
+ s=$D/out/$p
+ [ -e "$s" ] || [ -L "$s" ] || { echo "spark-build-once: cache entry $key lacks $p" >&2; return 1; }
+ mkdir -p "$(dirname "$p")"
+ if [ "$link" = 1 ]; then
+ if [ -d "$p" ] && [ ! -L "$p" ]; then echo "spark-build-once: --link refuses to replace the real directory $p" >&2; return 1; fi
+ ln -sfn "$s" "$p" || return 1
+ elif [ -d "$s" ] && [ ! -L "$s" ]; then
+ mkdir -p "$p" && cp -a "$s/." "$p/" || return 1
+ else
+ cp -a --remove-destination "$s" "$p" || return 1
+ fi
+ done <<EOF
+$outs
+EOF
+}
+
+hit() {
+ restore || { log FAIL-RESTORE "$@"; exit 1; }
+ echo "spark-build-once: HIT $key (built $(sed -n 's/^built //p' "$D/meta") in $(sed -n 's/^from //p' "$D/meta"); $(( $(date +%s) - t0 )) s)" >&2
+ log HIT "$@"; exit 0
+}
+
+# fast path: already stored, no lock needed (entries are only ever created by rename)
+[ -f "$D/meta" ] && hit "$@"
+
+exec 8>"$D.lock"
+if ! flock -n 8; then
+ ( exec 8>&-; while sleep 60; do echo "spark-build-once: waiting $(( $(date +%s) - t0 )) s for key $key, held by: $(cat "$D.who" 2>/dev/null || echo unknown)" >&2; done ) &
+ tick=$!
+ flock 8
+ kill $tick 2>/dev/null
+fi
+echo "pid $$ since $(date -u +%FT%TZ) in $PWD" > "$D.who"
+[ -f "$D/meta" ] && hit "$@"
+
+echo "spark-build-once: MISS $key, building through quiet-build" >&2
+quiet-build "$@"; rc=$?
+if [ $rc -ne 0 ]; then echo "spark-build-once: build failed (exit $rc), nothing stored" >&2; log "FAIL-$rc" "$@"; exit $rc; fi
+T=$C/.tmp.$key.$$
+rm -rf -- "$T"; mkdir -p "$T/out"
+ok=1
+while IFS= read -r p; do
+ if [ ! -e "$p" ]; then echo "spark-build-once: build passed but --out $p does not exist; not stored" >&2; ok=0; continue; fi
+ mkdir -p "$T/out/$(dirname "$p")" && cp -a "$p" "$T/out/$p" || ok=0
+done <<EOF
+$outs
+EOF
+if [ $ok = 1 ]; then
+ { echo "key $key"; echo "built $(date -u +%FT%TZ)"; echo "from $PWD"; echo "seconds $(( $(date +%s) - t0 ))"
+ echo "source $src"; echo "knobs$knobs"; printf 'cmd'; printf ' %s' "$@"; echo; echo "outs"; echo "$outs"; } > "$T/meta"
+ mv -T "$T" "$D" 2>/dev/null || { rm -rf -- "$T"; echo "spark-build-once: another caller stored $key first; kept theirs" >&2; }
+ echo "spark-build-once: stored $key ($(du -sh "$D" | cut -f1))" >&2
+ log MISS-STORED "$@"
+else
+ rm -rf -- "$T"; log MISS-NOTSTORED "$@"
+fi
+exit 0
diff --git a/tools/ops/spark-calibrate b/tools/ops/spark-calibrate
new file mode 100755
index 0000000..c8f3b52
--- /dev/null
+++ b/tools/ops/spark-calibrate
@@ -0,0 +1,97 @@
+#!/bin/sh
+# spark-calibrate: the one calibration file of a measurement window.
+#
+# Run inside an open window (spark-window run spark-calibrate, or with
+# SPARK_WINDOW set). Holding /tmp/aien-gb10.lock (waits for it, printing the
+# holders every 60 s), it measures:
+# 1. CPU memory bandwidth with the omega#583 memcpy probe (pinned source
+# omega research/cost-sim-583@3bd56731 tools/dagsim/memcpy_probe.c), the
+# same call research/583 used: nice -n 10 memcpy_probe 1 K 10, K = 1 and 8.
+# Skipped (and said so) when MemAvailable is under 14.5 GiB (12 GiB
+# headroom rule plus the probe's 2 GB).
+# 2. Idle power at the wall: 30 s of nothing, through spark-receipt.
+# Writes ~/yardsticks/windows/<id>/calibration.json (raw CSVs and the idle
+# receipt beside it). Every receipt taken later in the window links that file.
+set -u
+WR=${SPARK_WINDOWS_ROOT:-$HOME/yardsticks/windows}
+id=${SPARK_WINDOW:-$(spark-window id)} || { echo "spark-calibrate: no open window; run spark-window open NAME first" >&2; exit 1; }
+[ "$(cat "$WR/OPEN" 2>/dev/null)" = "$id" ] && [ -f "$WR/$id/held" ] || { echo "spark-calibrate: window $id is not the open, held window" >&2; exit 1; }
+held() { [ "$(cat "$WR/OPEN" 2>/dev/null)" = "$id" ] && [ -f "$WR/$id/held" ] && [ ! -f "$WR/$id/expired" ] && kill -0 "$(cat "$WR/$id/holder.pid" 2>/dev/null)" 2>/dev/null; }
+d=$WR/$id; mkdir -p "$d/calibration"
+export SPARK_WINDOW=$id SPARK_WINDOW_DIR=$d
+G=/tmp/aien-gb10.lock
+
+# the probe, built once per source blob + flags
+REPO=${OMEGA_REPO:-$HOME/workspace/omega}; PIN=3bd56731c5517e2a9c8f195955c71e73dc6f9269; SRC=tools/dagsim/memcpy_probe.c
+CFLAGS="-O2 -pthread"
+blob=$(git -C "$REPO" rev-parse "$PIN:$SRC" 2>/dev/null) || { echo "spark-calibrate: cannot read $SRC at $PIN in $REPO (git fetch origin research/cost-sim-583)" >&2; exit 1; }
+P=$HOME/.cache/spark-shared/memcpy_probe-$(echo "$blob $CFLAGS" | sha256sum | cut -c1-12)
+if [ ! -x "$P" ]; then
+ mkdir -p "${P%/*}"
+ git -C "$REPO" cat-file -p "$blob" > "$P.c" && cc $CFLAGS -o "$P.tmp.$$" "$P.c" && mv -f "$P.tmp.$$" "$P" || { echo "spark-calibrate: probe build failed" >&2; exit 1; }
+fi
+
+t0=$(date +%s)
+# A window opened with --gb10 exclusive|shared already holds the GPU lock for us (spark-window, L154);
+# taking it again here would wait on our own window forever.
+gmode=$(cat "$WR/$id/gb10" 2>/dev/null || echo legacy)
+case $gmode in
+ exclusive|shared) ;;
+ *) exec 9>"$G"
+ # Wait in the queue without stepping out of it (a timed retry loses the place to newer waiters);
+ # a separate ticker prints who holds the lock every 60 s.
+ ( exec 9>&-; while sleep 60; do echo "spark-calibrate: waiting $(( $(date +%s) - t0 )) s for the GB10 lock: $(spark-window locks gb10)" >&2; done ) &
+ tick=$!
+ flock 9
+ kill $tick 2>/dev/null ;;
+esac
+gwait=$(( $(date +%s) - t0 ))
+held || { echo "spark-calibrate: window $id lapsed (lease ran out or closed) while waiting for the GB10 lock; nothing measured" >&2; exit 1; }
+start=$(date -u +%FT%TZ)
+
+stat_csv() { # median/min/max of column 5 (GB/s) in a probe CSV, as JSON
+ grep -v '^#' "$1" | grep -E '^[0-9]' | cut -d, -f5 | sort -n | awk '
+ { v[NR] = $1 } END { if (!NR) { print "null"; exit }
+ m = (NR % 2) ? v[(NR+1)/2] : (v[NR/2] + v[NR/2+1]) / 2
+ printf "{\"reps\": %d, \"GBps_median\": %s, \"GBps_min\": %s, \"GBps_max\": %s}", NR, m, v[1], v[NR] }'
+}
+avail=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
+probe_json=""
+for k in 1 8; do
+ f=$d/calibration/memcpy_k$k.csv
+ if [ "$avail" -lt 15204352 ]; then
+ echo "# SKIPPED k=$k: MemAvailable $avail kB under 14.5 GiB" > "$f"; s=null
+ else
+ nice -n 10 "$P" 1 $k 10 > "$f" 2>&1; s=$(stat_csv "$f")
+ fi
+ probe_json="$probe_json\"k$k\": $s, "
+ avail=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
+done
+
+# 30 s idle at the wall; receipt name carries the window id so windows never overwrite each other
+spark-receipt "calib-idle-$id" --idle 0 -- sleep 30 > "$d/calibration/idle.out" 2>&1
+r=$(sed -n 's/^receipt: //p' "$d/calibration/idle.out")
+cp "$r" "$d/calibration/idle-receipt.json"
+jv() { sed -n "s/^ *\"$1\": \([^,]*\),\{0,1\}$/\1/p" "$d/calibration/idle-receipt.json"; }
+held && wheld=true || wheld=false
+flock -u 9
+
+cat > "$d/calibration.json.tmp" <<EOF
+{
+ "window_id": "$id",
+ "start": "$start",
+ "gb10_lock_waited_s": $gwait,
+ "gb10_lock_held_by": "$( case $gmode in exclusive|shared) echo "window ($gmode)" ;; *) echo calibrate ;; esac )",
+ "window_held_throughout": $wheld,
+ "memcpy_probe": {"source": "omega research/cost-sim-583@$PIN $SRC", "blob": "$blob", "cflags": "$CFLAGS",
+ "binary_sha256": "$(sha256sum "$P" | cut -c1-64)", "cmd": "nice -n 10 memcpy_probe 1 K 10",
+ "unit": "GB/s, read+write counted twice, as in M1 block4", ${probe_json%, }},
+ "idle": {"seconds": 30, "wall_W_mean": $(jv wall_W_mean), "gpu_W_mean": $(jv gpu_W_mean), "gpu_util_mean": $(jv gpu_util_mean),
+ "samples": $(jv samples), "load1_start": $(jv load1_start), "receipt": "$r"},
+ "files": "calibration/memcpy_k1.csv calibration/memcpy_k8.csv calibration/idle-receipt.json",
+ "note": "wall W is the whole UPS output (UPS ups.load x 10, 10 W steps, ~2 s), not the Spark alone; the GPU is held idle by the GB10 lock during the 30 s but servers stay resident"
+}
+EOF
+mv -f "$d/calibration.json.tmp" "$d/calibration.json"
+cat "$d/calibration.json"
+echo "calibration: $d/calibration.json"
diff --git a/tools/ops/spark-receipt b/tools/ops/spark-receipt
new file mode 100755
index 0000000..f0069c3
--- /dev/null
+++ b/tools/ops/spark-receipt
@@ -0,0 +1,102 @@
+#!/bin/sh
+# spark-receipt: run a command between sensor samples and print a receipt.
+#
+# usage: spark-receipt NAME [--idle SECS] -- CMD ARGS...
+# Records start/end, reads ~/yardsticks/sensors/<date>.csv for the window,
+# and writes ~/yardsticks/receipts/<date>-<NAME>.json with:
+# wall energy (J) over the run, mean wall W, mean GPU W, idle baseline W
+# (mean of the --idle seconds before start, default 30), incremental J,
+# load and MemAvailable at start/end, lock holders, NVRM error delta,
+# command, exit code, git head of cwd if any. Energy resolution: the UPS
+# reports 1% of 1000 W every ~2 s, so numbers under ~20 J are noise.
+# Measurement windows (spark-window): when SPARK_WINDOW is set (spark-window
+# run sets it), the receipt also carries window_id and the path of that
+# window's calibration.json (null when either is absent).
+# Shell + awk port of the earlier Python version: same keys, same file name,
+# same stdout (command output, then the JSON, then "receipt: PATH").
+set -u
+usage() { sed -n '2,17p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }
+[ $# -ge 1 ] || usage
+name=$1; shift; idle=30
+while [ $# -gt 0 ] && [ "$1" != "--" ]; do
+ case $1 in --idle) idle=${2:?}; shift 2 ;; *) shift ;; esac
+done
+[ $# -gt 0 ] || usage
+shift
+[ $# -gt 0 ] || usage
+S=$HOME/yardsticks/sensors; R=$HOME/yardsticks/receipts; WR=${SPARK_WINDOWS_ROOT:-$HOME/yardsticks/windows}
+t_idle0=$(( $(date +%s) - idle ))
+head=$(git rev-parse --short HEAD 2>/dev/null)
+start=$(date +%Y-%m-%dT%H:%M:%S.%6N)
+t0=$(date +%s.%N)
+"$@"; rc=$?
+t1=$(date +%s.%N)
+sleep 3
+win=${SPARK_WINDOW:-}; cal=""
+if [ -n "$win" ]; then
+ wd=${SPARK_WINDOW_DIR:-$WR/$win}
+ [ -f "$wd/calibration.json" ] && cal=$wd/calibration.json
+fi
+i0=${t0%.*}; i1=${t1%.*}
+files=""
+for d in $(date -d "@$t_idle0" +%F) $(date -d "@$i0" +%F) $(date -d "@$i1" +%F); do
+ case " $files " in *" $S/$d.csv "*) ;; *) [ -f "$S/$d.csv" ] && files="$files $S/$d.csv" ;; esac
+done
+mkdir -p "$R"
+p=$R/$(date +%F)-$name.json
+cmd=$(printf '%s ' "$@"); cmd=${cmd% }
+# shellcheck disable=SC2086
+awk -F, -v name="$name" -v cmd="$cmd" -v rc="$rc" -v head="$head" -v start="$start" \
+ -v t0="$t0" -v t1="$t1" -v ti="$t_idle0" -v i0="$i0" -v i1="$i1" -v win="$win" -v cal="$cal" '
+function isnum(s) { return s ~ /^[ \t]*[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?[ \t]*$/ }
+function esc(s) { gsub(/\\/, "\\\\", s); gsub(/"/, "\\\"", s); gsub(/\t/, "\\t", s); gsub(/\n/, "\\n", s); gsub(/\r/, "\\r", s); return s }
+function str(s) { return "\"" esc(s) "\"" }
+function strn(s) { return s == "" ? "null" : str(s) }
+function n(x, s) { s = sprintf("%.10g", x); if (s !~ /[.eEn]/) s = s ".0"; return s } # floats keep a decimal point, as the Python version printed them
+!isnum($1) { next }
+{ t = int($1) }
+t >= ti && t <= i0 && isnum($3) { pre_w += $3; pre_n++ }
+t >= i0 && t <= i1 {
+ nr++; ts[nr] = t; ix[nr] = nr; row[nr] = $0
+}
+END {
+ # rows in time order, stable (insertion sort on the epoch)
+ for (i = 2; i <= nr; i++) { v = ts[i]; x = ix[i]; j = i - 1; while (j > 0 && ts[j] > v) { ts[j+1] = ts[j]; ix[j+1] = ix[j]; j-- } ts[j+1] = v; ix[j+1] = x }
+ for (i = 1; i <= nr; i++) {
+ split(row[ix[i]], c, ",")
+ if (isnum(c[3])) { w += c[3]; wn++ }
+ if (isnum(c[4])) { g += c[4]; gn++ }
+ if (isnum(c[5])) { u += c[5]; un++ }
+ if (isnum(c[8]) && (lk == "" || c[8] + 0 > lk + 0)) lk = c[8] + 0
+ if (i == 1) { l0 = c[6]; m0 = c[7]; e0 = c[9] }
+ if (i == nr) { l1 = c[6]; m1 = c[7]; e1 = c[9] }
+ }
+ dur = t1 - t0
+ wm = wn ? w / wn : ""; im = pre_n ? pre_w / pre_n : ""
+ print "{"
+ print " \"name\": " str(name) ","
+ print " \"cmd\": " str(cmd) ","
+ print " \"exit\": " rc ","
+ print " \"git_head\": " strn(head) ","
+ print " \"start\": " str(start) ","
+ print " \"seconds\": " sprintf("%.3f", dur) ","
+ print " \"samples\": " nr + 0 ","
+ print " \"wall_W_mean\": " (wn ? n(wm) : "null") ","
+ print " \"wall_J\": " (wn ? n(wm * dur) : "null") ","
+ print " \"idle_W_before\": " (pre_n ? n(im) : "null") ","
+ print " \"incremental_J\": " ((wn && pre_n) ? n((wm - im) * dur) : "null") ","
+ print " \"gpu_W_mean\": " (gn ? n(g / gn) : "null") ","
+ print " \"gpu_util_mean\": " (un ? n(u / un) : "null") ","
+ print " \"load1_start\": " (nr ? str(l0) : "null") ","
+ print " \"load1_end\": " (nr ? str(l1) : "null") ","
+ print " \"mem_avail_kB_start\": " (nr ? str(m0) : "null") ","
+ print " \"mem_avail_kB_end\": " (nr ? str(m1) : "null") ","
+ print " \"lock_holders_max\": " (lk == "" ? "null" : lk) ","
+ print " \"nvrm_errors_delta\": " ((nr && isnum(e0) && isnum(e1)) ? e1 - e0 : "null") ","
+ print " \"note\": \"wall W = UPS ups.load x 10 (CP1500PFCLCD, 1 percent steps, ~2 s); whole UPS output, not the Spark alone\","
+ print " \"window_id\": " strn(win) ","
+ print " \"calibration\": " strn(cal)
+ print "}"
+}' $files /dev/null > "$p.tmp.$$" && mv -f "$p.tmp.$$" "$p"
+cat "$p"; echo "receipt: $p"
+exit $rc
diff --git a/tools/ops/spark-window b/tools/ops/spark-window
new file mode 100755
index 0000000..b738e94
--- /dev/null
+++ b/tools/ops/spark-window
@@ -0,0 +1,421 @@
+#!/bin/sh
+# spark-window: one measurement window at a time on the Spark.
+#
+# spark-window open NAME [--ledger ID] [--lease MIN] [--gb10 exclusive|shared|none] [--quiet exclusive|none] [--wait]
+# Refuses (exit 3) if a window is already open or anyone is in line, and
+# lists them. With --wait it takes a ticket and waits its turn instead:
+# first come, first served (L113, 2026-10-20: retrying every 15 s lost
+# the turn for 4 h).
+# Otherwise creates window id <UTC date-time>-<random>, FIRST takes the
+# chip lock /tmp/aien-gb10.lock (default exclusive; none skips it), THEN
+# the quiet lock exclusive. While it waits for the chip it holds nothing,
+# so it never blocks CPU timings (L154, 2026-10-20: a window held the
+# quiet lock 25 min while its own GPU job queued for the chip). Once it
+# has the chip it KEEPS it while it waits for the quiet lock, and raises a
+# gate (/tmp/aien-quiet.gate, exclusive) so new quiet-build / quiet-measure
+# callers wait outside while the ones already holding the quiet lock finish
+# (L322, 2026-10-21: with no gate, shared takers kept arriving, the
+# exclusive waiter never won, and each time the window let the chip go a raw
+# flock user took it: 40+ min for the front of the line).
+# L405 (2026-10-22): the window drains the quiet lock for at most 5 min, then lets
+# everything go and waits for a quiet machine again; quiet-build gives up waiting after 25 min.
+# Deadlock guard: measurements take quiet then chip, so if a process waiting
+# for the chip holds the quiet lock, the window lets the chip go (gate stays
+# up), waits for quiet, then tries the chip without blocking.
+# --quiet none: chip lock only, no quiet lock and no gate. For chip checks that
+# compare VALUES (routes, logits, cosines), not times: the quiet lock exists for
+# timings only. Never use it for a number you will report as a speed.
+# A holder process keeps the locks until close or until the lease runs out
+# (default and maximum 20 min when it takes anything exclusive; 90 min otherwise). Records box state at open in
+# ~/yardsticks/windows/<id>/open.json and prints the id. While waiting it
+# prints who holds each lock.
+# spark-window run CMD... run CMD inside the open window: sets SPARK_WINDOW and
+# SPARK_WINDOW_DIR, so spark-receipt stamps the window id and calibration,
+# and, when the window holds the chip lock, AIEN_GB10_LOCK_HELD=1, so a
+# job that honours it (aien-test gates, the 27B server) does not queue
+# behind its own window. A job that takes /tmp/aien-gb10.lock itself and
+# ignores the marker (plain flock) waits until the window closes: open
+# such windows with --gb10 none. quiet-measure run inside the window runs CMD
+# directly instead of waiting on our own lock.
+# spark-window close [ID] release the quiet lock, record box state at close
+# (close.json), print what the window holds. With an ID it closes only that
+# window. Without one it closes the open window only if you own it: the shell
+# that ran open is in your process tree, or $SPARK_WINDOW (set by run) is its id.
+# Otherwise it refuses (exit 3) and prints the holder; close it by ID or wait.
+# spark-window status show the open window (or "none") and the lock queue.
+# spark-window id print the open, held window id (exit 1 if none).
+# spark-window locks [gb10|quiet] who holds and who is queued on the locks (kernel lock table).
+#
+# L405 lock policy (Drake 2026-10-22: "stop chip locking"):
+# 1. Correctness work (builds, host tests, QEMU, crumb checks, value gates) takes no exclusive lock and waits
+# at most 25 min behind a timing lock (quiet-build), then runs anyway and the window is marked "shared machine".
+# 2. Exclusive windows are for TIMING receipts only and last at most 20 min (open refuses more). A window
+# that overruns is let go and gets NO VERDICT. Split long measurements, or run on the shared machine labelled so.
+# 3. A timing window opens only when the machine is quiet anyway: at most 3 jobs on the quiet lock and load at
+# most 10 (numbers from the L371 incident: 3.25 new builds per 20 min). It waits, holding nothing, until then.
+# 4. Test model servers use their own chip lock (q36-extra sets AIEN_SERVE_GPU_LOCK), like the live server.
+# 5. lock-long-holds (cron, 5 min) posts every exclusive hold over 20 min on the board and asks spark-window to
+# close a window past its lease; it never kills jobs.
+# Rule: one window at a time. Wait your turn with open --wait (first come, first served) and
+# say so on the ledger (ledger note <your id> "measure: in line for a window").
+set -u
+WR=${SPARK_WINDOWS_ROOT:-$HOME/yardsticks/windows}
+Q=${SPARK_QUIET_LOCK:-/tmp/aien-quiet.lock}; W=${SPARK_QUIET_WANT:-/tmp/aien-quiet.want.d}; G=${SPARK_GB10_LOCK:-/tmp/aien-gb10.lock} # overrides: tests only
+# writer-preference gate (see _hold): quiet-build and quiet-measure pass through it before taking the quiet lock
+GATE=${SPARK_QUIET_GATE:-/tmp/aien-quiet.gate}
+# L405 limits (numbers from the 2026-10-21 L371 incident: the build line grew from 3 to 29 in 160 min,
+# 3.25 new jobs per 20 min, calc:691a9354): exclusive leases at most LEASE_MAX min; open only when at most
+# IDLE_N jobs hold or wait on the quiet lock and the 1-min load is at most IDLE_LOAD; drain the quiet lock
+# for at most DRAIN_MAX s, else let go and wait for quiet again; give up after IDLE_MAX s of waiting.
+# Builds wait at most DRAIN_MAX + LEASE_MAX (25 min, quiet-build SPARK_BUILD_MAX_WAIT) behind a window.
+LEASE_MAX=${SPARK_LEASE_MAX:-20}; LU=${SPARK_LEASE_UNIT_S:-60}
+IDLE_N=${SPARK_IDLE_N:-3}; IDLE_LOAD=${SPARK_IDLE_LOAD:-10}; DRAIN_MAX=${SPARK_DRAIN_MAX:-300}; IDLE_MAX=${SPARK_IDLE_MAX:-2700}
+BOARD=${SPARK_BOARD:-$HOME/handoffs/BOARD.md} # overrides: tests only
+mkdir -p "$WR"
+now() { date -u +%FT%TZ; }
+esc() { printf '%s' "$1" | tr '\n\t' ' ' | sed 's/\\/\\\\/g; s/"/\\"/g'; }
+age() { echo $(( $(date +%s) - $(stat -c %Y "$1" 2>/dev/null || date +%s) )); }
+
+# openers FILE: the processes that have FILE open right now (a lock set by a flock that has since
+# exited lives on in whoever inherited the open file), up to 5, as "pid cmd"
+openers() {
+ n=0; seen=" "
+ for f in /proc/[0-9]*/fd/*; do
+ [ "$(readlink "$f" 2>/dev/null)" = "$1" ] || continue
+ p=${f#/proc/}; p=${p%%/*}
+ case $seen in *" $p "*) continue ;; esac
+ seen="$seen$p "; n=$((n + 1)); [ $n -le 5 ] || continue
+ printf '%spid %s %s' "$([ $n -gt 1 ] && echo '; ')" "$p" "$(ps -o args= -p "$p" 2>/dev/null | cut -c1-70)"
+ done
+ [ $n -gt 0 ] || printf 'none found'
+ [ $n -le 5 ] || printf '+%s more' $((n - 5))
+}
+# holders LOCKFILE: who holds the lock (kernel lock table) and who is queued on it, with ages
+holders() {
+ ino=$(stat -c %i "$1" 2>/dev/null) || return 0
+ grep -E "^[0-9]+: +(-> +)?FLOCK +[A-Z]+ +[A-Z]+ +[0-9]+ [0-9a-f]+:[0-9a-f]+:$ino " /proc/locks 2>/dev/null |
+ while read -r _ a b c d e _; do
+ if [ "$a" = "->" ]; then q="queued"; m=$d; p=$e; else q="holds"; m=$c; p=$d; fi
+ [ "$m" = READ ] && m=shared || m=exclusive
+ a=$(ps -o args= -p "$p" 2>/dev/null | cut -c1-110); [ -n "$a" ] || a="(set by a finished flock; processes with $1 open now: $(openers "$1"))"
+ printf '%s %s pid %s (%ss) %s; ' "$q" "$m" "$p" "$(ps -o etimes= -p "$p" 2>/dev/null | tr -d ' ')" "$a"
+ done
+}
+waiters() {
+ own=$(cat "$WR/$(cur)/qm.pid" 2>/dev/null)
+ for f in "$W"/*; do [ -f "$f" ] || continue; [ "${f##*/}" = "$own" ] && continue
+ printf 'pid %s waiting %ss: %s; ' "${f##*/}" "$(age "$f")" "$(cut -c22-140 "$f")"
+ done
+}
+
+# state: one JSON object with the box state right now
+state() {
+ sr=$(tail -n 1 "$HOME/yardsticks/sensors/$(date +%F).csv" 2>/dev/null)
+ se=${sr%%,*}; sa=$(( $(date +%s) - ${se:-0} ))
+ g=$(nvidia-smi --query-gpu=utilization.gpu,power.draw --format=csv,noheader,nounits 2>/dev/null | tr -d ' ')
+ apps=$(nvidia-smi --query-compute-apps=pid,used_memory,process_name --format=csv,noheader 2>/dev/null | tr '\n' ';')
+ printf '{"utc": "%s", "loadavg": "%s", "mem_avail_kB": %s, "gpu_util_pct": "%s", "gpu_W": "%s",\n' \
+ "$(now)" "$(cat /proc/loadavg)" "$(awk '/MemAvailable/{print $2}' /proc/meminfo)" "${g%%,*}" "${g##*,}"
+ printf ' "gb10_lock_holders": "%s",\n "quiet_lock_holders": "%s",\n "quiet_waiters": "%s",\n "gpu_apps": "%s",\n' \
+ "$(esc "$(holders $G)")" "$(esc "$(holders $Q)")" "$(esc "$(waiters)")" "$(esc "$apps")"
+ printf ' "sensors_row": "%s", "sensors_row_age_s": %s}\n' "$(esc "$sr")" "$sa"
+}
+
+alive() { [ -n "${1:-}" ] && kill -0 "$1" 2>/dev/null; }
+cur() { cat "$WR/OPEN" 2>/dev/null; }
+# the waiting line for --wait: one ticket file per waiter, named <epoch ns>-<pid>; a dead waiter's ticket is dropped
+QD=$WR/QUEUE
+qclean() { for t in "$QD"/*; do [ -f "$t" ] || continue; alive "${t##*-}" || rm -f "$t"; done; }
+qhead() { ls "$QD" 2>/dev/null | sort | head -n 1; }
+qpos() { ls "$QD" 2>/dev/null | sort | grep -n -x -F "${1##*/}" | cut -d: -f1; }
+qlist() { ls "$QD" 2>/dev/null | sort | while read -r t; do echo " in line: $(cat "$QD/$t" 2>/dev/null) (pid ${t##*-})"; done; }
+hpid() { cat "$WR/$1/holder.pid" 2>/dev/null; }
+
+# Who may close a window without naming it. open records the shell that ran it ("opener",
+# pid:start time, so a reused pid does not count); a bare close is only for that shell's tree
+# or for a caller whose $SPARK_WINDOW is the window id (set by run). L162, 2026-10-20.
+pstat() { sed 's/^.*) //' "/proc/$1/stat" 2>/dev/null; } # fields from the state letter on
+ppid_of() { pstat "$1" | cut -d' ' -f2; }
+stime() { pstat "$1" | cut -d' ' -f20; }
+cmdl() { tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null; }
+# the shell that ran this command, looking past the subshell a $(...) makes (same command line)
+anchor() {
+ a=$PPID
+ while p=$(ppid_of "$a"); [ -n "$p" ] && [ "$p" -gt 1 ] && [ "$(cmdl "$a")" = "$(cmdl "$p")" ]; do a=$p; done
+ echo "$a"
+}
+in_tree() { # in_tree PID START: is that same process this one or one of its ancestors?
+ a=$$
+ while [ -n "$a" ] && [ "$a" -gt 1 ]; do
+ [ "$a" = "$1" ] && [ "$(stime "$a")" = "$2" ] && return 0
+ a=$(ppid_of "$a")
+ done
+ return 1
+}
+mine() { # mine ID: may this caller close window ID without naming it?
+ [ "${SPARK_WINDOW:-}" = "$1" ] && return 0
+ o=$(cat "$WR/$1/opener" 2>/dev/null)
+ [ -n "$o" ] && in_tree "${o%%:*}" "${o##*:}" && return 0
+ h=$(hpid "$1"); [ -n "$h" ] && in_tree "$h" "$(stime "$h")" && return 0
+ return 1
+}
+
+describe() {
+ d=$WR/$1
+ st=queued; [ -f "$d/held" ] && st=held
+ echo "window $1 name=$(cat "$d/name" 2>/dev/null) owner=$(cat "$d/owner" 2>/dev/null) gb10=$(cat "$d/gb10" 2>/dev/null || echo legacy-quiet-only) quiet=$(cat "$d/quiet" 2>/dev/null || echo exclusive) state=$st opened_request=$(cat "$d/requested" 2>/dev/null) holder_pid=$(hpid "$1") lease_min=$(cat "$d/lease" 2>/dev/null)"
+ [ -f "$d/held" ] && echo " held since $(cat "$d/held") ($(age "$d/held") s)"
+}
+
+# verdict ID: what a window's timings are worth (L405): NO VERDICT after a lease overrun, "shared machine"
+# when correctness jobs ran beside it after their 25 min cap, else "quiet machine"
+verdict() {
+ [ -f "$WR/$1/expired" ] && { echo "NO VERDICT: the lease ran out before close"; return; }
+ n=$(cat "$WR/$1/intrusions" 2>/dev/null | wc -l)
+ [ "$n" -gt 0 ] && { echo "shared machine: $n correctness job(s) ran beside it after waiting their cap"; return; }
+ echo "quiet machine"
+}
+board() { echo "$(date -u +%FT%H:%MZ) $1" >> "$BOARD" 2>/dev/null; }
+
+# called with the state lock held: drop a window whose holder is gone
+reap() {
+ id=$(cur); [ -n "$id" ] || return 0
+ alive "$(hpid "$id")" && return 0
+ why="holder process gone"; [ -f "$WR/$id/expired" ] && why="lease expired $(cat "$WR/$id/expired")"
+ [ -f "$WR/$id/gave-up" ] && why="never opened: $(cat "$WR/$id/gave-up")"
+ { printf '{"closed_by": "spark-window reap", "reason": "%s", "verdict": "%s", "state": ' "$(esc "$why")" "$(verdict "$id")"; state; echo '}'; } > "$WR/$id/close.json"
+ rm -f "$WR/OPEN"
+ echo "spark-window: closed stale window $id ($why)" >&2
+}
+
+cmd=${1:-status}; [ $# -gt 0 ] && shift
+case $cmd in
+open)
+ name=${1:?usage: spark-window open NAME [--ledger ID] [--lease MIN] [--gb10 exclusive|shared|none] [--quiet exclusive|none] [--wait]}; shift
+ ledger=""; lease=""; gb10=exclusive; quiet=exclusive; wait=0
+ while [ $# -gt 0 ]; do case $1 in --ledger) ledger=$2; shift 2 ;; --lease) lease=$2; shift 2 ;; --gb10) gb10=$2; shift 2 ;; --quiet) quiet=$2; shift 2 ;; --wait) wait=1; shift ;; *) echo "spark-window: unknown option $1" >&2; exit 2 ;; esac; done
+ case $gb10 in exclusive) gflag=-x ;; shared) gflag=-s ;; none) gflag= ;; *) echo "spark-window: --gb10 must be exclusive, shared or none" >&2; exit 2 ;; esac
+ case $quiet in exclusive) ;; none) [ "$gb10" != none ] || { echo "spark-window: --gb10 none with --quiet none would lock nothing" >&2; exit 2; } ;; *) echo "spark-window: --quiet must be exclusive or none" >&2; exit 2 ;; esac
+ # L405: exclusive locks are for short timing receipts only
+ excl=0; { [ "$gb10" = exclusive ] || [ "$quiet" = exclusive ]; } && excl=1
+ [ -n "$lease" ] || { [ $excl = 1 ] && lease=$LEASE_MAX || lease=90; }
+ case $lease in ''|*[!0-9]*|0) echo "spark-window: --lease must be a whole number of minutes" >&2; exit 2 ;; esac
+ if [ $excl = 1 ] && [ "$lease" -gt "$LEASE_MAX" ]; then
+ echo "spark-window: refused, --lease $lease: exclusive windows (chip or quiet) are at most $LEASE_MAX min (L405, Drake 2026-10-22)." >&2
+ echo " Split the measurement into windows of $LEASE_MAX min or less, or run it on the shared machine and label the receipt \"shared machine\"." >&2
+ echo " Value checks (tokens, routes, outputs) need no exclusive lock: --gb10 shared --quiet none, or no window at all." >&2
+ exit 2
+ fi
+ RES=$HOME/.local/state/aien-coordinator/CHIP-RESERVED
+ # Drake 2026-10-24 ("be coworkers"): the reservation file is a courtesy note, not a gate. Say what you run on the BOARD, let anyone mid-measurement finish, step aside when asked. No refusal here.
+ if [ -f "$RES" ] && ! head -1 "$RES" | cut -d"(" -f1 | tr " " "\n" | grep -qx "${ledger:-none}"; then echo "spark-window: note, other lanes also want the chip ($(head -1 "$RES" | cut -d'(' -f1 | xargs)). Courtesy rule (Drake 2026-10-24): post what you run and for how long on ~/handoffs/BOARD.md, let anyone mid-measurement finish, step aside if asked." >&2; fi
+ # --wait: take a numbered ticket and wait in line; the oldest live ticket opens next. Without --wait
+ # an open is refused while a window is open or anyone holds a ticket, so nobody jumps the line.
+ mkdir -p "$QD"; tk=""
+ if [ "$wait" = 1 ]; then
+ tk=$QD/$(date +%s%N)-$$; printf '%s owner=%s since=%s\n' "$name" "${ledger:-$(whoami)@pid$PPID}" "$(now)" > "$tk"
+ trap 'rm -f "$tk"' EXIT; trap 'exit 130' INT TERM
+ fi
+ tq=$(date +%s); lastq=$tq
+ while :; do
+ exec 7>"$WR/.state.lock"; flock 7
+ reap; qclean
+ first=$(qhead)
+ if [ -z "$(cur)" ] && { [ -z "$first" ] || [ "$QD/$first" = "$tk" ]; }; then break; fi
+ if [ -z "$tk" ]; then
+ echo "spark-window: refused, a window is already open or queued:" >&2
+ [ -n "$(cur)" ] && describe "$(cur)" >&2
+ qlist >&2
+ echo "Wait in line with: spark-window open $name --wait ... (first come, first served)" >&2
+ exit 3
+ fi
+ flock -u 7; exec 7>&-
+ if [ $(( $(date +%s) - lastq )) -ge 60 ]; then
+ lastq=$(date +%s)
+ echo "spark-window: in line $(( lastq - tq )) s, place $(qpos "$tk"); open now: $(cur || true)" >&2
+ fi
+ sleep 2
+ done
+ [ -n "$tk" ] && { rm -f "$tk"; trap - EXIT INT TERM; }
+ id=$(date -u +%Y%m%dT%H%M%SZ)-$(od -An -N3 -tx1 /dev/urandom | tr -d ' \n')
+ d=$WR/$id; mkdir -p "$d"
+ oa=$(anchor); echo "$oa:$(stime "$oa")" > "$d/opener"
+ echo "$name" > "$d/name"; echo "${ledger:-${SPARK_WINDOW_OWNER:-$(whoami)@pid$PPID}}" > "$d/owner"
+ echo "$lease" > "$d/lease"; now > "$d/requested"
+ echo "$id" > "$WR/OPEN.tmp" && mv -f "$WR/OPEN.tmp" "$WR/OPEN"
+ echo "$gb10" > "$d/gb10"
+ echo "$quiet" > "$d/quiet"
+ setsid "$0" _hold "$id" 7>&- > "$d/holder.log" 2>&1 < /dev/null &
+ echo $! > "$d/holder.pid"
+ flock -u 7; exec 7>&-
+ t0=$(date +%s); last=$t0
+ while [ ! -f "$d/held" ]; do
+ if ! alive "$(hpid "$id")"; then
+ if [ -f "$d/gave-up" ]; then echo "spark-window: not opened: $(cat "$d/gave-up")" >&2; rm -f "$WR/OPEN"; exit 4; fi
+ echo "spark-window: holder died before taking the lock; see $d/holder.log" >&2; rm -f "$WR/OPEN"; exit 1
+ fi
+ if [ $(( $(date +%s) - last )) -ge 60 ]; then
+ last=$(date +%s)
+ echo "spark-window: waiting $(( last - t0 )) s: $(cut -c22- "$d/phase" 2>/dev/null). gb10: $(holders $G) | quiet: $(holders $Q) | waiters: $(waiters)" >&2
+ fi
+ sleep 1
+ done
+ { printf '{"window_id": "%s", "name": "%s", "owner": "%s", "lease_min": %s, "gb10": "%s", "waited_s": %s, "state": ' \
+ "$id" "$(esc "$name")" "$(esc "$(cat "$d/owner")")" "$lease" "$gb10" "$(( $(date +%s) - t0 ))"; state; echo '}'; } > "$d/open.json"
+ echo "spark-window: window $id open, chip lock $gb10, quiet lock $quiet (waited $(( $(date +%s) - t0 )) s); box state in $d/open.json" >&2
+ echo "$id"
+ ;;
+_hold)
+ # Takes the window's locks, then holds them until close or lease end.
+ # Order and rules (L154, L189, L322, L405):
+ # 0. (quiet exclusive only, L405) Wait, holding NOTHING, until the machine is quiet anyway: at most
+ # $IDLE_N jobs hold or wait on the quiet lock and the 1-min load is at most $IDLE_LOAD. A window
+ # opens when the machine is idle, it does not stop everyone. Give up after $IDLE_MAX s (exit 4).
+ # 1. Wait for the chip holding NOTHING (a window waiting for the chip must not block CPU timings).
+ # 2. With the chip in hand, raise the GATE (exclusive on $GATE). quiet-build and quiet-measure pass
+ # through it (shared, for a moment) before they take the quiet lock, so no NEW taker arrives while
+ # we wait; the ones already holding the quiet lock finish normally (L322).
+ # 3. Drain: wait for the quiet lock while KEEPING the chip, in 5 s polls, for at most $DRAIN_MAX s.
+ # If it has not drained by then, let everything go (builds pass) and go back to step 0.
+ # 4. Deadlock guard: the measurement tools take quiet THEN chip. If a process queued on the chip
+ # has the quiet lock file open, it waits for our chip while we wait for its quiet lock: let the
+ # chip go (gate stays up), wait for the quiet lock holding nothing else (same drain cap), then TRY
+ # the chip without blocking (a try cannot deadlock). If the try fails, let quiet go and start again.
+ # 5. Hold until close or lease end. Lease end (L405): let go, write NO VERDICT, post on the board.
+ # --quiet none: chip only, no quiet lock, no gate, no idle wait (value checks, not timings).
+ id=$1; d=$WR/$id; lease=$(cat "$d/lease"); mode=$(cat "$d/gb10" 2>/dev/null || echo legacy); qmode=$(cat "$d/quiet" 2>/dev/null || echo exclusive)
+ echo $$ > "$d/holder.pid.tmp" && mv -f "$d/holder.pid.tmp" "$d/holder.pid"
+ case $mode in exclusive) gf=-x ;; shared) gf=-s ;; *) gf= ;; esac
+ phase() { echo "$(now) $1" > "$d/phase"; }
+ # qjobs: rows (holders and waiters) on the quiet lock in the kernel lock table
+ qjobs() { qi=$(stat -c %i "$Q" 2>/dev/null) || { echo 0; return; }; grep -cE "^[0-9]+: +(-> +)?FLOCK +[A-Z]+ +[A-Z]+ +[0-9]+ [0-9a-f]+:[0-9a-f]+:$qi " /proc/locks 2>/dev/null; }
+ load1() { cut -d. -f1 /proc/loadavg; }
+ t_idle0=$(date +%s)
+ wait_idle() {
+ while :; do
+ n=$(qjobs); l=$(load1)
+ [ "$n" -le "$IDLE_N" ] && [ "$l" -le "$IDLE_LOAD" ] && return 0
+ if [ $(( $(date +%s) - t_idle0 )) -ge "$IDLE_MAX" ]; then
+ echo "the machine was never quiet in ${IDLE_MAX}s ($n jobs on the quiet lock, max $IDLE_N; load $l, max $IDLE_LOAD). Split the measurement or run it on the shared machine and label it \"shared machine\"." > "$d/gave-up"
+ phase "gave up: machine never quiet"; exit 4
+ fi
+ phase "waiting for a quiet machine, holding nothing: $n jobs on the quiet lock (max $IDLE_N), load $l (max $IDLE_LOAD)"
+ sleep 5 8>&- 9>&- 6>&-
+ done
+ }
+ # drain: wait for the quiet lock (fd 8) at most DRAIN_MAX s; with $1=guard, stop early when the deadlock guard fires
+ drain() {
+ ds=$(date +%s); yield=0
+ while [ $(( $(date +%s) - ds )) -lt "$DRAIN_MAX" ]; do
+ flock -w 5 -x 8 && return 0
+ if [ "${1:-}" = guard ] && [ -n "$gf" ] && chip_waiter_holds_quiet; then yield=1; return 1; fi
+ done
+ return 1
+ }
+ # chip_waiter_holds_quiet: some process queued on the chip lock has the quiet lock file open
+ chip_waiter_holds_quiet() {
+ cino=$(stat -c %i "$G" 2>/dev/null) || return 1
+ for p in $(awk -v i="$cino" '$2=="->" { split($7, a, ":"); if (a[3] == i) print $6 }' /proc/locks 2>/dev/null); do
+ for f in /proc/$p/fd/*; do [ "$(readlink "$f" 2>/dev/null)" = "$Q" ] && return 0; done
+ done
+ return 1
+ }
+ # legacy: a window opened by the previous version runs _hold under quiet-measure, which already
+ # holds the quiet lock for it; taking it again here would wait on itself.
+ if [ "$mode" != legacy ]; then
+ [ -n "$gf" ] && exec 9>>"$G"
+ if [ "$qmode" = none ]; then
+ phase "waiting for the chip lock ($mode, no quiet lock)"; flock $gf 9; tries=1
+ else
+ exec 8>>"$Q"; mkdir -p "$(dirname "$GATE")"; [ -e "$GATE" ] || { : > "$GATE"; chmod 666 "$GATE"; } 2>/dev/null; exec 6>>"$GATE"
+ tries=0
+ while :; do
+ tries=$((tries + 1))
+ wait_idle
+ if [ -n "$gf" ]; then phase "waiting for the chip lock ($mode)"; flock $gf 9; fi
+ flock -x 6
+ flock -n -x 8 && break
+ phase "chip held, gate up, draining the quiet lock for at most ${DRAIN_MAX}s (try $tries)"
+ drain guard && break
+ if [ $yield = 1 ]; then
+ flock -u 9; yields=$((${yields:-0} + 1)); echo "$yields" > "$d/yields"
+ phase "chip let go: a process waiting for the chip holds the quiet lock (try $tries)"
+ drain && { flock -n $gf 9 && break; }
+ fi
+ flock -u 8; flock -u 6; [ -n "$gf" ] && flock -u 9
+ echo "$(now) try $tries: quiet lock did not drain in ${DRAIN_MAX}s, let everything go" >> "$d/backoffs"
+ phase "quiet lock did not drain in ${DRAIN_MAX}s: let everything go so builds pass, back to waiting for a quiet machine (try $tries)"
+ sleep 2 8>&- 9>&- 6>&-
+ done
+ flock -u 6
+ fi
+ echo "$tries" > "$d/tries"
+ fi
+ phase "holding"
+ now > "$d/held"
+ end=$(( $(date +%s) + lease * LU ))
+ while [ ! -f "$d/close-request" ]; do
+ if [ "$(date +%s)" -ge "$end" ]; then
+ now > "$d/expired"
+ echo "NO VERDICT: the lease of $lease min ran out before close; timings from this window are not valid (L405)" > "$d/verdict"
+ echo "lease of $lease min ran out" >&2
+ board "spark-window to $(cat "$d/owner" 2>/dev/null): window $id ($(cat "$d/name" 2>/dev/null)) ran past its $lease min lease. Its locks are let go and its timings get NO VERDICT (L405). Split long measurements into windows of $LEASE_MAX min or less."
+ exit 0
+ fi
+ sleep 2 8>&- 9>&- 6>&-
+ done
+ exit 0
+ ;;
+run)
+ id=$(cur)
+ if [ -z "$id" ] || [ ! -f "$WR/$id/held" ] || ! alive "$(hpid "$id")"; then echo "spark-window: no open window holds its locks; run spark-window open NAME first" >&2; exit 1; fi
+ [ $# -gt 0 ] || { echo "usage: spark-window run CMD..." >&2; exit 2; }
+ case $(cat "$WR/$id/gb10" 2>/dev/null) in exclusive|shared) AIEN_GB10_LOCK_HELD=1; export AIEN_GB10_LOCK_HELD ;; esac
+ SPARK_WINDOW=$id SPARK_WINDOW_DIR=$WR/$id exec "$@"
+ ;;
+id)
+ id=$(cur)
+ [ -n "$id" ] && [ -f "$WR/$id/held" ] && alive "$(hpid "$id")" && { echo "$id"; exit 0; }
+ exit 1
+ ;;
+close)
+ exec 7>"$WR/.state.lock"; flock 7
+ named=${1:-}; id=${named:-$(cur)}
+ case $id in */*|.*) echo "spark-window: not a window id: $id" >&2; exit 2 ;; esac
+ [ -n "$id" ] && [ -d "$WR/$id" ] || { echo "spark-window: no window to close" >&2; exit 1; }
+ [ -f "$WR/$id/close.json" ] && { echo "spark-window: window $id is already closed" >&2; exit 1; }
+ # A bare close is not allowed to end somebody else's window (L129's finishing script closed
+ # L159's window, whose own bare close then closed L127's queued one).
+ if [ -z "$named" ] && ! mine "$id"; then
+ echo "spark-window: refused, the open window is not yours (you did not open it from this shell, and SPARK_WINDOW is ${SPARK_WINDOW:-unset}):" >&2
+ describe "$id" >&2
+ echo "Close your own window by id (spark-window close <ID>); this one is closed by its owner or when its lease runs out." >&2
+ exit 3
+ fi
+ d=$WR/$id; h=$(hpid "$id")
+ now > "$d/close-request"
+ # A holder still waiting for its locks holds nothing: stop it (its own process group, from setsid).
+ [ -f "$d/held" ] || { alive "$h" && kill -- -"$h" 2>/dev/null; why_pre="closed while still waiting for its locks"; }
+ while alive "$h"; do sleep 1; done
+ why=${why_pre:-closed}; [ -f "$d/expired" ] && why="lease expired $(cat "$d/expired") before close"
+ { printf '{"window_id": "%s", "closed_by": "spark-window close", "reason": "%s", "verdict": "%s", "held_s": %s, "state": ' \
+ "$id" "$why" "$(esc "$(verdict "$id")")" "$(( $(date +%s) - $(stat -c %Y "$d/held" 2>/dev/null || date +%s) ))"; state; echo '}'; } > "$d/close.json"
+ [ "$(cur)" = "$id" ] && rm -f "$WR/OPEN"
+ echo "spark-window: verdict for its timings: $(verdict "$id")" >&2
+ echo "spark-window: window $id closed ($why). It holds:" >&2
+ ls "$d" | grep -E '\.json$' | sed 's/^/ /' >&2
+ ;;
+locks)
+ case ${1:-all} in gb10) holders $G ;; quiet) holders $Q ;; *) echo "quiet: $(holders $Q)"; echo "gb10: $(holders $G)" ;; esac
+ echo
+ ;;
+status)
+ id=$(cur)
+ if [ -n "$id" ]; then describe "$id"; alive "$(hpid "$id")" || echo " holder process is gone (next open reaps it)"; else echo "no window open"; fi
+ echo "quiet lock holders: $(holders $Q)"
+ echo "quiet waiters: $(waiters)"
+ echo "gb10 lock holders: $(holders $G)"
+ qclean; echo "waiting line (--wait):"; qlist
+ ;;
+*) sed -n '2,/^set -u/p' "$0"; exit 2 ;;
+esac
diff --git a/tools/ops/test-spark-window-starve.sh b/tools/ops/test-spark-window-starve.sh
new file mode 100755
index 0000000..8d4cd86
--- /dev/null
+++ b/tools/ops/test-spark-window-starve.sh
@@ -0,0 +1,57 @@
+#!/bin/sh
+# test-spark-window-starve.sh [SCRIPT]: L189 regression test for spark-window _hold.
+# A window must open even while the quiet lock is held shared by one holder after another
+# (builds and tests in turn) and while the chip lock is free. Uses only temp lock files and a
+# temp window root; never touches /tmp/aien-quiet.lock or /tmp/aien-gb10.lock.
+# case 1 (no contention): opens fast.
+# case 2 (shared quiet holders back to back, short gaps): opens within LIMIT seconds.
+# Exit 0 = all pass. Pass an older script path to see it fail (red).
+set -u
+S=${1:-$(dirname "$0")/spark-window}; LIMIT=${LIMIT:-60}
+T=$(mktemp -d /tmp/spark-window-starve.XXXXXX)
+export SPARK_WINDOWS_ROOT=$T/win SPARK_QUIET_LOCK=$T/quiet.lock SPARK_GB10_LOCK=$T/gb10.lock
+# The L405 gate path, want dir and board are temp too, and the idle check ignores the host load:
+# these temp locks have no other users, so the real machine load says nothing about them.
+export SPARK_QUIET_GATE=$T/quiet.gate SPARK_QUIET_WANT=$T/want.d SPARK_BOARD=$T/BOARD.md SPARK_IDLE_LOAD=100000
+: > "$SPARK_QUIET_LOCK"; : > "$SPARK_GB10_LOCK"
+pids=""
+cleanup() { for p in $pids; do kill "$p" 2>/dev/null; done; for h in "$T"/win/*/holder.pid; do [ -f "$h" ] && kill -- -"$(cat "$h")" 2>/dev/null; done; sleep 0.5; rm -rf "$T"; }
+trap cleanup EXIT
+fail=0
+opens_within() { # NAME SECONDS: run open, true if it prints a window id in time
+ ( "$S" open "$1" --lease 5 > "$T/open.out" 2> "$T/open.err" ) & op=$!
+ i=0; while [ $i -lt $(( $2 * 5 )) ]; do
+ [ -f "$SPARK_WINDOWS_ROOT/OPEN" ] && [ -f "$SPARK_WINDOWS_ROOT/$(cat "$SPARK_WINDOWS_ROOT/OPEN")/held" ] && { wait $op; return 0; }
+ sleep 0.2; i=$((i + 1)); done
+ return 1
+}
+close_it() { "$S" close "$(cat "$SPARK_WINDOWS_ROOT/OPEN" 2>/dev/null)" > /dev/null 2>&1; }
+
+if opens_within plain 10; then echo "PASS case 1: no contention opens"; close_it; else echo "FAIL case 1: no contention did not open"; fail=1; close_it; fi
+
+# Shared quiet holders back to back, like builds and tests in turn. A waiting exclusive lock can only
+# be won in a gap; the old _hold let it go again at once and almost never won it a second time.
+stream() { # SECONDS GAP: one shared holder after another, forever
+ ( while :; do flock -s "$SPARK_QUIET_LOCK" sleep "$1"; sleep "$2"; done ) & pids="$pids $!"
+}
+stop_streams() { for p in $pids; do kill "$p" 2>/dev/null; done; pids=""; sleep 1.2; }
+case_run() { # LABEL: open under the running streams
+ if opens_within "$1" "$LIMIT"; then echo "PASS $1: opened under shared quiet holders (tries $(cat "$SPARK_WINDOWS_ROOT/$(cat "$SPARK_WINDOWS_ROOT/OPEN")/tries" 2>/dev/null))"
+ else echo "FAIL $1: no window in $LIMIT s under shared quiet holders back to back"; fail=1; fi
+ close_it; stop_streams
+}
+stream 1.0 0
+case_run "case 2 one holder, no pause between holders"
+stream 0.9 0; stream 0.6 0
+case_run "case 3 two holders, no pause between holders"
+# chip busy too: the window must wait for the chip, then open once it is free (no deadlock, no early open)
+stream 1.0 0
+( flock -x "$SPARK_GB10_LOCK" sleep 6 ) & pids="$pids $!"; sleep 0.5; t0=$(date +%s)
+# the open time comes from the window's own held file, not from when this loop noticed it (the poll is slow on a loaded box)
+if opens_within "case 4 chip busy 6 s" "$LIMIT"; then
+ dt=$(( $(stat -c %Y "$SPARK_WINDOWS_ROOT/$(cat "$SPARK_WINDOWS_ROOT/OPEN")/held") - t0 ))
+ if [ $dt -ge 4 ]; then echo "PASS case 4 chip busy 6 s: opened only after the chip was free (window opened $dt s after the start)"
+ else echo "FAIL case 4 chip busy 6 s: opened while the chip was held ($dt s)"; fail=1; fi
+else echo "FAIL case 4 chip busy 6 s: no window in $LIMIT s"; fail=1; fi
+close_it; stop_streams
+exit $fail
diff --git a/tools/ops/test_spark_window_close.sh b/tools/ops/test_spark_window_close.sh
new file mode 100755
index 0000000..11d3cc8
--- /dev/null
+++ b/tools/ops/test_spark_window_close.sh
@@ -0,0 +1,86 @@
+#!/bin/sh
+# Offline test: a bare `spark-window close` must not close a window it does not own (L162).
+# Uses a scratch windows folder and scratch lock files; never touches the live windows.
+# Usage: tools/ops/test_spark_window_close.sh [path/to/spark-window]
+set -u
+here=$(cd "$(dirname "$0")" && pwd)
+SW=${1:-$here/spark-window}
+T=$(mktemp -d /tmp/spark-window-close-test.XXXXXX)
+SPARK_WINDOWS_ROOT=$T/windows SPARK_QUIET_LOCK=$T/quiet.lock SPARK_GB10_LOCK=$T/gb10.lock
+export SPARK_WINDOWS_ROOT SPARK_QUIET_LOCK SPARK_GB10_LOCK
+# The L405 gate path, want dir and board are temp too, and the idle check ignores the host load:
+# these temp locks have no other users, so the real machine load says nothing about them.
+export SPARK_QUIET_GATE=$T/quiet.gate SPARK_QUIET_WANT=$T/want.d SPARK_BOARD=$T/BOARD.md SPARK_IDLE_LOAD=100000
+unset SPARK_WINDOW
+pass=0; fail=0
+ok() { pass=$((pass + 1)); echo "ok $1"; }
+bad() { fail=$((fail + 1)); echo "FAIL $1"; }
+check() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (got '$2', want '$3')"; fi; }
+cleanup() {
+ for h in "$T"/windows/*/holder.pid; do [ -f "$h" ] && kill -- -"$(cat "$h")" 2>/dev/null; done
+ rm -rf "$T"
+}
+trap cleanup EXIT
+waitfor() { i=0; while [ ! -e "$1" ] && [ $i -lt 100 ]; do sleep 0.2; i=$((i + 1)); done; [ -e "$1" ]; }
+closed() { [ -f "$SPARK_WINDOWS_ROOT/$1/close.json" ]; }
+holder_alive() { kill -0 "$(cat "$SPARK_WINDOWS_ROOT/$1/holder.pid")" 2>/dev/null; }
+
+# Lane 1: its own script process. Opens inside $(...) like real lanes, waits for go1, then bare-closes.
+cat > "$T/lane1.sh" <<EOF
+id=\$("$SW" open lane1 --ledger L1 --gb10 none 2>/dev/null)
+echo "\$id" > "$T/id1"
+while [ ! -e "$T/go1" ]; do sleep 0.2; done
+"$SW" close > "$T/lane1.out" 2>&1
+echo \$? > "$T/lane1.rc"
+EOF
+sh "$T/lane1.sh" & lane1=$!
+waitfor "$T/id1" && [ -n "$(cat "$T/id1")" ] || { bad "lane 1 opened a window"; exit 1; }
+A=$(cat "$T/id1")
+ok "lane 1 opened window $A"
+check "window A is held" "$([ -f "$SPARK_WINDOWS_ROOT/$A/held" ] && echo yes)" yes
+
+# 1. A stranger's bare close is refused (exit 3), names the holder, and changes nothing.
+sh -c "\"$SW\" close" > "$T/stranger.out" 2>&1; rc=$?
+check "stranger bare close exits 3" "$rc" 3
+grep -q "$A" "$T/stranger.out" && grep -q 'owner=L1' "$T/stranger.out"; check "refusal prints the holder" "$?" 0
+check "window A still held after the refusal" "$(closed "$A" && echo closed || echo held)" held
+holder_alive "$A"; check "window A holder still alive" "$?" 0
+
+# 2. Wrong SPARK_WINDOW does not count as ownership.
+SPARK_WINDOW=20200101T000000Z-aaaaaa sh -c "\"$SW\" close" > /dev/null 2>&1; rc=$?
+check "bare close with another window's SPARK_WINDOW exits 3" "$rc" 3
+check "window A still held after wrong SPARK_WINDOW" "$(closed "$A" && echo closed || echo held)" held
+
+# 3. close with a bogus or unknown id touches nothing.
+sh -c "\"$SW\" close ../x" > /dev/null 2>&1; check "close ../x exits 2" "$?" 2
+sh -c "\"$SW\" close 20200101T000000Z-bbbbbb" > /dev/null 2>&1; check "close of an unknown id exits 1" "$?" 1
+check "window A still held after bad ids" "$(closed "$A" && echo closed || echo held)" held
+
+# 4. The owner's own bare close (same script, different subshell from the open) works.
+touch "$T/go1"; wait "$lane1"
+check "owner bare close exits 0" "$(cat "$T/lane1.rc")" 0
+check "window A closed by its owner" "$(closed "$A" && echo closed || echo held)" closed
+
+# 5. Incident replay: lane 2 opens B; lane 1's stale bare close (a new process, as a finishing
+# script after its lease ran out) must not close B; close A (already closed) by id must not either.
+B=$(sh -c "\"$SW\" open lane2 --ledger L2 --gb10 none 2>/dev/null"); [ -n "$B" ] || { bad "lane 2 opened a window"; exit 1; }
+ok "lane 2 opened window $B"
+sh "$T/lane1.sh" > /dev/null 2>&1 & stale=$! # a second lane-1 run: its open is refused (B is open), id empty
+sleep 1; touch "$T/go1"; wait "$stale"
+check "stale lane-1 bare close exits 3" "$(cat "$T/lane1.rc")" 3
+sh -c "\"$SW\" close" > /dev/null 2>&1; check "stale bare close exits 3" "$?" 3
+sh -c "\"$SW\" close $A" > /dev/null 2>&1; check "close of the already closed A exits 1" "$?" 1
+check "window B untouched" "$(closed "$B" && echo closed || echo held)" held
+holder_alive "$B"; check "window B holder alive" "$?" 0
+
+# 6. SPARK_WINDOW = the window id (what spark-window run sets) allows a bare close from anywhere.
+SPARK_WINDOW=$B sh -c "\"$SW\" close" > /dev/null 2>&1; check "bare close with SPARK_WINDOW=B exits 0" "$?" 0
+check "window B closed" "$(closed "$B" && echo closed || echo held)" closed
+
+# 7. close with an explicit id closes exactly that window, from any process.
+C=$(sh -c "\"$SW\" open lane3 --ledger L3 --gb10 none 2>/dev/null"); [ -n "$C" ] || { bad "lane 3 opened a window"; exit 1; }
+sh -c "\"$SW\" close $C" > /dev/null 2>&1; check "close <ID> exits 0" "$?" 0
+check "window C closed" "$(closed "$C" && echo closed || echo held)" closed
+
+echo "pass $pass fail $fail"
+[ "$fail" -eq 0 ]